PackageManagerService.java revision c5967e9862489024c932b0c7fcb84ed0af2a7fd7
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_DUPLICATE_PACKAGE; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_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_DISABLED_COMPONENTS; 63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 70import static android.content.pm.PackageManager.PERMISSION_DENIED; 71import static android.content.pm.PackageManager.PERMISSION_GRANTED; 72import static android.content.pm.PackageParser.isApkFile; 73import static android.os.Process.PACKAGE_INFO_GID; 74import static android.os.Process.SYSTEM_UID; 75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 76import static android.system.OsConstants.O_CREAT; 77import static android.system.OsConstants.O_RDWR; 78 79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 81import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 82import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 83import static com.android.internal.util.ArrayUtils.appendInt; 84import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 85import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 88import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 89import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 93 94import android.Manifest; 95import android.annotation.NonNull; 96import android.annotation.Nullable; 97import android.app.ActivityManager; 98import android.app.ActivityManagerNative; 99import android.app.AppGlobals; 100import android.app.IActivityManager; 101import android.app.admin.IDevicePolicyManager; 102import android.app.backup.IBackupManager; 103import android.content.BroadcastReceiver; 104import android.content.ComponentName; 105import android.content.Context; 106import android.content.IIntentReceiver; 107import android.content.Intent; 108import android.content.IntentFilter; 109import android.content.IntentSender; 110import android.content.IntentSender.SendIntentException; 111import android.content.ServiceConnection; 112import android.content.pm.ActivityInfo; 113import android.content.pm.ApplicationInfo; 114import android.content.pm.AppsQueryHelper; 115import android.content.pm.ComponentInfo; 116import android.content.pm.EphemeralApplicationInfo; 117import android.content.pm.EphemeralResolveInfo; 118import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 119import android.content.pm.FeatureInfo; 120import android.content.pm.IOnPermissionsChangeListener; 121import android.content.pm.IPackageDataObserver; 122import android.content.pm.IPackageDeleteObserver; 123import android.content.pm.IPackageDeleteObserver2; 124import android.content.pm.IPackageInstallObserver2; 125import android.content.pm.IPackageInstaller; 126import android.content.pm.IPackageManager; 127import android.content.pm.IPackageMoveObserver; 128import android.content.pm.IPackageStatsObserver; 129import android.content.pm.InstrumentationInfo; 130import android.content.pm.IntentFilterVerificationInfo; 131import android.content.pm.KeySet; 132import android.content.pm.PackageCleanItem; 133import android.content.pm.PackageInfo; 134import android.content.pm.PackageInfoLite; 135import android.content.pm.PackageInstaller; 136import android.content.pm.PackageManager; 137import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 138import android.content.pm.PackageManagerInternal; 139import android.content.pm.PackageParser; 140import android.content.pm.PackageParser.ActivityIntentInfo; 141import android.content.pm.PackageParser.PackageLite; 142import android.content.pm.PackageParser.PackageParserException; 143import android.content.pm.PackageStats; 144import android.content.pm.PackageUserState; 145import android.content.pm.ParceledListSlice; 146import android.content.pm.PermissionGroupInfo; 147import android.content.pm.PermissionInfo; 148import android.content.pm.ProviderInfo; 149import android.content.pm.ResolveInfo; 150import android.content.pm.ServiceInfo; 151import android.content.pm.Signature; 152import android.content.pm.UserInfo; 153import android.content.pm.VerificationParams; 154import android.content.pm.VerifierDeviceIdentity; 155import android.content.pm.VerifierInfo; 156import android.content.res.Resources; 157import android.graphics.Bitmap; 158import android.hardware.display.DisplayManager; 159import android.net.Uri; 160import android.os.Binder; 161import android.os.Build; 162import android.os.Bundle; 163import android.os.Debug; 164import android.os.Environment; 165import android.os.Environment.UserEnvironment; 166import android.os.FileUtils; 167import android.os.Handler; 168import android.os.IBinder; 169import android.os.Looper; 170import android.os.Message; 171import android.os.Parcel; 172import android.os.ParcelFileDescriptor; 173import android.os.Process; 174import android.os.RemoteCallbackList; 175import android.os.RemoteException; 176import android.os.ResultReceiver; 177import android.os.SELinux; 178import android.os.ServiceManager; 179import android.os.SystemClock; 180import android.os.SystemProperties; 181import android.os.Trace; 182import android.os.UserHandle; 183import android.os.UserManager; 184import android.os.storage.IMountService; 185import android.os.storage.MountServiceInternal; 186import android.os.storage.StorageEventListener; 187import android.os.storage.StorageManager; 188import android.os.storage.VolumeInfo; 189import android.os.storage.VolumeRecord; 190import android.security.KeyStore; 191import android.security.SystemKeyStore; 192import android.system.ErrnoException; 193import android.system.Os; 194import android.system.StructStat; 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.SomeArgs; 222import com.android.internal.os.Zygote; 223import com.android.internal.util.ArrayUtils; 224import com.android.internal.util.FastPrintWriter; 225import com.android.internal.util.FastXmlSerializer; 226import com.android.internal.util.IndentingPrintWriter; 227import com.android.internal.util.Preconditions; 228import com.android.server.EventLogTags; 229import com.android.server.FgThread; 230import com.android.server.IntentResolver; 231import com.android.server.LocalServices; 232import com.android.server.ServiceThread; 233import com.android.server.SystemConfig; 234import com.android.server.Watchdog; 235import com.android.server.pm.PermissionsState.PermissionState; 236import com.android.server.pm.Settings.DatabaseVersion; 237import com.android.server.pm.Settings.VersionInfo; 238import com.android.server.storage.DeviceStorageMonitorInternal; 239 240import dalvik.system.DexFile; 241import dalvik.system.VMRuntime; 242 243import libcore.io.IoUtils; 244import libcore.util.EmptyArray; 245 246import org.xmlpull.v1.XmlPullParser; 247import org.xmlpull.v1.XmlPullParserException; 248import org.xmlpull.v1.XmlSerializer; 249 250import java.io.BufferedInputStream; 251import java.io.BufferedOutputStream; 252import java.io.BufferedReader; 253import java.io.ByteArrayInputStream; 254import java.io.ByteArrayOutputStream; 255import java.io.File; 256import java.io.FileDescriptor; 257import java.io.FileNotFoundException; 258import java.io.FileOutputStream; 259import java.io.FileReader; 260import java.io.FilenameFilter; 261import java.io.IOException; 262import java.io.InputStream; 263import java.io.PrintWriter; 264import java.nio.charset.StandardCharsets; 265import java.security.MessageDigest; 266import java.security.NoSuchAlgorithmException; 267import java.security.PublicKey; 268import java.security.cert.CertificateEncodingException; 269import java.security.cert.CertificateException; 270import java.text.SimpleDateFormat; 271import java.util.ArrayList; 272import java.util.Arrays; 273import java.util.Collection; 274import java.util.Collections; 275import java.util.Comparator; 276import java.util.Date; 277import java.util.Iterator; 278import java.util.List; 279import java.util.Map; 280import java.util.Objects; 281import java.util.Set; 282import java.util.concurrent.CountDownLatch; 283import java.util.concurrent.TimeUnit; 284import java.util.concurrent.atomic.AtomicBoolean; 285import java.util.concurrent.atomic.AtomicInteger; 286import java.util.concurrent.atomic.AtomicLong; 287 288/** 289 * Keep track of all those .apks everywhere. 290 * 291 * This is very central to the platform's security; please run the unit 292 * tests whenever making modifications here: 293 * 294runtest -c android.content.pm.PackageManagerTests frameworks-core 295 * 296 * {@hide} 297 */ 298public class PackageManagerService extends IPackageManager.Stub { 299 static final String TAG = "PackageManager"; 300 static final boolean DEBUG_SETTINGS = false; 301 static final boolean DEBUG_PREFERRED = false; 302 static final boolean DEBUG_UPGRADE = false; 303 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 304 private static final boolean DEBUG_BACKUP = false; 305 private static final boolean DEBUG_INSTALL = false; 306 private static final boolean DEBUG_REMOVE = false; 307 private static final boolean DEBUG_BROADCASTS = false; 308 private static final boolean DEBUG_SHOW_INFO = false; 309 private static final boolean DEBUG_PACKAGE_INFO = false; 310 private static final boolean DEBUG_INTENT_MATCHING = false; 311 private static final boolean DEBUG_PACKAGE_SCANNING = false; 312 private static final boolean DEBUG_VERIFY = false; 313 private static final boolean DEBUG_DEXOPT = false; 314 private static final boolean DEBUG_ABI_SELECTION = false; 315 private static final boolean DEBUG_EPHEMERAL = false; 316 private static final boolean DEBUG_TRIAGED_MISSING = false; 317 318 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 319 320 private static final int RADIO_UID = Process.PHONE_UID; 321 private static final int LOG_UID = Process.LOG_UID; 322 private static final int NFC_UID = Process.NFC_UID; 323 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 324 private static final int SHELL_UID = Process.SHELL_UID; 325 326 // Cap the size of permission trees that 3rd party apps can define 327 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 328 329 // Suffix used during package installation when copying/moving 330 // package apks to install directory. 331 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 332 333 static final int SCAN_NO_DEX = 1<<1; 334 static final int SCAN_FORCE_DEX = 1<<2; 335 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 336 static final int SCAN_NEW_INSTALL = 1<<4; 337 static final int SCAN_NO_PATHS = 1<<5; 338 static final int SCAN_UPDATE_TIME = 1<<6; 339 static final int SCAN_DEFER_DEX = 1<<7; 340 static final int SCAN_BOOTING = 1<<8; 341 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 342 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 343 static final int SCAN_REPLACING = 1<<11; 344 static final int SCAN_REQUIRE_KNOWN = 1<<12; 345 static final int SCAN_MOVE = 1<<13; 346 static final int SCAN_INITIAL = 1<<14; 347 348 static final int REMOVE_CHATTY = 1<<16; 349 350 private static final int[] EMPTY_INT_ARRAY = new int[0]; 351 352 /** 353 * Timeout (in milliseconds) after which the watchdog should declare that 354 * our handler thread is wedged. The usual default for such things is one 355 * minute but we sometimes do very lengthy I/O operations on this thread, 356 * such as installing multi-gigabyte applications, so ours needs to be longer. 357 */ 358 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 359 360 /** 361 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 362 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 363 * settings entry if available, otherwise we use the hardcoded default. If it's been 364 * more than this long since the last fstrim, we force one during the boot sequence. 365 * 366 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 367 * one gets run at the next available charging+idle time. This final mandatory 368 * no-fstrim check kicks in only of the other scheduling criteria is never met. 369 */ 370 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 371 372 /** 373 * Whether verification is enabled by default. 374 */ 375 private static final boolean DEFAULT_VERIFY_ENABLE = true; 376 377 /** 378 * The default maximum time to wait for the verification agent to return in 379 * milliseconds. 380 */ 381 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 382 383 /** 384 * The default response for package verification timeout. 385 * 386 * This can be either PackageManager.VERIFICATION_ALLOW or 387 * PackageManager.VERIFICATION_REJECT. 388 */ 389 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 390 391 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 392 393 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 394 DEFAULT_CONTAINER_PACKAGE, 395 "com.android.defcontainer.DefaultContainerService"); 396 397 private static final String KILL_APP_REASON_GIDS_CHANGED = 398 "permission grant or revoke changed gids"; 399 400 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 401 "permissions revoked"; 402 403 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 404 405 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 406 407 /** Permission grant: not grant the permission. */ 408 private static final int GRANT_DENIED = 1; 409 410 /** Permission grant: grant the permission as an install permission. */ 411 private static final int GRANT_INSTALL = 2; 412 413 /** Permission grant: grant the permission as a runtime one. */ 414 private static final int GRANT_RUNTIME = 3; 415 416 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 417 private static final int GRANT_UPGRADE = 4; 418 419 /** Canonical intent used to identify what counts as a "web browser" app */ 420 private static final Intent sBrowserIntent; 421 static { 422 sBrowserIntent = new Intent(); 423 sBrowserIntent.setAction(Intent.ACTION_VIEW); 424 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 425 sBrowserIntent.setData(Uri.parse("http:")); 426 } 427 428 final ServiceThread mHandlerThread; 429 430 final PackageHandler mHandler; 431 432 /** 433 * Messages for {@link #mHandler} that need to wait for system ready before 434 * being dispatched. 435 */ 436 private ArrayList<Message> mPostSystemReadyMessages; 437 438 final int mSdkVersion = Build.VERSION.SDK_INT; 439 440 final Context mContext; 441 final boolean mFactoryTest; 442 final boolean mOnlyCore; 443 final DisplayMetrics mMetrics; 444 final int mDefParseFlags; 445 final String[] mSeparateProcesses; 446 final boolean mIsUpgrade; 447 448 /** The location for ASEC container files on internal storage. */ 449 final String mAsecInternalPath; 450 451 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 452 // LOCK HELD. Can be called with mInstallLock held. 453 @GuardedBy("mInstallLock") 454 final Installer mInstaller; 455 456 /** Directory where installed third-party apps stored */ 457 final File mAppInstallDir; 458 final File mEphemeralInstallDir; 459 460 /** 461 * Directory to which applications installed internally have their 462 * 32 bit native libraries copied. 463 */ 464 private File mAppLib32InstallDir; 465 466 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 467 // apps. 468 final File mDrmAppPrivateInstallDir; 469 470 // ---------------------------------------------------------------- 471 472 // Lock for state used when installing and doing other long running 473 // operations. Methods that must be called with this lock held have 474 // the suffix "LI". 475 final Object mInstallLock = new Object(); 476 477 // ---------------------------------------------------------------- 478 479 // Keys are String (package name), values are Package. This also serves 480 // as the lock for the global state. Methods that must be called with 481 // this lock held have the prefix "LP". 482 @GuardedBy("mPackages") 483 final ArrayMap<String, PackageParser.Package> mPackages = 484 new ArrayMap<String, PackageParser.Package>(); 485 486 // Tracks available target package names -> overlay package paths. 487 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 488 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 489 490 /** 491 * Tracks new system packages [received in an OTA] that we expect to 492 * find updated user-installed versions. Keys are package name, values 493 * are package location. 494 */ 495 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 496 497 /** 498 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 499 */ 500 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 501 /** 502 * Whether or not system app permissions should be promoted from install to runtime. 503 */ 504 boolean mPromoteSystemApps; 505 506 final Settings mSettings; 507 boolean mRestoredSettings; 508 509 // System configuration read by SystemConfig. 510 final int[] mGlobalGids; 511 final SparseArray<ArraySet<String>> mSystemPermissions; 512 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 513 514 // If mac_permissions.xml was found for seinfo labeling. 515 boolean mFoundPolicyFile; 516 517 // If a recursive restorecon of /data/data/<pkg> is needed. 518 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 519 520 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 521 522 public static final class SharedLibraryEntry { 523 public final String path; 524 public final String apk; 525 526 SharedLibraryEntry(String _path, String _apk) { 527 path = _path; 528 apk = _apk; 529 } 530 } 531 532 // Currently known shared libraries. 533 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 534 new ArrayMap<String, SharedLibraryEntry>(); 535 536 // All available activities, for your resolving pleasure. 537 final ActivityIntentResolver mActivities = 538 new ActivityIntentResolver(); 539 540 // All available receivers, for your resolving pleasure. 541 final ActivityIntentResolver mReceivers = 542 new ActivityIntentResolver(); 543 544 // All available services, for your resolving pleasure. 545 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 546 547 // All available providers, for your resolving pleasure. 548 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 549 550 // Mapping from provider base names (first directory in content URI codePath) 551 // to the provider information. 552 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 553 new ArrayMap<String, PackageParser.Provider>(); 554 555 // Mapping from instrumentation class names to info about them. 556 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 557 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 558 559 // Mapping from permission names to info about them. 560 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 561 new ArrayMap<String, PackageParser.PermissionGroup>(); 562 563 // Packages whose data we have transfered into another package, thus 564 // should no longer exist. 565 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 566 567 // Broadcast actions that are only available to the system. 568 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 569 570 /** List of packages waiting for verification. */ 571 final SparseArray<PackageVerificationState> mPendingVerification 572 = new SparseArray<PackageVerificationState>(); 573 574 /** Set of packages associated with each app op permission. */ 575 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 576 577 final PackageInstallerService mInstallerService; 578 579 private final PackageDexOptimizer mPackageDexOptimizer; 580 581 private AtomicInteger mNextMoveId = new AtomicInteger(); 582 private final MoveCallbacks mMoveCallbacks; 583 584 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 585 586 // Cache of users who need badging. 587 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 588 589 /** Token for keys in mPendingVerification. */ 590 private int mPendingVerificationToken = 0; 591 592 volatile boolean mSystemReady; 593 volatile boolean mSafeMode; 594 volatile boolean mHasSystemUidErrors; 595 596 ApplicationInfo mAndroidApplication; 597 final ActivityInfo mResolveActivity = new ActivityInfo(); 598 final ResolveInfo mResolveInfo = new ResolveInfo(); 599 ComponentName mResolveComponentName; 600 PackageParser.Package mPlatformPackage; 601 ComponentName mCustomResolverComponentName; 602 603 boolean mResolverReplaced = false; 604 605 private final @Nullable ComponentName mIntentFilterVerifierComponent; 606 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 607 608 private int mIntentFilterVerificationToken = 0; 609 610 /** Component that knows whether or not an ephemeral application exists */ 611 final ComponentName mEphemeralResolverComponent; 612 /** The service connection to the ephemeral resolver */ 613 final EphemeralResolverConnection mEphemeralResolverConnection; 614 615 /** Component used to install ephemeral applications */ 616 final ComponentName mEphemeralInstallerComponent; 617 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 618 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 619 620 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 621 = new SparseArray<IntentFilterVerificationState>(); 622 623 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 624 new DefaultPermissionGrantPolicy(this); 625 626 // List of packages names to keep cached, even if they are uninstalled for all users 627 private List<String> mKeepUninstalledPackages; 628 629 private static class IFVerificationParams { 630 PackageParser.Package pkg; 631 boolean replacing; 632 int userId; 633 int verifierUid; 634 635 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 636 int _userId, int _verifierUid) { 637 pkg = _pkg; 638 replacing = _replacing; 639 userId = _userId; 640 replacing = _replacing; 641 verifierUid = _verifierUid; 642 } 643 } 644 645 private interface IntentFilterVerifier<T extends IntentFilter> { 646 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 647 T filter, String packageName); 648 void startVerifications(int userId); 649 void receiveVerificationResponse(int verificationId); 650 } 651 652 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 653 private Context mContext; 654 private ComponentName mIntentFilterVerifierComponent; 655 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 656 657 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 658 mContext = context; 659 mIntentFilterVerifierComponent = verifierComponent; 660 } 661 662 private String getDefaultScheme() { 663 return IntentFilter.SCHEME_HTTPS; 664 } 665 666 @Override 667 public void startVerifications(int userId) { 668 // Launch verifications requests 669 int count = mCurrentIntentFilterVerifications.size(); 670 for (int n=0; n<count; n++) { 671 int verificationId = mCurrentIntentFilterVerifications.get(n); 672 final IntentFilterVerificationState ivs = 673 mIntentFilterVerificationStates.get(verificationId); 674 675 String packageName = ivs.getPackageName(); 676 677 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 678 final int filterCount = filters.size(); 679 ArraySet<String> domainsSet = new ArraySet<>(); 680 for (int m=0; m<filterCount; m++) { 681 PackageParser.ActivityIntentInfo filter = filters.get(m); 682 domainsSet.addAll(filter.getHostsList()); 683 } 684 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 685 synchronized (mPackages) { 686 if (mSettings.createIntentFilterVerificationIfNeededLPw( 687 packageName, domainsList) != null) { 688 scheduleWriteSettingsLocked(); 689 } 690 } 691 sendVerificationRequest(userId, verificationId, ivs); 692 } 693 mCurrentIntentFilterVerifications.clear(); 694 } 695 696 private void sendVerificationRequest(int userId, int verificationId, 697 IntentFilterVerificationState ivs) { 698 699 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 700 verificationIntent.putExtra( 701 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 702 verificationId); 703 verificationIntent.putExtra( 704 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 705 getDefaultScheme()); 706 verificationIntent.putExtra( 707 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 708 ivs.getHostsString()); 709 verificationIntent.putExtra( 710 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 711 ivs.getPackageName()); 712 verificationIntent.setComponent(mIntentFilterVerifierComponent); 713 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 714 715 UserHandle user = new UserHandle(userId); 716 mContext.sendBroadcastAsUser(verificationIntent, user); 717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 718 "Sending IntentFilter verification broadcast"); 719 } 720 721 public void receiveVerificationResponse(int verificationId) { 722 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 723 724 final boolean verified = ivs.isVerified(); 725 726 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 727 final int count = filters.size(); 728 if (DEBUG_DOMAIN_VERIFICATION) { 729 Slog.i(TAG, "Received verification response " + verificationId 730 + " for " + count + " filters, verified=" + verified); 731 } 732 for (int n=0; n<count; n++) { 733 PackageParser.ActivityIntentInfo filter = filters.get(n); 734 filter.setVerified(verified); 735 736 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 737 + " verified with result:" + verified + " and hosts:" 738 + ivs.getHostsString()); 739 } 740 741 mIntentFilterVerificationStates.remove(verificationId); 742 743 final String packageName = ivs.getPackageName(); 744 IntentFilterVerificationInfo ivi = null; 745 746 synchronized (mPackages) { 747 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 748 } 749 if (ivi == null) { 750 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 751 + verificationId + " packageName:" + packageName); 752 return; 753 } 754 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 755 "Updating IntentFilterVerificationInfo for package " + packageName 756 +" verificationId:" + verificationId); 757 758 synchronized (mPackages) { 759 if (verified) { 760 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 761 } else { 762 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 763 } 764 scheduleWriteSettingsLocked(); 765 766 final int userId = ivs.getUserId(); 767 if (userId != UserHandle.USER_ALL) { 768 final int userStatus = 769 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 770 771 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 772 boolean needUpdate = false; 773 774 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 775 // already been set by the User thru the Disambiguation dialog 776 switch (userStatus) { 777 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 778 if (verified) { 779 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 780 } else { 781 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 782 } 783 needUpdate = true; 784 break; 785 786 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 787 if (verified) { 788 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 789 needUpdate = true; 790 } 791 break; 792 793 default: 794 // Nothing to do 795 } 796 797 if (needUpdate) { 798 mSettings.updateIntentFilterVerificationStatusLPw( 799 packageName, updatedStatus, userId); 800 scheduleWritePackageRestrictionsLocked(userId); 801 } 802 } 803 } 804 } 805 806 @Override 807 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 808 ActivityIntentInfo filter, String packageName) { 809 if (!hasValidDomains(filter)) { 810 return false; 811 } 812 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 813 if (ivs == null) { 814 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 815 packageName); 816 } 817 if (DEBUG_DOMAIN_VERIFICATION) { 818 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 819 } 820 ivs.addFilter(filter); 821 return true; 822 } 823 824 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 825 int userId, int verificationId, String packageName) { 826 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 827 verifierUid, userId, packageName); 828 ivs.setPendingState(); 829 synchronized (mPackages) { 830 mIntentFilterVerificationStates.append(verificationId, ivs); 831 mCurrentIntentFilterVerifications.add(verificationId); 832 } 833 return ivs; 834 } 835 } 836 837 private static boolean hasValidDomains(ActivityIntentInfo filter) { 838 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 839 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 840 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 841 } 842 843 // Set of pending broadcasts for aggregating enable/disable of components. 844 static class PendingPackageBroadcasts { 845 // for each user id, a map of <package name -> components within that package> 846 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 847 848 public PendingPackageBroadcasts() { 849 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 850 } 851 852 public ArrayList<String> get(int userId, String packageName) { 853 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 854 return packages.get(packageName); 855 } 856 857 public void put(int userId, String packageName, ArrayList<String> components) { 858 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 859 packages.put(packageName, components); 860 } 861 862 public void remove(int userId, String packageName) { 863 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 864 if (packages != null) { 865 packages.remove(packageName); 866 } 867 } 868 869 public void remove(int userId) { 870 mUidMap.remove(userId); 871 } 872 873 public int userIdCount() { 874 return mUidMap.size(); 875 } 876 877 public int userIdAt(int n) { 878 return mUidMap.keyAt(n); 879 } 880 881 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 882 return mUidMap.get(userId); 883 } 884 885 public int size() { 886 // total number of pending broadcast entries across all userIds 887 int num = 0; 888 for (int i = 0; i< mUidMap.size(); i++) { 889 num += mUidMap.valueAt(i).size(); 890 } 891 return num; 892 } 893 894 public void clear() { 895 mUidMap.clear(); 896 } 897 898 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 899 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 900 if (map == null) { 901 map = new ArrayMap<String, ArrayList<String>>(); 902 mUidMap.put(userId, map); 903 } 904 return map; 905 } 906 } 907 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 908 909 // Service Connection to remote media container service to copy 910 // package uri's from external media onto secure containers 911 // or internal storage. 912 private IMediaContainerService mContainerService = null; 913 914 static final int SEND_PENDING_BROADCAST = 1; 915 static final int MCS_BOUND = 3; 916 static final int END_COPY = 4; 917 static final int INIT_COPY = 5; 918 static final int MCS_UNBIND = 6; 919 static final int START_CLEANING_PACKAGE = 7; 920 static final int FIND_INSTALL_LOC = 8; 921 static final int POST_INSTALL = 9; 922 static final int MCS_RECONNECT = 10; 923 static final int MCS_GIVE_UP = 11; 924 static final int UPDATED_MEDIA_STATUS = 12; 925 static final int WRITE_SETTINGS = 13; 926 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 927 static final int PACKAGE_VERIFIED = 15; 928 static final int CHECK_PENDING_VERIFICATION = 16; 929 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 930 static final int INTENT_FILTER_VERIFIED = 18; 931 932 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 933 934 // Delay time in millisecs 935 static final int BROADCAST_DELAY = 10 * 1000; 936 937 static UserManagerService sUserManager; 938 939 // Stores a list of users whose package restrictions file needs to be updated 940 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 941 942 final private DefaultContainerConnection mDefContainerConn = 943 new DefaultContainerConnection(); 944 class DefaultContainerConnection implements ServiceConnection { 945 public void onServiceConnected(ComponentName name, IBinder service) { 946 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 947 IMediaContainerService imcs = 948 IMediaContainerService.Stub.asInterface(service); 949 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 950 } 951 952 public void onServiceDisconnected(ComponentName name) { 953 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 954 } 955 } 956 957 // Recordkeeping of restore-after-install operations that are currently in flight 958 // between the Package Manager and the Backup Manager 959 static class PostInstallData { 960 public InstallArgs args; 961 public PackageInstalledInfo res; 962 963 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 964 args = _a; 965 res = _r; 966 } 967 } 968 969 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 970 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 971 972 // XML tags for backup/restore of various bits of state 973 private static final String TAG_PREFERRED_BACKUP = "pa"; 974 private static final String TAG_DEFAULT_APPS = "da"; 975 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 976 977 final @Nullable String mRequiredVerifierPackage; 978 final @Nullable String mRequiredInstallerPackage; 979 980 private final PackageUsage mPackageUsage = new PackageUsage(); 981 982 private class PackageUsage { 983 private static final int WRITE_INTERVAL 984 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 985 986 private final Object mFileLock = new Object(); 987 private final AtomicLong mLastWritten = new AtomicLong(0); 988 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 989 990 private boolean mIsHistoricalPackageUsageAvailable = true; 991 992 boolean isHistoricalPackageUsageAvailable() { 993 return mIsHistoricalPackageUsageAvailable; 994 } 995 996 void write(boolean force) { 997 if (force) { 998 writeInternal(); 999 return; 1000 } 1001 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1002 && !DEBUG_DEXOPT) { 1003 return; 1004 } 1005 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1006 new Thread("PackageUsage_DiskWriter") { 1007 @Override 1008 public void run() { 1009 try { 1010 writeInternal(); 1011 } finally { 1012 mBackgroundWriteRunning.set(false); 1013 } 1014 } 1015 }.start(); 1016 } 1017 } 1018 1019 private void writeInternal() { 1020 synchronized (mPackages) { 1021 synchronized (mFileLock) { 1022 AtomicFile file = getFile(); 1023 FileOutputStream f = null; 1024 try { 1025 f = file.startWrite(); 1026 BufferedOutputStream out = new BufferedOutputStream(f); 1027 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1028 StringBuilder sb = new StringBuilder(); 1029 for (PackageParser.Package pkg : mPackages.values()) { 1030 if (pkg.mLastPackageUsageTimeInMills == 0) { 1031 continue; 1032 } 1033 sb.setLength(0); 1034 sb.append(pkg.packageName); 1035 sb.append(' '); 1036 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1037 sb.append('\n'); 1038 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1039 } 1040 out.flush(); 1041 file.finishWrite(f); 1042 } catch (IOException e) { 1043 if (f != null) { 1044 file.failWrite(f); 1045 } 1046 Log.e(TAG, "Failed to write package usage times", e); 1047 } 1048 } 1049 } 1050 mLastWritten.set(SystemClock.elapsedRealtime()); 1051 } 1052 1053 void readLP() { 1054 synchronized (mFileLock) { 1055 AtomicFile file = getFile(); 1056 BufferedInputStream in = null; 1057 try { 1058 in = new BufferedInputStream(file.openRead()); 1059 StringBuffer sb = new StringBuffer(); 1060 while (true) { 1061 String packageName = readToken(in, sb, ' '); 1062 if (packageName == null) { 1063 break; 1064 } 1065 String timeInMillisString = readToken(in, sb, '\n'); 1066 if (timeInMillisString == null) { 1067 throw new IOException("Failed to find last usage time for package " 1068 + packageName); 1069 } 1070 PackageParser.Package pkg = mPackages.get(packageName); 1071 if (pkg == null) { 1072 continue; 1073 } 1074 long timeInMillis; 1075 try { 1076 timeInMillis = Long.parseLong(timeInMillisString); 1077 } catch (NumberFormatException e) { 1078 throw new IOException("Failed to parse " + timeInMillisString 1079 + " as a long.", e); 1080 } 1081 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1082 } 1083 } catch (FileNotFoundException expected) { 1084 mIsHistoricalPackageUsageAvailable = false; 1085 } catch (IOException e) { 1086 Log.w(TAG, "Failed to read package usage times", e); 1087 } finally { 1088 IoUtils.closeQuietly(in); 1089 } 1090 } 1091 mLastWritten.set(SystemClock.elapsedRealtime()); 1092 } 1093 1094 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1095 throws IOException { 1096 sb.setLength(0); 1097 while (true) { 1098 int ch = in.read(); 1099 if (ch == -1) { 1100 if (sb.length() == 0) { 1101 return null; 1102 } 1103 throw new IOException("Unexpected EOF"); 1104 } 1105 if (ch == endOfToken) { 1106 return sb.toString(); 1107 } 1108 sb.append((char)ch); 1109 } 1110 } 1111 1112 private AtomicFile getFile() { 1113 File dataDir = Environment.getDataDirectory(); 1114 File systemDir = new File(dataDir, "system"); 1115 File fname = new File(systemDir, "package-usage.list"); 1116 return new AtomicFile(fname); 1117 } 1118 } 1119 1120 class PackageHandler extends Handler { 1121 private boolean mBound = false; 1122 final ArrayList<HandlerParams> mPendingInstalls = 1123 new ArrayList<HandlerParams>(); 1124 1125 private boolean connectToService() { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1127 " DefaultContainerService"); 1128 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1129 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1130 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1131 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1132 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1133 mBound = true; 1134 return true; 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 return false; 1138 } 1139 1140 private void disconnectService() { 1141 mContainerService = null; 1142 mBound = false; 1143 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1144 mContext.unbindService(mDefContainerConn); 1145 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1146 } 1147 1148 PackageHandler(Looper looper) { 1149 super(looper); 1150 } 1151 1152 public void handleMessage(Message msg) { 1153 try { 1154 doHandleMessage(msg); 1155 } finally { 1156 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1157 } 1158 } 1159 1160 void doHandleMessage(Message msg) { 1161 switch (msg.what) { 1162 case INIT_COPY: { 1163 HandlerParams params = (HandlerParams) msg.obj; 1164 int idx = mPendingInstalls.size(); 1165 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1166 // If a bind was already initiated we dont really 1167 // need to do anything. The pending install 1168 // will be processed later on. 1169 if (!mBound) { 1170 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1171 System.identityHashCode(mHandler)); 1172 // If this is the only one pending we might 1173 // have to bind to the service again. 1174 if (!connectToService()) { 1175 Slog.e(TAG, "Failed to bind to media container service"); 1176 params.serviceError(); 1177 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1178 System.identityHashCode(mHandler)); 1179 if (params.traceMethod != null) { 1180 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1181 params.traceCookie); 1182 } 1183 return; 1184 } else { 1185 // Once we bind to the service, the first 1186 // pending request will be processed. 1187 mPendingInstalls.add(idx, params); 1188 } 1189 } else { 1190 mPendingInstalls.add(idx, params); 1191 // Already bound to the service. Just make 1192 // sure we trigger off processing the first request. 1193 if (idx == 0) { 1194 mHandler.sendEmptyMessage(MCS_BOUND); 1195 } 1196 } 1197 break; 1198 } 1199 case MCS_BOUND: { 1200 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1201 if (msg.obj != null) { 1202 mContainerService = (IMediaContainerService) msg.obj; 1203 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1204 System.identityHashCode(mHandler)); 1205 } 1206 if (mContainerService == null) { 1207 if (!mBound) { 1208 // Something seriously wrong since we are not bound and we are not 1209 // waiting for connection. Bail out. 1210 Slog.e(TAG, "Cannot bind to media container service"); 1211 for (HandlerParams params : mPendingInstalls) { 1212 // Indicate service bind error 1213 params.serviceError(); 1214 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1215 System.identityHashCode(params)); 1216 if (params.traceMethod != null) { 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1218 params.traceMethod, params.traceCookie); 1219 } 1220 return; 1221 } 1222 mPendingInstalls.clear(); 1223 } else { 1224 Slog.w(TAG, "Waiting to connect to media container service"); 1225 } 1226 } else if (mPendingInstalls.size() > 0) { 1227 HandlerParams params = mPendingInstalls.get(0); 1228 if (params != null) { 1229 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1230 System.identityHashCode(params)); 1231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1232 if (params.startCopy()) { 1233 // We are done... look for more work or to 1234 // go idle. 1235 if (DEBUG_SD_INSTALL) Log.i(TAG, 1236 "Checking for more work or unbind..."); 1237 // Delete pending install 1238 if (mPendingInstalls.size() > 0) { 1239 mPendingInstalls.remove(0); 1240 } 1241 if (mPendingInstalls.size() == 0) { 1242 if (mBound) { 1243 if (DEBUG_SD_INSTALL) Log.i(TAG, 1244 "Posting delayed MCS_UNBIND"); 1245 removeMessages(MCS_UNBIND); 1246 Message ubmsg = obtainMessage(MCS_UNBIND); 1247 // Unbind after a little delay, to avoid 1248 // continual thrashing. 1249 sendMessageDelayed(ubmsg, 10000); 1250 } 1251 } else { 1252 // There are more pending requests in queue. 1253 // Just post MCS_BOUND message to trigger processing 1254 // of next pending install. 1255 if (DEBUG_SD_INSTALL) Log.i(TAG, 1256 "Posting MCS_BOUND for next work"); 1257 mHandler.sendEmptyMessage(MCS_BOUND); 1258 } 1259 } 1260 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1261 } 1262 } else { 1263 // Should never happen ideally. 1264 Slog.w(TAG, "Empty queue"); 1265 } 1266 break; 1267 } 1268 case MCS_RECONNECT: { 1269 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1270 if (mPendingInstalls.size() > 0) { 1271 if (mBound) { 1272 disconnectService(); 1273 } 1274 if (!connectToService()) { 1275 Slog.e(TAG, "Failed to bind to media container service"); 1276 for (HandlerParams params : mPendingInstalls) { 1277 // Indicate service bind error 1278 params.serviceError(); 1279 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1280 System.identityHashCode(params)); 1281 } 1282 mPendingInstalls.clear(); 1283 } 1284 } 1285 break; 1286 } 1287 case MCS_UNBIND: { 1288 // If there is no actual work left, then time to unbind. 1289 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1290 1291 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1292 if (mBound) { 1293 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1294 1295 disconnectService(); 1296 } 1297 } else if (mPendingInstalls.size() > 0) { 1298 // There are more pending requests in queue. 1299 // Just post MCS_BOUND message to trigger processing 1300 // of next pending install. 1301 mHandler.sendEmptyMessage(MCS_BOUND); 1302 } 1303 1304 break; 1305 } 1306 case MCS_GIVE_UP: { 1307 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1308 HandlerParams params = mPendingInstalls.remove(0); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1310 System.identityHashCode(params)); 1311 break; 1312 } 1313 case SEND_PENDING_BROADCAST: { 1314 String packages[]; 1315 ArrayList<String> components[]; 1316 int size = 0; 1317 int uids[]; 1318 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1319 synchronized (mPackages) { 1320 if (mPendingBroadcasts == null) { 1321 return; 1322 } 1323 size = mPendingBroadcasts.size(); 1324 if (size <= 0) { 1325 // Nothing to be done. Just return 1326 return; 1327 } 1328 packages = new String[size]; 1329 components = new ArrayList[size]; 1330 uids = new int[size]; 1331 int i = 0; // filling out the above arrays 1332 1333 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1334 int packageUserId = mPendingBroadcasts.userIdAt(n); 1335 Iterator<Map.Entry<String, ArrayList<String>>> it 1336 = mPendingBroadcasts.packagesForUserId(packageUserId) 1337 .entrySet().iterator(); 1338 while (it.hasNext() && i < size) { 1339 Map.Entry<String, ArrayList<String>> ent = it.next(); 1340 packages[i] = ent.getKey(); 1341 components[i] = ent.getValue(); 1342 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1343 uids[i] = (ps != null) 1344 ? UserHandle.getUid(packageUserId, ps.appId) 1345 : -1; 1346 i++; 1347 } 1348 } 1349 size = i; 1350 mPendingBroadcasts.clear(); 1351 } 1352 // Send broadcasts 1353 for (int i = 0; i < size; i++) { 1354 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1355 } 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 break; 1358 } 1359 case START_CLEANING_PACKAGE: { 1360 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1361 final String packageName = (String)msg.obj; 1362 final int userId = msg.arg1; 1363 final boolean andCode = msg.arg2 != 0; 1364 synchronized (mPackages) { 1365 if (userId == UserHandle.USER_ALL) { 1366 int[] users = sUserManager.getUserIds(); 1367 for (int user : users) { 1368 mSettings.addPackageToCleanLPw( 1369 new PackageCleanItem(user, packageName, andCode)); 1370 } 1371 } else { 1372 mSettings.addPackageToCleanLPw( 1373 new PackageCleanItem(userId, packageName, andCode)); 1374 } 1375 } 1376 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1377 startCleaningPackages(); 1378 } break; 1379 case POST_INSTALL: { 1380 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1381 1382 PostInstallData data = mRunningInstalls.get(msg.arg1); 1383 mRunningInstalls.delete(msg.arg1); 1384 boolean deleteOld = false; 1385 1386 if (data != null) { 1387 InstallArgs args = data.args; 1388 PackageInstalledInfo res = data.res; 1389 1390 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1391 final String packageName = res.pkg.applicationInfo.packageName; 1392 res.removedInfo.sendBroadcast(false, true, false); 1393 Bundle extras = new Bundle(1); 1394 extras.putInt(Intent.EXTRA_UID, res.uid); 1395 1396 // Now that we successfully installed the package, grant runtime 1397 // permissions if requested before broadcasting the install. 1398 if ((args.installFlags 1399 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1400 && res.pkg.applicationInfo.targetSdkVersion 1401 >= Build.VERSION_CODES.M) { 1402 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1403 args.installGrantPermissions); 1404 } 1405 1406 synchronized (mPackages) { 1407 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1408 } 1409 1410 // Determine the set of users who are adding this 1411 // package for the first time vs. those who are seeing 1412 // an update. 1413 int[] firstUsers; 1414 int[] updateUsers = new int[0]; 1415 if (res.origUsers == null || res.origUsers.length == 0) { 1416 firstUsers = res.newUsers; 1417 } else { 1418 firstUsers = new int[0]; 1419 for (int i=0; i<res.newUsers.length; i++) { 1420 int user = res.newUsers[i]; 1421 boolean isNew = true; 1422 for (int j=0; j<res.origUsers.length; j++) { 1423 if (res.origUsers[j] == user) { 1424 isNew = false; 1425 break; 1426 } 1427 } 1428 if (isNew) { 1429 int[] newFirst = new int[firstUsers.length+1]; 1430 System.arraycopy(firstUsers, 0, newFirst, 0, 1431 firstUsers.length); 1432 newFirst[firstUsers.length] = user; 1433 firstUsers = newFirst; 1434 } else { 1435 int[] newUpdate = new int[updateUsers.length+1]; 1436 System.arraycopy(updateUsers, 0, newUpdate, 0, 1437 updateUsers.length); 1438 newUpdate[updateUsers.length] = user; 1439 updateUsers = newUpdate; 1440 } 1441 } 1442 } 1443 // don't broadcast for ephemeral installs/updates 1444 final boolean isEphemeral = isEphemeral(res.pkg); 1445 if (!isEphemeral) { 1446 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1447 extras, 0 /*flags*/, null /*targetPackage*/, 1448 null /*finishedReceiver*/, firstUsers); 1449 } 1450 final boolean update = res.removedInfo.removedPackage != null; 1451 if (update) { 1452 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1453 } 1454 if (!isEphemeral) { 1455 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1456 extras, 0 /*flags*/, null /*targetPackage*/, 1457 null /*finishedReceiver*/, updateUsers); 1458 } 1459 if (update) { 1460 if (!isEphemeral) { 1461 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1462 packageName, extras, 0 /*flags*/, 1463 null /*targetPackage*/, null /*finishedReceiver*/, 1464 updateUsers); 1465 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1466 null /*package*/, null /*extras*/, 0 /*flags*/, 1467 packageName /*targetPackage*/, 1468 null /*finishedReceiver*/, updateUsers); 1469 } 1470 1471 // treat asec-hosted packages like removable media on upgrade 1472 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1473 if (DEBUG_INSTALL) { 1474 Slog.i(TAG, "upgrading pkg " + res.pkg 1475 + " is ASEC-hosted -> AVAILABLE"); 1476 } 1477 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1478 ArrayList<String> pkgList = new ArrayList<String>(1); 1479 pkgList.add(packageName); 1480 sendResourcesChangedBroadcast(true, true, 1481 pkgList,uidArray, null); 1482 } 1483 } 1484 if (res.removedInfo.args != null) { 1485 // Remove the replaced package's older resources safely now 1486 deleteOld = true; 1487 } 1488 1489 // If this app is a browser and it's newly-installed for some 1490 // users, clear any default-browser state in those users 1491 if (firstUsers.length > 0) { 1492 // the app's nature doesn't depend on the user, so we can just 1493 // check its browser nature in any user and generalize. 1494 if (packageIsBrowser(packageName, firstUsers[0])) { 1495 synchronized (mPackages) { 1496 for (int userId : firstUsers) { 1497 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1498 } 1499 } 1500 } 1501 } 1502 // Log current value of "unknown sources" setting 1503 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1504 getUnknownSourcesSettings()); 1505 } 1506 // Force a gc to clear up things 1507 Runtime.getRuntime().gc(); 1508 // We delete after a gc for applications on sdcard. 1509 if (deleteOld) { 1510 synchronized (mInstallLock) { 1511 res.removedInfo.args.doPostDeleteLI(true); 1512 } 1513 } 1514 if (args.observer != null) { 1515 try { 1516 Bundle extras = extrasForInstallResult(res); 1517 args.observer.onPackageInstalled(res.name, res.returnCode, 1518 res.returnMsg, extras); 1519 } catch (RemoteException e) { 1520 Slog.i(TAG, "Observer no longer exists."); 1521 } 1522 } 1523 if (args.traceMethod != null) { 1524 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1525 args.traceCookie); 1526 } 1527 return; 1528 } else { 1529 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1530 } 1531 1532 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1533 } break; 1534 case UPDATED_MEDIA_STATUS: { 1535 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1536 boolean reportStatus = msg.arg1 == 1; 1537 boolean doGc = msg.arg2 == 1; 1538 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1539 if (doGc) { 1540 // Force a gc to clear up stale containers. 1541 Runtime.getRuntime().gc(); 1542 } 1543 if (msg.obj != null) { 1544 @SuppressWarnings("unchecked") 1545 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1546 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1547 // Unload containers 1548 unloadAllContainers(args); 1549 } 1550 if (reportStatus) { 1551 try { 1552 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1553 PackageHelper.getMountService().finishMediaUpdate(); 1554 } catch (RemoteException e) { 1555 Log.e(TAG, "MountService not running?"); 1556 } 1557 } 1558 } break; 1559 case WRITE_SETTINGS: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 synchronized (mPackages) { 1562 removeMessages(WRITE_SETTINGS); 1563 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1564 mSettings.writeLPr(); 1565 mDirtyUsers.clear(); 1566 } 1567 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1568 } break; 1569 case WRITE_PACKAGE_RESTRICTIONS: { 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1571 synchronized (mPackages) { 1572 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1573 for (int userId : mDirtyUsers) { 1574 mSettings.writePackageRestrictionsLPr(userId); 1575 } 1576 mDirtyUsers.clear(); 1577 } 1578 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1579 } break; 1580 case CHECK_PENDING_VERIFICATION: { 1581 final int verificationId = msg.arg1; 1582 final PackageVerificationState state = mPendingVerification.get(verificationId); 1583 1584 if ((state != null) && !state.timeoutExtended()) { 1585 final InstallArgs args = state.getInstallArgs(); 1586 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1587 1588 Slog.i(TAG, "Verification timed out for " + originUri); 1589 mPendingVerification.remove(verificationId); 1590 1591 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1592 1593 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1594 Slog.i(TAG, "Continuing with installation of " + originUri); 1595 state.setVerifierResponse(Binder.getCallingUid(), 1596 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1597 broadcastPackageVerified(verificationId, originUri, 1598 PackageManager.VERIFICATION_ALLOW, 1599 state.getInstallArgs().getUser()); 1600 try { 1601 ret = args.copyApk(mContainerService, true); 1602 } catch (RemoteException e) { 1603 Slog.e(TAG, "Could not contact the ContainerService"); 1604 } 1605 } else { 1606 broadcastPackageVerified(verificationId, originUri, 1607 PackageManager.VERIFICATION_REJECT, 1608 state.getInstallArgs().getUser()); 1609 } 1610 1611 Trace.asyncTraceEnd( 1612 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1613 1614 processPendingInstall(args, ret); 1615 mHandler.sendEmptyMessage(MCS_UNBIND); 1616 } 1617 break; 1618 } 1619 case PACKAGE_VERIFIED: { 1620 final int verificationId = msg.arg1; 1621 1622 final PackageVerificationState state = mPendingVerification.get(verificationId); 1623 if (state == null) { 1624 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1625 break; 1626 } 1627 1628 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1629 1630 state.setVerifierResponse(response.callerUid, response.code); 1631 1632 if (state.isVerificationComplete()) { 1633 mPendingVerification.remove(verificationId); 1634 1635 final InstallArgs args = state.getInstallArgs(); 1636 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1637 1638 int ret; 1639 if (state.isInstallAllowed()) { 1640 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1641 broadcastPackageVerified(verificationId, originUri, 1642 response.code, state.getInstallArgs().getUser()); 1643 try { 1644 ret = args.copyApk(mContainerService, true); 1645 } catch (RemoteException e) { 1646 Slog.e(TAG, "Could not contact the ContainerService"); 1647 } 1648 } else { 1649 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1650 } 1651 1652 Trace.asyncTraceEnd( 1653 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1654 1655 processPendingInstall(args, ret); 1656 mHandler.sendEmptyMessage(MCS_UNBIND); 1657 } 1658 1659 break; 1660 } 1661 case START_INTENT_FILTER_VERIFICATIONS: { 1662 IFVerificationParams params = (IFVerificationParams) msg.obj; 1663 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1664 params.replacing, params.pkg); 1665 break; 1666 } 1667 case INTENT_FILTER_VERIFIED: { 1668 final int verificationId = msg.arg1; 1669 1670 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1671 verificationId); 1672 if (state == null) { 1673 Slog.w(TAG, "Invalid IntentFilter verification token " 1674 + verificationId + " received"); 1675 break; 1676 } 1677 1678 final int userId = state.getUserId(); 1679 1680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1681 "Processing IntentFilter verification with token:" 1682 + verificationId + " and userId:" + userId); 1683 1684 final IntentFilterVerificationResponse response = 1685 (IntentFilterVerificationResponse) msg.obj; 1686 1687 state.setVerifierResponse(response.callerUid, response.code); 1688 1689 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1690 "IntentFilter verification with token:" + verificationId 1691 + " and userId:" + userId 1692 + " is settings verifier response with response code:" 1693 + response.code); 1694 1695 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1696 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1697 + response.getFailedDomainsString()); 1698 } 1699 1700 if (state.isVerificationComplete()) { 1701 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1702 } else { 1703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1704 "IntentFilter verification with token:" + verificationId 1705 + " was not said to be complete"); 1706 } 1707 1708 break; 1709 } 1710 } 1711 } 1712 } 1713 1714 private StorageEventListener mStorageListener = new StorageEventListener() { 1715 @Override 1716 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1717 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1718 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1719 final String volumeUuid = vol.getFsUuid(); 1720 1721 // Clean up any users or apps that were removed or recreated 1722 // while this volume was missing 1723 reconcileUsers(volumeUuid); 1724 reconcileApps(volumeUuid); 1725 1726 // Clean up any install sessions that expired or were 1727 // cancelled while this volume was missing 1728 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1729 1730 loadPrivatePackages(vol); 1731 1732 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1733 unloadPrivatePackages(vol); 1734 } 1735 } 1736 1737 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1738 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1739 updateExternalMediaStatus(true, false); 1740 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1741 updateExternalMediaStatus(false, false); 1742 } 1743 } 1744 } 1745 1746 @Override 1747 public void onVolumeForgotten(String fsUuid) { 1748 if (TextUtils.isEmpty(fsUuid)) { 1749 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1750 return; 1751 } 1752 1753 // Remove any apps installed on the forgotten volume 1754 synchronized (mPackages) { 1755 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1756 for (PackageSetting ps : packages) { 1757 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1758 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1759 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1760 } 1761 1762 mSettings.onVolumeForgotten(fsUuid); 1763 mSettings.writeLPr(); 1764 } 1765 } 1766 }; 1767 1768 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1769 String[] grantedPermissions) { 1770 if (userId >= UserHandle.USER_SYSTEM) { 1771 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1772 } else if (userId == UserHandle.USER_ALL) { 1773 final int[] userIds; 1774 synchronized (mPackages) { 1775 userIds = UserManagerService.getInstance().getUserIds(); 1776 } 1777 for (int someUserId : userIds) { 1778 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1779 } 1780 } 1781 1782 // We could have touched GID membership, so flush out packages.list 1783 synchronized (mPackages) { 1784 mSettings.writePackageListLPr(); 1785 } 1786 } 1787 1788 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1789 String[] grantedPermissions) { 1790 SettingBase sb = (SettingBase) pkg.mExtras; 1791 if (sb == null) { 1792 return; 1793 } 1794 1795 PermissionsState permissionsState = sb.getPermissionsState(); 1796 1797 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1798 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1799 1800 synchronized (mPackages) { 1801 for (String permission : pkg.requestedPermissions) { 1802 BasePermission bp = mSettings.mPermissions.get(permission); 1803 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1804 && (grantedPermissions == null 1805 || ArrayUtils.contains(grantedPermissions, permission))) { 1806 final int flags = permissionsState.getPermissionFlags(permission, userId); 1807 // Installer cannot change immutable permissions. 1808 if ((flags & immutableFlags) == 0) { 1809 grantRuntimePermission(pkg.packageName, permission, userId); 1810 } 1811 } 1812 } 1813 } 1814 } 1815 1816 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1817 Bundle extras = null; 1818 switch (res.returnCode) { 1819 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1820 extras = new Bundle(); 1821 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1822 res.origPermission); 1823 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1824 res.origPackage); 1825 break; 1826 } 1827 case PackageManager.INSTALL_SUCCEEDED: { 1828 extras = new Bundle(); 1829 extras.putBoolean(Intent.EXTRA_REPLACING, 1830 res.removedInfo != null && res.removedInfo.removedPackage != null); 1831 break; 1832 } 1833 } 1834 return extras; 1835 } 1836 1837 void scheduleWriteSettingsLocked() { 1838 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1839 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1840 } 1841 } 1842 1843 void scheduleWritePackageRestrictionsLocked(int userId) { 1844 if (!sUserManager.exists(userId)) return; 1845 mDirtyUsers.add(userId); 1846 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1847 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1848 } 1849 } 1850 1851 public static PackageManagerService main(Context context, Installer installer, 1852 boolean factoryTest, boolean onlyCore) { 1853 PackageManagerService m = new PackageManagerService(context, installer, 1854 factoryTest, onlyCore); 1855 m.enableSystemUserPackages(); 1856 ServiceManager.addService("package", m); 1857 return m; 1858 } 1859 1860 private void enableSystemUserPackages() { 1861 if (!UserManager.isSplitSystemUser()) { 1862 return; 1863 } 1864 // For system user, enable apps based on the following conditions: 1865 // - app is whitelisted or belong to one of these groups: 1866 // -- system app which has no launcher icons 1867 // -- system app which has INTERACT_ACROSS_USERS permission 1868 // -- system IME app 1869 // - app is not in the blacklist 1870 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1871 Set<String> enableApps = new ArraySet<>(); 1872 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1873 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1874 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1875 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1876 enableApps.addAll(wlApps); 1877 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1878 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1879 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1880 enableApps.removeAll(blApps); 1881 Log.i(TAG, "Applications installed for system user: " + enableApps); 1882 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1883 UserHandle.SYSTEM); 1884 final int allAppsSize = allAps.size(); 1885 synchronized (mPackages) { 1886 for (int i = 0; i < allAppsSize; i++) { 1887 String pName = allAps.get(i); 1888 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1889 // Should not happen, but we shouldn't be failing if it does 1890 if (pkgSetting == null) { 1891 continue; 1892 } 1893 boolean install = enableApps.contains(pName); 1894 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1895 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1896 + " for system user"); 1897 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1898 } 1899 } 1900 } 1901 } 1902 1903 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1904 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1905 Context.DISPLAY_SERVICE); 1906 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1907 } 1908 1909 public PackageManagerService(Context context, Installer installer, 1910 boolean factoryTest, boolean onlyCore) { 1911 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1912 SystemClock.uptimeMillis()); 1913 1914 if (mSdkVersion <= 0) { 1915 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1916 } 1917 1918 mContext = context; 1919 mFactoryTest = factoryTest; 1920 mOnlyCore = onlyCore; 1921 mMetrics = new DisplayMetrics(); 1922 mSettings = new Settings(mPackages); 1923 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1924 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1925 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1926 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1927 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1928 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1929 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1930 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1931 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1932 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1933 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1934 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1935 1936 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1937 if (separateProcesses != null && separateProcesses.length() > 0) { 1938 if ("*".equals(separateProcesses)) { 1939 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1940 mSeparateProcesses = null; 1941 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1942 } else { 1943 mDefParseFlags = 0; 1944 mSeparateProcesses = separateProcesses.split(","); 1945 Slog.w(TAG, "Running with debug.separate_processes: " 1946 + separateProcesses); 1947 } 1948 } else { 1949 mDefParseFlags = 0; 1950 mSeparateProcesses = null; 1951 } 1952 1953 mInstaller = installer; 1954 mPackageDexOptimizer = new PackageDexOptimizer(this); 1955 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1956 1957 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1958 FgThread.get().getLooper()); 1959 1960 getDefaultDisplayMetrics(context, mMetrics); 1961 1962 SystemConfig systemConfig = SystemConfig.getInstance(); 1963 mGlobalGids = systemConfig.getGlobalGids(); 1964 mSystemPermissions = systemConfig.getSystemPermissions(); 1965 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1966 1967 synchronized (mInstallLock) { 1968 // writer 1969 synchronized (mPackages) { 1970 mHandlerThread = new ServiceThread(TAG, 1971 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1972 mHandlerThread.start(); 1973 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1974 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1975 1976 File dataDir = Environment.getDataDirectory(); 1977 mAppInstallDir = new File(dataDir, "app"); 1978 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1979 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1980 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1981 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1982 1983 sUserManager = new UserManagerService(context, this, mPackages); 1984 1985 // Propagate permission configuration in to package manager. 1986 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1987 = systemConfig.getPermissions(); 1988 for (int i=0; i<permConfig.size(); i++) { 1989 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1990 BasePermission bp = mSettings.mPermissions.get(perm.name); 1991 if (bp == null) { 1992 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1993 mSettings.mPermissions.put(perm.name, bp); 1994 } 1995 if (perm.gids != null) { 1996 bp.setGids(perm.gids, perm.perUser); 1997 } 1998 } 1999 2000 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2001 for (int i=0; i<libConfig.size(); i++) { 2002 mSharedLibraries.put(libConfig.keyAt(i), 2003 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2004 } 2005 2006 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2007 2008 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2009 2010 String customResolverActivity = Resources.getSystem().getString( 2011 R.string.config_customResolverActivity); 2012 if (TextUtils.isEmpty(customResolverActivity)) { 2013 customResolverActivity = null; 2014 } else { 2015 mCustomResolverComponentName = ComponentName.unflattenFromString( 2016 customResolverActivity); 2017 } 2018 2019 long startTime = SystemClock.uptimeMillis(); 2020 2021 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2022 startTime); 2023 2024 // Set flag to monitor and not change apk file paths when 2025 // scanning install directories. 2026 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2027 2028 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2029 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2030 2031 if (bootClassPath == null) { 2032 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2033 } 2034 2035 if (systemServerClassPath == null) { 2036 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2037 } 2038 2039 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2040 final String[] dexCodeInstructionSets = 2041 getDexCodeInstructionSets( 2042 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2043 2044 /** 2045 * Ensure all external libraries have had dexopt run on them. 2046 */ 2047 if (mSharedLibraries.size() > 0) { 2048 // NOTE: For now, we're compiling these system "shared libraries" 2049 // (and framework jars) into all available architectures. It's possible 2050 // to compile them only when we come across an app that uses them (there's 2051 // already logic for that in scanPackageLI) but that adds some complexity. 2052 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2053 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2054 final String lib = libEntry.path; 2055 if (lib == null) { 2056 continue; 2057 } 2058 2059 try { 2060 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2061 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2062 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2063 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2064 } 2065 } catch (FileNotFoundException e) { 2066 Slog.w(TAG, "Library not found: " + lib); 2067 } catch (IOException e) { 2068 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2069 + e.getMessage()); 2070 } 2071 } 2072 } 2073 } 2074 2075 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2076 2077 final VersionInfo ver = mSettings.getInternalVersion(); 2078 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2079 // when upgrading from pre-M, promote system app permissions from install to runtime 2080 mPromoteSystemApps = 2081 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2082 2083 // save off the names of pre-existing system packages prior to scanning; we don't 2084 // want to automatically grant runtime permissions for new system apps 2085 if (mPromoteSystemApps) { 2086 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2087 while (pkgSettingIter.hasNext()) { 2088 PackageSetting ps = pkgSettingIter.next(); 2089 if (isSystemApp(ps)) { 2090 mExistingSystemPackages.add(ps.name); 2091 } 2092 } 2093 } 2094 2095 // Collect vendor overlay packages. 2096 // (Do this before scanning any apps.) 2097 // For security and version matching reason, only consider 2098 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2099 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2100 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2101 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2102 2103 // Find base frameworks (resource packages without code). 2104 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2105 | PackageParser.PARSE_IS_SYSTEM_DIR 2106 | PackageParser.PARSE_IS_PRIVILEGED, 2107 scanFlags | SCAN_NO_DEX, 0); 2108 2109 // Collected privileged system packages. 2110 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2111 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2112 | PackageParser.PARSE_IS_SYSTEM_DIR 2113 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2114 2115 // Collect ordinary system packages. 2116 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2117 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2118 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2119 2120 // Collect all vendor packages. 2121 File vendorAppDir = new File("/vendor/app"); 2122 try { 2123 vendorAppDir = vendorAppDir.getCanonicalFile(); 2124 } catch (IOException e) { 2125 // failed to look up canonical path, continue with original one 2126 } 2127 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2128 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2129 2130 // Collect all OEM packages. 2131 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2132 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2133 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2134 2135 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2136 mInstaller.moveFiles(); 2137 2138 // Prune any system packages that no longer exist. 2139 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2140 if (!mOnlyCore) { 2141 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2142 while (psit.hasNext()) { 2143 PackageSetting ps = psit.next(); 2144 2145 /* 2146 * If this is not a system app, it can't be a 2147 * disable system app. 2148 */ 2149 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2150 continue; 2151 } 2152 2153 /* 2154 * If the package is scanned, it's not erased. 2155 */ 2156 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2157 if (scannedPkg != null) { 2158 /* 2159 * If the system app is both scanned and in the 2160 * disabled packages list, then it must have been 2161 * added via OTA. Remove it from the currently 2162 * scanned package so the previously user-installed 2163 * application can be scanned. 2164 */ 2165 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2166 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2167 + ps.name + "; removing system app. Last known codePath=" 2168 + ps.codePathString + ", installStatus=" + ps.installStatus 2169 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2170 + scannedPkg.mVersionCode); 2171 removePackageLI(ps, true); 2172 mExpectingBetter.put(ps.name, ps.codePath); 2173 } 2174 2175 continue; 2176 } 2177 2178 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2179 psit.remove(); 2180 logCriticalInfo(Log.WARN, "System package " + ps.name 2181 + " no longer exists; wiping its data"); 2182 removeDataDirsLI(null, ps.name); 2183 } else { 2184 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2185 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2186 possiblyDeletedUpdatedSystemApps.add(ps.name); 2187 } 2188 } 2189 } 2190 } 2191 2192 //look for any incomplete package installations 2193 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2194 //clean up list 2195 for(int i = 0; i < deletePkgsList.size(); i++) { 2196 //clean up here 2197 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2198 } 2199 //delete tmp files 2200 deleteTempPackageFiles(); 2201 2202 // Remove any shared userIDs that have no associated packages 2203 mSettings.pruneSharedUsersLPw(); 2204 2205 if (!mOnlyCore) { 2206 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2207 SystemClock.uptimeMillis()); 2208 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2209 2210 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2211 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2212 2213 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2214 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2215 2216 /** 2217 * Remove disable package settings for any updated system 2218 * apps that were removed via an OTA. If they're not a 2219 * previously-updated app, remove them completely. 2220 * Otherwise, just revoke their system-level permissions. 2221 */ 2222 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2223 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2224 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2225 2226 String msg; 2227 if (deletedPkg == null) { 2228 msg = "Updated system package " + deletedAppName 2229 + " no longer exists; wiping its data"; 2230 removeDataDirsLI(null, deletedAppName); 2231 } else { 2232 msg = "Updated system app + " + deletedAppName 2233 + " no longer present; removing system privileges for " 2234 + deletedAppName; 2235 2236 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2237 2238 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2239 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2240 } 2241 logCriticalInfo(Log.WARN, msg); 2242 } 2243 2244 /** 2245 * Make sure all system apps that we expected to appear on 2246 * the userdata partition actually showed up. If they never 2247 * appeared, crawl back and revive the system version. 2248 */ 2249 for (int i = 0; i < mExpectingBetter.size(); i++) { 2250 final String packageName = mExpectingBetter.keyAt(i); 2251 if (!mPackages.containsKey(packageName)) { 2252 final File scanFile = mExpectingBetter.valueAt(i); 2253 2254 logCriticalInfo(Log.WARN, "Expected better " + packageName 2255 + " but never showed up; reverting to system"); 2256 2257 final int reparseFlags; 2258 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2259 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2260 | PackageParser.PARSE_IS_SYSTEM_DIR 2261 | PackageParser.PARSE_IS_PRIVILEGED; 2262 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2263 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2264 | PackageParser.PARSE_IS_SYSTEM_DIR; 2265 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2266 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR; 2268 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2269 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2270 | PackageParser.PARSE_IS_SYSTEM_DIR; 2271 } else { 2272 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2273 continue; 2274 } 2275 2276 mSettings.enableSystemPackageLPw(packageName); 2277 2278 try { 2279 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2280 } catch (PackageManagerException e) { 2281 Slog.e(TAG, "Failed to parse original system package: " 2282 + e.getMessage()); 2283 } 2284 } 2285 } 2286 } 2287 mExpectingBetter.clear(); 2288 2289 // Now that we know all of the shared libraries, update all clients to have 2290 // the correct library paths. 2291 updateAllSharedLibrariesLPw(); 2292 2293 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2294 // NOTE: We ignore potential failures here during a system scan (like 2295 // the rest of the commands above) because there's precious little we 2296 // can do about it. A settings error is reported, though. 2297 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2298 false /* boot complete */); 2299 } 2300 2301 // Now that we know all the packages we are keeping, 2302 // read and update their last usage times. 2303 mPackageUsage.readLP(); 2304 2305 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2306 SystemClock.uptimeMillis()); 2307 Slog.i(TAG, "Time to scan packages: " 2308 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2309 + " seconds"); 2310 2311 // If the platform SDK has changed since the last time we booted, 2312 // we need to re-grant app permission to catch any new ones that 2313 // appear. This is really a hack, and means that apps can in some 2314 // cases get permissions that the user didn't initially explicitly 2315 // allow... it would be nice to have some better way to handle 2316 // this situation. 2317 int updateFlags = UPDATE_PERMISSIONS_ALL; 2318 if (ver.sdkVersion != mSdkVersion) { 2319 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2320 + mSdkVersion + "; regranting permissions for internal storage"); 2321 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2322 } 2323 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2324 ver.sdkVersion = mSdkVersion; 2325 2326 // If this is the first boot or an update from pre-M, and it is a normal 2327 // boot, then we need to initialize the default preferred apps across 2328 // all defined users. 2329 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2330 for (UserInfo user : sUserManager.getUsers(true)) { 2331 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2332 applyFactoryDefaultBrowserLPw(user.id); 2333 primeDomainVerificationsLPw(user.id); 2334 } 2335 } 2336 2337 // If this is first boot after an OTA, and a normal boot, then 2338 // we need to clear code cache directories. 2339 if (mIsUpgrade && !onlyCore) { 2340 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2341 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2342 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2343 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2344 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2345 } 2346 } 2347 ver.fingerprint = Build.FINGERPRINT; 2348 } 2349 2350 checkDefaultBrowser(); 2351 2352 // clear only after permissions and other defaults have been updated 2353 mExistingSystemPackages.clear(); 2354 mPromoteSystemApps = false; 2355 2356 // All the changes are done during package scanning. 2357 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2358 2359 // can downgrade to reader 2360 mSettings.writeLPr(); 2361 2362 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2363 SystemClock.uptimeMillis()); 2364 2365 if (!mOnlyCore) { 2366 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2367 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2368 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2369 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2370 mIntentFilterVerifierComponent); 2371 } else { 2372 mRequiredVerifierPackage = null; 2373 mRequiredInstallerPackage = null; 2374 mIntentFilterVerifierComponent = null; 2375 mIntentFilterVerifier = null; 2376 } 2377 2378 mInstallerService = new PackageInstallerService(context, this); 2379 2380 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2381 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2382 // both the installer and resolver must be present to enable ephemeral 2383 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2384 if (DEBUG_EPHEMERAL) { 2385 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2386 + " installer:" + ephemeralInstallerComponent); 2387 } 2388 mEphemeralResolverComponent = ephemeralResolverComponent; 2389 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2390 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2391 mEphemeralResolverConnection = 2392 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2393 } else { 2394 if (DEBUG_EPHEMERAL) { 2395 final String missingComponent = 2396 (ephemeralResolverComponent == null) 2397 ? (ephemeralInstallerComponent == null) 2398 ? "resolver and installer" 2399 : "resolver" 2400 : "installer"; 2401 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2402 } 2403 mEphemeralResolverComponent = null; 2404 mEphemeralInstallerComponent = null; 2405 mEphemeralResolverConnection = null; 2406 } 2407 2408 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2409 } // synchronized (mPackages) 2410 } // synchronized (mInstallLock) 2411 2412 // Now after opening every single application zip, make sure they 2413 // are all flushed. Not really needed, but keeps things nice and 2414 // tidy. 2415 Runtime.getRuntime().gc(); 2416 2417 // The initial scanning above does many calls into installd while 2418 // holding the mPackages lock, but we're mostly interested in yelling 2419 // once we have a booted system. 2420 mInstaller.setWarnIfHeld(mPackages); 2421 2422 // Expose private service for system components to use. 2423 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2424 } 2425 2426 @Override 2427 public boolean isFirstBoot() { 2428 return !mRestoredSettings; 2429 } 2430 2431 @Override 2432 public boolean isOnlyCoreApps() { 2433 return mOnlyCore; 2434 } 2435 2436 @Override 2437 public boolean isUpgrade() { 2438 return mIsUpgrade; 2439 } 2440 2441 private @NonNull String getRequiredVerifierLPr() { 2442 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2443 2444 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2445 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2446 if (matches.size() == 1) { 2447 return matches.get(0).getComponentInfo().packageName; 2448 } else { 2449 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2450 } 2451 } 2452 2453 private @NonNull String getRequiredInstallerLPr() { 2454 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2455 intent.addCategory(Intent.CATEGORY_DEFAULT); 2456 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2457 2458 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2459 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2460 if (matches.size() == 1) { 2461 return matches.get(0).getComponentInfo().packageName; 2462 } else { 2463 throw new RuntimeException("There must be exactly one installer; found " + matches); 2464 } 2465 } 2466 2467 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2468 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2469 2470 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2471 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2472 ResolveInfo best = null; 2473 final int N = matches.size(); 2474 for (int i = 0; i < N; i++) { 2475 final ResolveInfo cur = matches.get(i); 2476 final String packageName = cur.getComponentInfo().packageName; 2477 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2478 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2479 continue; 2480 } 2481 2482 if (best == null || cur.priority > best.priority) { 2483 best = cur; 2484 } 2485 } 2486 2487 if (best != null) { 2488 return best.getComponentInfo().getComponentName(); 2489 } else { 2490 throw new RuntimeException("There must be at least one intent filter verifier"); 2491 } 2492 } 2493 2494 private @Nullable ComponentName getEphemeralResolverLPr() { 2495 final String[] packageArray = 2496 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2497 if (packageArray.length == 0) { 2498 if (DEBUG_EPHEMERAL) { 2499 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2500 } 2501 return null; 2502 } 2503 2504 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2505 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2506 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2507 2508 final int N = resolvers.size(); 2509 if (N == 0) { 2510 if (DEBUG_EPHEMERAL) { 2511 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2512 } 2513 return null; 2514 } 2515 2516 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2517 for (int i = 0; i < N; i++) { 2518 final ResolveInfo info = resolvers.get(i); 2519 2520 if (info.serviceInfo == null) { 2521 continue; 2522 } 2523 2524 final String packageName = info.serviceInfo.packageName; 2525 if (!possiblePackages.contains(packageName)) { 2526 if (DEBUG_EPHEMERAL) { 2527 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2528 + " pkg: " + packageName + ", info:" + info); 2529 } 2530 continue; 2531 } 2532 2533 if (DEBUG_EPHEMERAL) { 2534 Slog.v(TAG, "Ephemeral resolver found;" 2535 + " pkg: " + packageName + ", info:" + info); 2536 } 2537 return new ComponentName(packageName, info.serviceInfo.name); 2538 } 2539 if (DEBUG_EPHEMERAL) { 2540 Slog.v(TAG, "Ephemeral resolver NOT found"); 2541 } 2542 return null; 2543 } 2544 2545 private @Nullable ComponentName getEphemeralInstallerLPr() { 2546 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2547 intent.addCategory(Intent.CATEGORY_DEFAULT); 2548 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2549 2550 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2551 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2552 if (matches.size() == 0) { 2553 return null; 2554 } else if (matches.size() == 1) { 2555 return matches.get(0).getComponentInfo().getComponentName(); 2556 } else { 2557 throw new RuntimeException( 2558 "There must be at most one ephemeral installer; found " + matches); 2559 } 2560 } 2561 2562 private void primeDomainVerificationsLPw(int userId) { 2563 if (DEBUG_DOMAIN_VERIFICATION) { 2564 Slog.d(TAG, "Priming domain verifications in user " + userId); 2565 } 2566 2567 SystemConfig systemConfig = SystemConfig.getInstance(); 2568 ArraySet<String> packages = systemConfig.getLinkedApps(); 2569 ArraySet<String> domains = new ArraySet<String>(); 2570 2571 for (String packageName : packages) { 2572 PackageParser.Package pkg = mPackages.get(packageName); 2573 if (pkg != null) { 2574 if (!pkg.isSystemApp()) { 2575 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2576 continue; 2577 } 2578 2579 domains.clear(); 2580 for (PackageParser.Activity a : pkg.activities) { 2581 for (ActivityIntentInfo filter : a.intents) { 2582 if (hasValidDomains(filter)) { 2583 domains.addAll(filter.getHostsList()); 2584 } 2585 } 2586 } 2587 2588 if (domains.size() > 0) { 2589 if (DEBUG_DOMAIN_VERIFICATION) { 2590 Slog.v(TAG, " + " + packageName); 2591 } 2592 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2593 // state w.r.t. the formal app-linkage "no verification attempted" state; 2594 // and then 'always' in the per-user state actually used for intent resolution. 2595 final IntentFilterVerificationInfo ivi; 2596 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2597 new ArrayList<String>(domains)); 2598 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2599 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2600 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2601 } else { 2602 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2603 + "' does not handle web links"); 2604 } 2605 } else { 2606 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2607 } 2608 } 2609 2610 scheduleWritePackageRestrictionsLocked(userId); 2611 scheduleWriteSettingsLocked(); 2612 } 2613 2614 private void applyFactoryDefaultBrowserLPw(int userId) { 2615 // The default browser app's package name is stored in a string resource, 2616 // with a product-specific overlay used for vendor customization. 2617 String browserPkg = mContext.getResources().getString( 2618 com.android.internal.R.string.default_browser); 2619 if (!TextUtils.isEmpty(browserPkg)) { 2620 // non-empty string => required to be a known package 2621 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2622 if (ps == null) { 2623 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2624 browserPkg = null; 2625 } else { 2626 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2627 } 2628 } 2629 2630 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2631 // default. If there's more than one, just leave everything alone. 2632 if (browserPkg == null) { 2633 calculateDefaultBrowserLPw(userId); 2634 } 2635 } 2636 2637 private void calculateDefaultBrowserLPw(int userId) { 2638 List<String> allBrowsers = resolveAllBrowserApps(userId); 2639 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2640 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2641 } 2642 2643 private List<String> resolveAllBrowserApps(int userId) { 2644 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2645 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2646 PackageManager.MATCH_ALL, userId); 2647 2648 final int count = list.size(); 2649 List<String> result = new ArrayList<String>(count); 2650 for (int i=0; i<count; i++) { 2651 ResolveInfo info = list.get(i); 2652 if (info.activityInfo == null 2653 || !info.handleAllWebDataURI 2654 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2655 || result.contains(info.activityInfo.packageName)) { 2656 continue; 2657 } 2658 result.add(info.activityInfo.packageName); 2659 } 2660 2661 return result; 2662 } 2663 2664 private boolean packageIsBrowser(String packageName, int userId) { 2665 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2666 PackageManager.MATCH_ALL, userId); 2667 final int N = list.size(); 2668 for (int i = 0; i < N; i++) { 2669 ResolveInfo info = list.get(i); 2670 if (packageName.equals(info.activityInfo.packageName)) { 2671 return true; 2672 } 2673 } 2674 return false; 2675 } 2676 2677 private void checkDefaultBrowser() { 2678 final int myUserId = UserHandle.myUserId(); 2679 final String packageName = getDefaultBrowserPackageName(myUserId); 2680 if (packageName != null) { 2681 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2682 if (info == null) { 2683 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2684 synchronized (mPackages) { 2685 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2686 } 2687 } 2688 } 2689 } 2690 2691 @Override 2692 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2693 throws RemoteException { 2694 try { 2695 return super.onTransact(code, data, reply, flags); 2696 } catch (RuntimeException e) { 2697 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2698 Slog.wtf(TAG, "Package Manager Crash", e); 2699 } 2700 throw e; 2701 } 2702 } 2703 2704 void cleanupInstallFailedPackage(PackageSetting ps) { 2705 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2706 2707 removeDataDirsLI(ps.volumeUuid, ps.name); 2708 if (ps.codePath != null) { 2709 if (ps.codePath.isDirectory()) { 2710 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2711 } else { 2712 ps.codePath.delete(); 2713 } 2714 } 2715 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2716 if (ps.resourcePath.isDirectory()) { 2717 FileUtils.deleteContents(ps.resourcePath); 2718 } 2719 ps.resourcePath.delete(); 2720 } 2721 mSettings.removePackageLPw(ps.name); 2722 } 2723 2724 static int[] appendInts(int[] cur, int[] add) { 2725 if (add == null) return cur; 2726 if (cur == null) return add; 2727 final int N = add.length; 2728 for (int i=0; i<N; i++) { 2729 cur = appendInt(cur, add[i]); 2730 } 2731 return cur; 2732 } 2733 2734 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 final PackageSetting ps = (PackageSetting) p.mExtras; 2737 if (ps == null) { 2738 return null; 2739 } 2740 2741 final PermissionsState permissionsState = ps.getPermissionsState(); 2742 2743 final int[] gids = permissionsState.computeGids(userId); 2744 final Set<String> permissions = permissionsState.getPermissions(userId); 2745 final PackageUserState state = ps.readUserState(userId); 2746 2747 return PackageParser.generatePackageInfo(p, gids, flags, 2748 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2749 } 2750 2751 @Override 2752 public void checkPackageStartable(String packageName, int userId) { 2753 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2754 2755 synchronized (mPackages) { 2756 final PackageSetting ps = mSettings.mPackages.get(packageName); 2757 if (ps == null) { 2758 throw new SecurityException("Package " + packageName + " was not found!"); 2759 } 2760 2761 if (ps.frozen) { 2762 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2763 } 2764 2765 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2766 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2767 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2768 } 2769 } 2770 } 2771 2772 @Override 2773 public boolean isPackageAvailable(String packageName, int userId) { 2774 if (!sUserManager.exists(userId)) return false; 2775 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2776 synchronized (mPackages) { 2777 PackageParser.Package p = mPackages.get(packageName); 2778 if (p != null) { 2779 final PackageSetting ps = (PackageSetting) p.mExtras; 2780 if (ps != null) { 2781 final PackageUserState state = ps.readUserState(userId); 2782 if (state != null) { 2783 return PackageParser.isAvailable(state); 2784 } 2785 } 2786 } 2787 } 2788 return false; 2789 } 2790 2791 @Override 2792 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 flags = updateFlagsForPackage(flags, userId, packageName); 2795 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2796 // reader 2797 synchronized (mPackages) { 2798 PackageParser.Package p = mPackages.get(packageName); 2799 if (DEBUG_PACKAGE_INFO) 2800 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2801 if (p != null) { 2802 return generatePackageInfo(p, flags, userId); 2803 } 2804 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2805 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2806 } 2807 } 2808 return null; 2809 } 2810 2811 @Override 2812 public String[] currentToCanonicalPackageNames(String[] names) { 2813 String[] out = new String[names.length]; 2814 // reader 2815 synchronized (mPackages) { 2816 for (int i=names.length-1; i>=0; i--) { 2817 PackageSetting ps = mSettings.mPackages.get(names[i]); 2818 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2819 } 2820 } 2821 return out; 2822 } 2823 2824 @Override 2825 public String[] canonicalToCurrentPackageNames(String[] names) { 2826 String[] out = new String[names.length]; 2827 // reader 2828 synchronized (mPackages) { 2829 for (int i=names.length-1; i>=0; i--) { 2830 String cur = mSettings.mRenamedPackages.get(names[i]); 2831 out[i] = cur != null ? cur : names[i]; 2832 } 2833 } 2834 return out; 2835 } 2836 2837 @Override 2838 public int getPackageUid(String packageName, int userId) { 2839 return getPackageUidEtc(packageName, 0, userId); 2840 } 2841 2842 @Override 2843 public int getPackageUidEtc(String packageName, int flags, int userId) { 2844 if (!sUserManager.exists(userId)) return -1; 2845 flags = updateFlagsForPackage(flags, userId, packageName); 2846 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2847 2848 // reader 2849 synchronized (mPackages) { 2850 final PackageParser.Package p = mPackages.get(packageName); 2851 if (p != null && p.isMatch(flags)) { 2852 return UserHandle.getUid(userId, p.applicationInfo.uid); 2853 } 2854 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2855 final PackageSetting ps = mSettings.mPackages.get(packageName); 2856 if (ps != null && ps.isMatch(flags)) { 2857 return UserHandle.getUid(userId, ps.appId); 2858 } 2859 } 2860 } 2861 2862 return -1; 2863 } 2864 2865 @Override 2866 public int[] getPackageGids(String packageName, int userId) { 2867 return getPackageGidsEtc(packageName, 0, userId); 2868 } 2869 2870 @Override 2871 public int[] getPackageGidsEtc(String packageName, int flags, int userId) { 2872 if (!sUserManager.exists(userId)) return null; 2873 flags = updateFlagsForPackage(flags, userId, packageName); 2874 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2875 "getPackageGids"); 2876 2877 // reader 2878 synchronized (mPackages) { 2879 final PackageParser.Package p = mPackages.get(packageName); 2880 if (p != null && p.isMatch(flags)) { 2881 PackageSetting ps = (PackageSetting) p.mExtras; 2882 return ps.getPermissionsState().computeGids(userId); 2883 } 2884 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2885 final PackageSetting ps = mSettings.mPackages.get(packageName); 2886 if (ps != null && ps.isMatch(flags)) { 2887 return ps.getPermissionsState().computeGids(userId); 2888 } 2889 } 2890 } 2891 2892 return null; 2893 } 2894 2895 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2896 if (bp.perm != null) { 2897 return PackageParser.generatePermissionInfo(bp.perm, flags); 2898 } 2899 PermissionInfo pi = new PermissionInfo(); 2900 pi.name = bp.name; 2901 pi.packageName = bp.sourcePackage; 2902 pi.nonLocalizedLabel = bp.name; 2903 pi.protectionLevel = bp.protectionLevel; 2904 return pi; 2905 } 2906 2907 @Override 2908 public PermissionInfo getPermissionInfo(String name, int flags) { 2909 // reader 2910 synchronized (mPackages) { 2911 final BasePermission p = mSettings.mPermissions.get(name); 2912 if (p != null) { 2913 return generatePermissionInfo(p, flags); 2914 } 2915 return null; 2916 } 2917 } 2918 2919 @Override 2920 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2921 // reader 2922 synchronized (mPackages) { 2923 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2924 for (BasePermission p : mSettings.mPermissions.values()) { 2925 if (group == null) { 2926 if (p.perm == null || p.perm.info.group == null) { 2927 out.add(generatePermissionInfo(p, flags)); 2928 } 2929 } else { 2930 if (p.perm != null && group.equals(p.perm.info.group)) { 2931 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2932 } 2933 } 2934 } 2935 2936 if (out.size() > 0) { 2937 return out; 2938 } 2939 return mPermissionGroups.containsKey(group) ? out : null; 2940 } 2941 } 2942 2943 @Override 2944 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2945 // reader 2946 synchronized (mPackages) { 2947 return PackageParser.generatePermissionGroupInfo( 2948 mPermissionGroups.get(name), flags); 2949 } 2950 } 2951 2952 @Override 2953 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2954 // reader 2955 synchronized (mPackages) { 2956 final int N = mPermissionGroups.size(); 2957 ArrayList<PermissionGroupInfo> out 2958 = new ArrayList<PermissionGroupInfo>(N); 2959 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2960 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2961 } 2962 return out; 2963 } 2964 } 2965 2966 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2967 int userId) { 2968 if (!sUserManager.exists(userId)) return null; 2969 PackageSetting ps = mSettings.mPackages.get(packageName); 2970 if (ps != null) { 2971 if (ps.pkg == null) { 2972 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2973 flags, userId); 2974 if (pInfo != null) { 2975 return pInfo.applicationInfo; 2976 } 2977 return null; 2978 } 2979 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2980 ps.readUserState(userId), userId); 2981 } 2982 return null; 2983 } 2984 2985 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2986 int userId) { 2987 if (!sUserManager.exists(userId)) return null; 2988 PackageSetting ps = mSettings.mPackages.get(packageName); 2989 if (ps != null) { 2990 PackageParser.Package pkg = ps.pkg; 2991 if (pkg == null) { 2992 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 2993 return null; 2994 } 2995 // Only data remains, so we aren't worried about code paths 2996 pkg = new PackageParser.Package(packageName); 2997 pkg.applicationInfo.packageName = packageName; 2998 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2999 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3000 pkg.applicationInfo.uid = ps.appId; 3001 pkg.applicationInfo.initForUser(userId); 3002 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3003 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3004 } 3005 return generatePackageInfo(pkg, flags, userId); 3006 } 3007 return null; 3008 } 3009 3010 @Override 3011 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3012 if (!sUserManager.exists(userId)) return null; 3013 flags = updateFlagsForApplication(flags, userId, packageName); 3014 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3015 // writer 3016 synchronized (mPackages) { 3017 PackageParser.Package p = mPackages.get(packageName); 3018 if (DEBUG_PACKAGE_INFO) Log.v( 3019 TAG, "getApplicationInfo " + packageName 3020 + ": " + p); 3021 if (p != null) { 3022 PackageSetting ps = mSettings.mPackages.get(packageName); 3023 if (ps == null) return null; 3024 // Note: isEnabledLP() does not apply here - always return info 3025 return PackageParser.generateApplicationInfo( 3026 p, flags, ps.readUserState(userId), userId); 3027 } 3028 if ("android".equals(packageName)||"system".equals(packageName)) { 3029 return mAndroidApplication; 3030 } 3031 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3032 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3033 } 3034 } 3035 return null; 3036 } 3037 3038 @Override 3039 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3040 final IPackageDataObserver observer) { 3041 mContext.enforceCallingOrSelfPermission( 3042 android.Manifest.permission.CLEAR_APP_CACHE, null); 3043 // Queue up an async operation since clearing cache may take a little while. 3044 mHandler.post(new Runnable() { 3045 public void run() { 3046 mHandler.removeCallbacks(this); 3047 int retCode = -1; 3048 synchronized (mInstallLock) { 3049 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3050 if (retCode < 0) { 3051 Slog.w(TAG, "Couldn't clear application caches"); 3052 } 3053 } 3054 if (observer != null) { 3055 try { 3056 observer.onRemoveCompleted(null, (retCode >= 0)); 3057 } catch (RemoteException e) { 3058 Slog.w(TAG, "RemoveException when invoking call back"); 3059 } 3060 } 3061 } 3062 }); 3063 } 3064 3065 @Override 3066 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3067 final IntentSender pi) { 3068 mContext.enforceCallingOrSelfPermission( 3069 android.Manifest.permission.CLEAR_APP_CACHE, null); 3070 // Queue up an async operation since clearing cache may take a little while. 3071 mHandler.post(new Runnable() { 3072 public void run() { 3073 mHandler.removeCallbacks(this); 3074 int retCode = -1; 3075 synchronized (mInstallLock) { 3076 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3077 if (retCode < 0) { 3078 Slog.w(TAG, "Couldn't clear application caches"); 3079 } 3080 } 3081 if(pi != null) { 3082 try { 3083 // Callback via pending intent 3084 int code = (retCode >= 0) ? 1 : 0; 3085 pi.sendIntent(null, code, null, 3086 null, null); 3087 } catch (SendIntentException e1) { 3088 Slog.i(TAG, "Failed to send pending intent"); 3089 } 3090 } 3091 } 3092 }); 3093 } 3094 3095 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3096 synchronized (mInstallLock) { 3097 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3098 throw new IOException("Failed to free enough space"); 3099 } 3100 } 3101 } 3102 3103 /** 3104 * Return if the user key is currently unlocked. 3105 */ 3106 private boolean isUserKeyUnlocked(int userId) { 3107 if (StorageManager.isFileBasedEncryptionEnabled()) { 3108 final IMountService mount = IMountService.Stub 3109 .asInterface(ServiceManager.getService("mount")); 3110 if (mount == null) { 3111 Slog.w(TAG, "Early during boot, assuming locked"); 3112 return false; 3113 } 3114 final long token = Binder.clearCallingIdentity(); 3115 try { 3116 return mount.isUserKeyUnlocked(userId); 3117 } catch (RemoteException e) { 3118 throw e.rethrowAsRuntimeException(); 3119 } finally { 3120 Binder.restoreCallingIdentity(token); 3121 } 3122 } else { 3123 return true; 3124 } 3125 } 3126 3127 /** 3128 * Update given flags based on encryption status of current user. 3129 */ 3130 private int updateFlagsForEncryption(int flags, int userId) { 3131 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3132 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3133 // Caller expressed an explicit opinion about what encryption 3134 // aware/unaware components they want to see, so fall through and 3135 // give them what they want 3136 } else { 3137 // Caller expressed no opinion, so match based on user state 3138 if (isUserKeyUnlocked(userId)) { 3139 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3140 } else { 3141 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3142 } 3143 } 3144 return flags; 3145 } 3146 3147 /** 3148 * Update given flags when being used to request {@link PackageInfo}. 3149 */ 3150 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3151 boolean triaged = true; 3152 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3153 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3154 // Caller is asking for component details, so they'd better be 3155 // asking for specific encryption matching behavior, or be triaged 3156 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3157 | PackageManager.MATCH_ENCRYPTION_AWARE 3158 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3159 triaged = false; 3160 } 3161 } 3162 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3163 | PackageManager.MATCH_SYSTEM_ONLY 3164 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3165 triaged = false; 3166 } 3167 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3168 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3169 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3170 } 3171 return updateFlagsForEncryption(flags, userId); 3172 } 3173 3174 /** 3175 * Update given flags when being used to request {@link ApplicationInfo}. 3176 */ 3177 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3178 return updateFlagsForPackage(flags, userId, cookie); 3179 } 3180 3181 /** 3182 * Update given flags when being used to request {@link ComponentInfo}. 3183 */ 3184 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3185 if (cookie instanceof Intent) { 3186 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3187 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3188 } 3189 } 3190 3191 boolean triaged = true; 3192 // Caller is asking for component details, so they'd better be 3193 // asking for specific encryption matching behavior, or be triaged 3194 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3195 | PackageManager.MATCH_ENCRYPTION_AWARE 3196 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3197 triaged = false; 3198 } 3199 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3200 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3201 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3202 } 3203 return updateFlagsForEncryption(flags, userId); 3204 } 3205 3206 /** 3207 * Update given flags when being used to request {@link ResolveInfo}. 3208 */ 3209 private int updateFlagsForResolve(int flags, int userId, Object cookie) { 3210 return updateFlagsForComponent(flags, userId, cookie); 3211 } 3212 3213 @Override 3214 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3215 if (!sUserManager.exists(userId)) return null; 3216 flags = updateFlagsForComponent(flags, userId, component); 3217 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3218 synchronized (mPackages) { 3219 PackageParser.Activity a = mActivities.mActivities.get(component); 3220 3221 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3222 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3223 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3224 if (ps == null) return null; 3225 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3226 userId); 3227 } 3228 if (mResolveComponentName.equals(component)) { 3229 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3230 new PackageUserState(), userId); 3231 } 3232 } 3233 return null; 3234 } 3235 3236 @Override 3237 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3238 String resolvedType) { 3239 synchronized (mPackages) { 3240 if (component.equals(mResolveComponentName)) { 3241 // The resolver supports EVERYTHING! 3242 return true; 3243 } 3244 PackageParser.Activity a = mActivities.mActivities.get(component); 3245 if (a == null) { 3246 return false; 3247 } 3248 for (int i=0; i<a.intents.size(); i++) { 3249 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3250 intent.getData(), intent.getCategories(), TAG) >= 0) { 3251 return true; 3252 } 3253 } 3254 return false; 3255 } 3256 } 3257 3258 @Override 3259 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3260 if (!sUserManager.exists(userId)) return null; 3261 flags = updateFlagsForComponent(flags, userId, component); 3262 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3263 synchronized (mPackages) { 3264 PackageParser.Activity a = mReceivers.mActivities.get(component); 3265 if (DEBUG_PACKAGE_INFO) Log.v( 3266 TAG, "getReceiverInfo " + component + ": " + a); 3267 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3268 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3269 if (ps == null) return null; 3270 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3271 userId); 3272 } 3273 } 3274 return null; 3275 } 3276 3277 @Override 3278 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForComponent(flags, userId, component); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3282 synchronized (mPackages) { 3283 PackageParser.Service s = mServices.mServices.get(component); 3284 if (DEBUG_PACKAGE_INFO) Log.v( 3285 TAG, "getServiceInfo " + component + ": " + s); 3286 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3287 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3288 if (ps == null) return null; 3289 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3290 userId); 3291 } 3292 } 3293 return null; 3294 } 3295 3296 @Override 3297 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3298 if (!sUserManager.exists(userId)) return null; 3299 flags = updateFlagsForComponent(flags, userId, component); 3300 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3301 synchronized (mPackages) { 3302 PackageParser.Provider p = mProviders.mProviders.get(component); 3303 if (DEBUG_PACKAGE_INFO) Log.v( 3304 TAG, "getProviderInfo " + component + ": " + p); 3305 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3306 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3307 if (ps == null) return null; 3308 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3309 userId); 3310 } 3311 } 3312 return null; 3313 } 3314 3315 @Override 3316 public String[] getSystemSharedLibraryNames() { 3317 Set<String> libSet; 3318 synchronized (mPackages) { 3319 libSet = mSharedLibraries.keySet(); 3320 int size = libSet.size(); 3321 if (size > 0) { 3322 String[] libs = new String[size]; 3323 libSet.toArray(libs); 3324 return libs; 3325 } 3326 } 3327 return null; 3328 } 3329 3330 /** 3331 * @hide 3332 */ 3333 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3334 synchronized (mPackages) { 3335 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3336 if (lib != null && lib.apk != null) { 3337 return mPackages.get(lib.apk); 3338 } 3339 } 3340 return null; 3341 } 3342 3343 @Override 3344 public FeatureInfo[] getSystemAvailableFeatures() { 3345 Collection<FeatureInfo> featSet; 3346 synchronized (mPackages) { 3347 featSet = mAvailableFeatures.values(); 3348 int size = featSet.size(); 3349 if (size > 0) { 3350 FeatureInfo[] features = new FeatureInfo[size+1]; 3351 featSet.toArray(features); 3352 FeatureInfo fi = new FeatureInfo(); 3353 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3354 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3355 features[size] = fi; 3356 return features; 3357 } 3358 } 3359 return null; 3360 } 3361 3362 @Override 3363 public boolean hasSystemFeature(String name) { 3364 synchronized (mPackages) { 3365 return mAvailableFeatures.containsKey(name); 3366 } 3367 } 3368 3369 @Override 3370 public int checkPermission(String permName, String pkgName, int userId) { 3371 if (!sUserManager.exists(userId)) { 3372 return PackageManager.PERMISSION_DENIED; 3373 } 3374 3375 synchronized (mPackages) { 3376 final PackageParser.Package p = mPackages.get(pkgName); 3377 if (p != null && p.mExtras != null) { 3378 final PackageSetting ps = (PackageSetting) p.mExtras; 3379 final PermissionsState permissionsState = ps.getPermissionsState(); 3380 if (permissionsState.hasPermission(permName, userId)) { 3381 return PackageManager.PERMISSION_GRANTED; 3382 } 3383 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3384 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3385 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3386 return PackageManager.PERMISSION_GRANTED; 3387 } 3388 } 3389 } 3390 3391 return PackageManager.PERMISSION_DENIED; 3392 } 3393 3394 @Override 3395 public int checkUidPermission(String permName, int uid) { 3396 final int userId = UserHandle.getUserId(uid); 3397 3398 if (!sUserManager.exists(userId)) { 3399 return PackageManager.PERMISSION_DENIED; 3400 } 3401 3402 synchronized (mPackages) { 3403 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3404 if (obj != null) { 3405 final SettingBase ps = (SettingBase) obj; 3406 final PermissionsState permissionsState = ps.getPermissionsState(); 3407 if (permissionsState.hasPermission(permName, userId)) { 3408 return PackageManager.PERMISSION_GRANTED; 3409 } 3410 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3411 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3412 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3413 return PackageManager.PERMISSION_GRANTED; 3414 } 3415 } else { 3416 ArraySet<String> perms = mSystemPermissions.get(uid); 3417 if (perms != null) { 3418 if (perms.contains(permName)) { 3419 return PackageManager.PERMISSION_GRANTED; 3420 } 3421 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3422 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3423 return PackageManager.PERMISSION_GRANTED; 3424 } 3425 } 3426 } 3427 } 3428 3429 return PackageManager.PERMISSION_DENIED; 3430 } 3431 3432 @Override 3433 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3434 if (UserHandle.getCallingUserId() != userId) { 3435 mContext.enforceCallingPermission( 3436 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3437 "isPermissionRevokedByPolicy for user " + userId); 3438 } 3439 3440 if (checkPermission(permission, packageName, userId) 3441 == PackageManager.PERMISSION_GRANTED) { 3442 return false; 3443 } 3444 3445 final long identity = Binder.clearCallingIdentity(); 3446 try { 3447 final int flags = getPermissionFlags(permission, packageName, userId); 3448 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3449 } finally { 3450 Binder.restoreCallingIdentity(identity); 3451 } 3452 } 3453 3454 @Override 3455 public String getPermissionControllerPackageName() { 3456 synchronized (mPackages) { 3457 return mRequiredInstallerPackage; 3458 } 3459 } 3460 3461 /** 3462 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3463 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3464 * @param checkShell TODO(yamasani): 3465 * @param message the message to log on security exception 3466 */ 3467 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3468 boolean checkShell, String message) { 3469 if (userId < 0) { 3470 throw new IllegalArgumentException("Invalid userId " + userId); 3471 } 3472 if (checkShell) { 3473 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3474 } 3475 if (userId == UserHandle.getUserId(callingUid)) return; 3476 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3477 if (requireFullPermission) { 3478 mContext.enforceCallingOrSelfPermission( 3479 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3480 } else { 3481 try { 3482 mContext.enforceCallingOrSelfPermission( 3483 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3484 } catch (SecurityException se) { 3485 mContext.enforceCallingOrSelfPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3487 } 3488 } 3489 } 3490 } 3491 3492 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3493 if (callingUid == Process.SHELL_UID) { 3494 if (userHandle >= 0 3495 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3496 throw new SecurityException("Shell does not have permission to access user " 3497 + userHandle); 3498 } else if (userHandle < 0) { 3499 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3500 + Debug.getCallers(3)); 3501 } 3502 } 3503 } 3504 3505 private BasePermission findPermissionTreeLP(String permName) { 3506 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3507 if (permName.startsWith(bp.name) && 3508 permName.length() > bp.name.length() && 3509 permName.charAt(bp.name.length()) == '.') { 3510 return bp; 3511 } 3512 } 3513 return null; 3514 } 3515 3516 private BasePermission checkPermissionTreeLP(String permName) { 3517 if (permName != null) { 3518 BasePermission bp = findPermissionTreeLP(permName); 3519 if (bp != null) { 3520 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3521 return bp; 3522 } 3523 throw new SecurityException("Calling uid " 3524 + Binder.getCallingUid() 3525 + " is not allowed to add to permission tree " 3526 + bp.name + " owned by uid " + bp.uid); 3527 } 3528 } 3529 throw new SecurityException("No permission tree found for " + permName); 3530 } 3531 3532 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3533 if (s1 == null) { 3534 return s2 == null; 3535 } 3536 if (s2 == null) { 3537 return false; 3538 } 3539 if (s1.getClass() != s2.getClass()) { 3540 return false; 3541 } 3542 return s1.equals(s2); 3543 } 3544 3545 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3546 if (pi1.icon != pi2.icon) return false; 3547 if (pi1.logo != pi2.logo) return false; 3548 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3549 if (!compareStrings(pi1.name, pi2.name)) return false; 3550 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3551 // We'll take care of setting this one. 3552 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3553 // These are not currently stored in settings. 3554 //if (!compareStrings(pi1.group, pi2.group)) return false; 3555 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3556 //if (pi1.labelRes != pi2.labelRes) return false; 3557 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3558 return true; 3559 } 3560 3561 int permissionInfoFootprint(PermissionInfo info) { 3562 int size = info.name.length(); 3563 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3564 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3565 return size; 3566 } 3567 3568 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3569 int size = 0; 3570 for (BasePermission perm : mSettings.mPermissions.values()) { 3571 if (perm.uid == tree.uid) { 3572 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3573 } 3574 } 3575 return size; 3576 } 3577 3578 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3579 // We calculate the max size of permissions defined by this uid and throw 3580 // if that plus the size of 'info' would exceed our stated maximum. 3581 if (tree.uid != Process.SYSTEM_UID) { 3582 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3583 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3584 throw new SecurityException("Permission tree size cap exceeded"); 3585 } 3586 } 3587 } 3588 3589 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3590 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3591 throw new SecurityException("Label must be specified in permission"); 3592 } 3593 BasePermission tree = checkPermissionTreeLP(info.name); 3594 BasePermission bp = mSettings.mPermissions.get(info.name); 3595 boolean added = bp == null; 3596 boolean changed = true; 3597 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3598 if (added) { 3599 enforcePermissionCapLocked(info, tree); 3600 bp = new BasePermission(info.name, tree.sourcePackage, 3601 BasePermission.TYPE_DYNAMIC); 3602 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3603 throw new SecurityException( 3604 "Not allowed to modify non-dynamic permission " 3605 + info.name); 3606 } else { 3607 if (bp.protectionLevel == fixedLevel 3608 && bp.perm.owner.equals(tree.perm.owner) 3609 && bp.uid == tree.uid 3610 && comparePermissionInfos(bp.perm.info, info)) { 3611 changed = false; 3612 } 3613 } 3614 bp.protectionLevel = fixedLevel; 3615 info = new PermissionInfo(info); 3616 info.protectionLevel = fixedLevel; 3617 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3618 bp.perm.info.packageName = tree.perm.info.packageName; 3619 bp.uid = tree.uid; 3620 if (added) { 3621 mSettings.mPermissions.put(info.name, bp); 3622 } 3623 if (changed) { 3624 if (!async) { 3625 mSettings.writeLPr(); 3626 } else { 3627 scheduleWriteSettingsLocked(); 3628 } 3629 } 3630 return added; 3631 } 3632 3633 @Override 3634 public boolean addPermission(PermissionInfo info) { 3635 synchronized (mPackages) { 3636 return addPermissionLocked(info, false); 3637 } 3638 } 3639 3640 @Override 3641 public boolean addPermissionAsync(PermissionInfo info) { 3642 synchronized (mPackages) { 3643 return addPermissionLocked(info, true); 3644 } 3645 } 3646 3647 @Override 3648 public void removePermission(String name) { 3649 synchronized (mPackages) { 3650 checkPermissionTreeLP(name); 3651 BasePermission bp = mSettings.mPermissions.get(name); 3652 if (bp != null) { 3653 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3654 throw new SecurityException( 3655 "Not allowed to modify non-dynamic permission " 3656 + name); 3657 } 3658 mSettings.mPermissions.remove(name); 3659 mSettings.writeLPr(); 3660 } 3661 } 3662 } 3663 3664 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3665 BasePermission bp) { 3666 int index = pkg.requestedPermissions.indexOf(bp.name); 3667 if (index == -1) { 3668 throw new SecurityException("Package " + pkg.packageName 3669 + " has not requested permission " + bp.name); 3670 } 3671 if (!bp.isRuntime() && !bp.isDevelopment()) { 3672 throw new SecurityException("Permission " + bp.name 3673 + " is not a changeable permission type"); 3674 } 3675 } 3676 3677 @Override 3678 public void grantRuntimePermission(String packageName, String name, final int userId) { 3679 if (!sUserManager.exists(userId)) { 3680 Log.e(TAG, "No such user:" + userId); 3681 return; 3682 } 3683 3684 mContext.enforceCallingOrSelfPermission( 3685 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3686 "grantRuntimePermission"); 3687 3688 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3689 "grantRuntimePermission"); 3690 3691 final int uid; 3692 final SettingBase sb; 3693 3694 synchronized (mPackages) { 3695 final PackageParser.Package pkg = mPackages.get(packageName); 3696 if (pkg == null) { 3697 throw new IllegalArgumentException("Unknown package: " + packageName); 3698 } 3699 3700 final BasePermission bp = mSettings.mPermissions.get(name); 3701 if (bp == null) { 3702 throw new IllegalArgumentException("Unknown permission: " + name); 3703 } 3704 3705 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3706 3707 // If a permission review is required for legacy apps we represent 3708 // their permissions as always granted runtime ones since we need 3709 // to keep the review required permission flag per user while an 3710 // install permission's state is shared across all users. 3711 if (Build.PERMISSIONS_REVIEW_REQUIRED 3712 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3713 && bp.isRuntime()) { 3714 return; 3715 } 3716 3717 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3718 sb = (SettingBase) pkg.mExtras; 3719 if (sb == null) { 3720 throw new IllegalArgumentException("Unknown package: " + packageName); 3721 } 3722 3723 final PermissionsState permissionsState = sb.getPermissionsState(); 3724 3725 final int flags = permissionsState.getPermissionFlags(name, userId); 3726 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3727 throw new SecurityException("Cannot grant system fixed permission " 3728 + name + " for package " + packageName); 3729 } 3730 3731 if (bp.isDevelopment()) { 3732 // Development permissions must be handled specially, since they are not 3733 // normal runtime permissions. For now they apply to all users. 3734 if (permissionsState.grantInstallPermission(bp) != 3735 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3736 scheduleWriteSettingsLocked(); 3737 } 3738 return; 3739 } 3740 3741 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3742 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3743 return; 3744 } 3745 3746 final int result = permissionsState.grantRuntimePermission(bp, userId); 3747 switch (result) { 3748 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3749 return; 3750 } 3751 3752 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3753 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3754 mHandler.post(new Runnable() { 3755 @Override 3756 public void run() { 3757 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3758 } 3759 }); 3760 } 3761 break; 3762 } 3763 3764 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3765 3766 // Not critical if that is lost - app has to request again. 3767 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3768 } 3769 3770 // Only need to do this if user is initialized. Otherwise it's a new user 3771 // and there are no processes running as the user yet and there's no need 3772 // to make an expensive call to remount processes for the changed permissions. 3773 if (READ_EXTERNAL_STORAGE.equals(name) 3774 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3775 final long token = Binder.clearCallingIdentity(); 3776 try { 3777 if (sUserManager.isInitialized(userId)) { 3778 MountServiceInternal mountServiceInternal = LocalServices.getService( 3779 MountServiceInternal.class); 3780 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3781 } 3782 } finally { 3783 Binder.restoreCallingIdentity(token); 3784 } 3785 } 3786 } 3787 3788 @Override 3789 public void revokeRuntimePermission(String packageName, String name, int userId) { 3790 if (!sUserManager.exists(userId)) { 3791 Log.e(TAG, "No such user:" + userId); 3792 return; 3793 } 3794 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3797 "revokeRuntimePermission"); 3798 3799 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3800 "revokeRuntimePermission"); 3801 3802 final int appId; 3803 3804 synchronized (mPackages) { 3805 final PackageParser.Package pkg = mPackages.get(packageName); 3806 if (pkg == null) { 3807 throw new IllegalArgumentException("Unknown package: " + packageName); 3808 } 3809 3810 final BasePermission bp = mSettings.mPermissions.get(name); 3811 if (bp == null) { 3812 throw new IllegalArgumentException("Unknown permission: " + name); 3813 } 3814 3815 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3816 3817 // If a permission review is required for legacy apps we represent 3818 // their permissions as always granted runtime ones since we need 3819 // to keep the review required permission flag per user while an 3820 // install permission's state is shared across all users. 3821 if (Build.PERMISSIONS_REVIEW_REQUIRED 3822 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3823 && bp.isRuntime()) { 3824 return; 3825 } 3826 3827 SettingBase sb = (SettingBase) pkg.mExtras; 3828 if (sb == null) { 3829 throw new IllegalArgumentException("Unknown package: " + packageName); 3830 } 3831 3832 final PermissionsState permissionsState = sb.getPermissionsState(); 3833 3834 final int flags = permissionsState.getPermissionFlags(name, userId); 3835 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3836 throw new SecurityException("Cannot revoke system fixed permission " 3837 + name + " for package " + packageName); 3838 } 3839 3840 if (bp.isDevelopment()) { 3841 // Development permissions must be handled specially, since they are not 3842 // normal runtime permissions. For now they apply to all users. 3843 if (permissionsState.revokeInstallPermission(bp) != 3844 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3845 scheduleWriteSettingsLocked(); 3846 } 3847 return; 3848 } 3849 3850 if (permissionsState.revokeRuntimePermission(bp, userId) == 3851 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3852 return; 3853 } 3854 3855 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3856 3857 // Critical, after this call app should never have the permission. 3858 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3859 3860 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3861 } 3862 3863 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3864 } 3865 3866 @Override 3867 public void resetRuntimePermissions() { 3868 mContext.enforceCallingOrSelfPermission( 3869 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3870 "revokeRuntimePermission"); 3871 3872 int callingUid = Binder.getCallingUid(); 3873 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3874 mContext.enforceCallingOrSelfPermission( 3875 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3876 "resetRuntimePermissions"); 3877 } 3878 3879 synchronized (mPackages) { 3880 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3881 for (int userId : UserManagerService.getInstance().getUserIds()) { 3882 final int packageCount = mPackages.size(); 3883 for (int i = 0; i < packageCount; i++) { 3884 PackageParser.Package pkg = mPackages.valueAt(i); 3885 if (!(pkg.mExtras instanceof PackageSetting)) { 3886 continue; 3887 } 3888 PackageSetting ps = (PackageSetting) pkg.mExtras; 3889 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3890 } 3891 } 3892 } 3893 } 3894 3895 @Override 3896 public int getPermissionFlags(String name, String packageName, int userId) { 3897 if (!sUserManager.exists(userId)) { 3898 return 0; 3899 } 3900 3901 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3902 3903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3904 "getPermissionFlags"); 3905 3906 synchronized (mPackages) { 3907 final PackageParser.Package pkg = mPackages.get(packageName); 3908 if (pkg == null) { 3909 throw new IllegalArgumentException("Unknown package: " + packageName); 3910 } 3911 3912 final BasePermission bp = mSettings.mPermissions.get(name); 3913 if (bp == null) { 3914 throw new IllegalArgumentException("Unknown permission: " + name); 3915 } 3916 3917 SettingBase sb = (SettingBase) pkg.mExtras; 3918 if (sb == null) { 3919 throw new IllegalArgumentException("Unknown package: " + packageName); 3920 } 3921 3922 PermissionsState permissionsState = sb.getPermissionsState(); 3923 return permissionsState.getPermissionFlags(name, userId); 3924 } 3925 } 3926 3927 @Override 3928 public void updatePermissionFlags(String name, String packageName, int flagMask, 3929 int flagValues, int userId) { 3930 if (!sUserManager.exists(userId)) { 3931 return; 3932 } 3933 3934 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3935 3936 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3937 "updatePermissionFlags"); 3938 3939 // Only the system can change these flags and nothing else. 3940 if (getCallingUid() != Process.SYSTEM_UID) { 3941 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3942 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3943 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3944 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3945 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3946 } 3947 3948 synchronized (mPackages) { 3949 final PackageParser.Package pkg = mPackages.get(packageName); 3950 if (pkg == null) { 3951 throw new IllegalArgumentException("Unknown package: " + packageName); 3952 } 3953 3954 final BasePermission bp = mSettings.mPermissions.get(name); 3955 if (bp == null) { 3956 throw new IllegalArgumentException("Unknown permission: " + name); 3957 } 3958 3959 SettingBase sb = (SettingBase) pkg.mExtras; 3960 if (sb == null) { 3961 throw new IllegalArgumentException("Unknown package: " + packageName); 3962 } 3963 3964 PermissionsState permissionsState = sb.getPermissionsState(); 3965 3966 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3967 3968 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3969 // Install and runtime permissions are stored in different places, 3970 // so figure out what permission changed and persist the change. 3971 if (permissionsState.getInstallPermissionState(name) != null) { 3972 scheduleWriteSettingsLocked(); 3973 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3974 || hadState) { 3975 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3976 } 3977 } 3978 } 3979 } 3980 3981 /** 3982 * Update the permission flags for all packages and runtime permissions of a user in order 3983 * to allow device or profile owner to remove POLICY_FIXED. 3984 */ 3985 @Override 3986 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3987 if (!sUserManager.exists(userId)) { 3988 return; 3989 } 3990 3991 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3992 3993 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3994 "updatePermissionFlagsForAllApps"); 3995 3996 // Only the system can change system fixed flags. 3997 if (getCallingUid() != Process.SYSTEM_UID) { 3998 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3999 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4000 } 4001 4002 synchronized (mPackages) { 4003 boolean changed = false; 4004 final int packageCount = mPackages.size(); 4005 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4006 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4007 SettingBase sb = (SettingBase) pkg.mExtras; 4008 if (sb == null) { 4009 continue; 4010 } 4011 PermissionsState permissionsState = sb.getPermissionsState(); 4012 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4013 userId, flagMask, flagValues); 4014 } 4015 if (changed) { 4016 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4017 } 4018 } 4019 } 4020 4021 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4022 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4023 != PackageManager.PERMISSION_GRANTED 4024 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4025 != PackageManager.PERMISSION_GRANTED) { 4026 throw new SecurityException(message + " requires " 4027 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4028 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4029 } 4030 } 4031 4032 @Override 4033 public boolean shouldShowRequestPermissionRationale(String permissionName, 4034 String packageName, int userId) { 4035 if (UserHandle.getCallingUserId() != userId) { 4036 mContext.enforceCallingPermission( 4037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4038 "canShowRequestPermissionRationale for user " + userId); 4039 } 4040 4041 final int uid = getPackageUid(packageName, userId); 4042 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4043 return false; 4044 } 4045 4046 if (checkPermission(permissionName, packageName, userId) 4047 == PackageManager.PERMISSION_GRANTED) { 4048 return false; 4049 } 4050 4051 final int flags; 4052 4053 final long identity = Binder.clearCallingIdentity(); 4054 try { 4055 flags = getPermissionFlags(permissionName, 4056 packageName, userId); 4057 } finally { 4058 Binder.restoreCallingIdentity(identity); 4059 } 4060 4061 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4062 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4063 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4064 4065 if ((flags & fixedFlags) != 0) { 4066 return false; 4067 } 4068 4069 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4070 } 4071 4072 @Override 4073 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4074 mContext.enforceCallingOrSelfPermission( 4075 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4076 "addOnPermissionsChangeListener"); 4077 4078 synchronized (mPackages) { 4079 mOnPermissionChangeListeners.addListenerLocked(listener); 4080 } 4081 } 4082 4083 @Override 4084 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4085 synchronized (mPackages) { 4086 mOnPermissionChangeListeners.removeListenerLocked(listener); 4087 } 4088 } 4089 4090 @Override 4091 public boolean isProtectedBroadcast(String actionName) { 4092 synchronized (mPackages) { 4093 if (mProtectedBroadcasts.contains(actionName)) { 4094 return true; 4095 } else if (actionName != null) { 4096 // TODO: remove these terrible hacks 4097 if (actionName.startsWith("android.net.netmon.lingerExpired") 4098 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4099 return true; 4100 } 4101 } 4102 } 4103 return false; 4104 } 4105 4106 @Override 4107 public int checkSignatures(String pkg1, String pkg2) { 4108 synchronized (mPackages) { 4109 final PackageParser.Package p1 = mPackages.get(pkg1); 4110 final PackageParser.Package p2 = mPackages.get(pkg2); 4111 if (p1 == null || p1.mExtras == null 4112 || p2 == null || p2.mExtras == null) { 4113 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4114 } 4115 return compareSignatures(p1.mSignatures, p2.mSignatures); 4116 } 4117 } 4118 4119 @Override 4120 public int checkUidSignatures(int uid1, int uid2) { 4121 // Map to base uids. 4122 uid1 = UserHandle.getAppId(uid1); 4123 uid2 = UserHandle.getAppId(uid2); 4124 // reader 4125 synchronized (mPackages) { 4126 Signature[] s1; 4127 Signature[] s2; 4128 Object obj = mSettings.getUserIdLPr(uid1); 4129 if (obj != null) { 4130 if (obj instanceof SharedUserSetting) { 4131 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4132 } else if (obj instanceof PackageSetting) { 4133 s1 = ((PackageSetting)obj).signatures.mSignatures; 4134 } else { 4135 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4136 } 4137 } else { 4138 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4139 } 4140 obj = mSettings.getUserIdLPr(uid2); 4141 if (obj != null) { 4142 if (obj instanceof SharedUserSetting) { 4143 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4144 } else if (obj instanceof PackageSetting) { 4145 s2 = ((PackageSetting)obj).signatures.mSignatures; 4146 } else { 4147 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4148 } 4149 } else { 4150 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4151 } 4152 return compareSignatures(s1, s2); 4153 } 4154 } 4155 4156 private void killUid(int appId, int userId, String reason) { 4157 final long identity = Binder.clearCallingIdentity(); 4158 try { 4159 IActivityManager am = ActivityManagerNative.getDefault(); 4160 if (am != null) { 4161 try { 4162 am.killUid(appId, userId, reason); 4163 } catch (RemoteException e) { 4164 /* ignore - same process */ 4165 } 4166 } 4167 } finally { 4168 Binder.restoreCallingIdentity(identity); 4169 } 4170 } 4171 4172 /** 4173 * Compares two sets of signatures. Returns: 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4176 * <br /> 4177 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4178 * <br /> 4179 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4180 * <br /> 4181 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4182 * <br /> 4183 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4184 */ 4185 static int compareSignatures(Signature[] s1, Signature[] s2) { 4186 if (s1 == null) { 4187 return s2 == null 4188 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4189 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4190 } 4191 4192 if (s2 == null) { 4193 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4194 } 4195 4196 if (s1.length != s2.length) { 4197 return PackageManager.SIGNATURE_NO_MATCH; 4198 } 4199 4200 // Since both signature sets are of size 1, we can compare without HashSets. 4201 if (s1.length == 1) { 4202 return s1[0].equals(s2[0]) ? 4203 PackageManager.SIGNATURE_MATCH : 4204 PackageManager.SIGNATURE_NO_MATCH; 4205 } 4206 4207 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4208 for (Signature sig : s1) { 4209 set1.add(sig); 4210 } 4211 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4212 for (Signature sig : s2) { 4213 set2.add(sig); 4214 } 4215 // Make sure s2 contains all signatures in s1. 4216 if (set1.equals(set2)) { 4217 return PackageManager.SIGNATURE_MATCH; 4218 } 4219 return PackageManager.SIGNATURE_NO_MATCH; 4220 } 4221 4222 /** 4223 * If the database version for this type of package (internal storage or 4224 * external storage) is less than the version where package signatures 4225 * were updated, return true. 4226 */ 4227 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4228 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4229 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4230 } 4231 4232 /** 4233 * Used for backward compatibility to make sure any packages with 4234 * certificate chains get upgraded to the new style. {@code existingSigs} 4235 * will be in the old format (since they were stored on disk from before the 4236 * system upgrade) and {@code scannedSigs} will be in the newer format. 4237 */ 4238 private int compareSignaturesCompat(PackageSignatures existingSigs, 4239 PackageParser.Package scannedPkg) { 4240 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4241 return PackageManager.SIGNATURE_NO_MATCH; 4242 } 4243 4244 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4245 for (Signature sig : existingSigs.mSignatures) { 4246 existingSet.add(sig); 4247 } 4248 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4249 for (Signature sig : scannedPkg.mSignatures) { 4250 try { 4251 Signature[] chainSignatures = sig.getChainSignatures(); 4252 for (Signature chainSig : chainSignatures) { 4253 scannedCompatSet.add(chainSig); 4254 } 4255 } catch (CertificateEncodingException e) { 4256 scannedCompatSet.add(sig); 4257 } 4258 } 4259 /* 4260 * Make sure the expanded scanned set contains all signatures in the 4261 * existing one. 4262 */ 4263 if (scannedCompatSet.equals(existingSet)) { 4264 // Migrate the old signatures to the new scheme. 4265 existingSigs.assignSignatures(scannedPkg.mSignatures); 4266 // The new KeySets will be re-added later in the scanning process. 4267 synchronized (mPackages) { 4268 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4269 } 4270 return PackageManager.SIGNATURE_MATCH; 4271 } 4272 return PackageManager.SIGNATURE_NO_MATCH; 4273 } 4274 4275 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4276 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4277 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4278 } 4279 4280 private int compareSignaturesRecover(PackageSignatures existingSigs, 4281 PackageParser.Package scannedPkg) { 4282 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4283 return PackageManager.SIGNATURE_NO_MATCH; 4284 } 4285 4286 String msg = null; 4287 try { 4288 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4289 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4290 + scannedPkg.packageName); 4291 return PackageManager.SIGNATURE_MATCH; 4292 } 4293 } catch (CertificateException e) { 4294 msg = e.getMessage(); 4295 } 4296 4297 logCriticalInfo(Log.INFO, 4298 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4299 return PackageManager.SIGNATURE_NO_MATCH; 4300 } 4301 4302 @Override 4303 public String[] getPackagesForUid(int uid) { 4304 uid = UserHandle.getAppId(uid); 4305 // reader 4306 synchronized (mPackages) { 4307 Object obj = mSettings.getUserIdLPr(uid); 4308 if (obj instanceof SharedUserSetting) { 4309 final SharedUserSetting sus = (SharedUserSetting) obj; 4310 final int N = sus.packages.size(); 4311 final String[] res = new String[N]; 4312 final Iterator<PackageSetting> it = sus.packages.iterator(); 4313 int i = 0; 4314 while (it.hasNext()) { 4315 res[i++] = it.next().name; 4316 } 4317 return res; 4318 } else if (obj instanceof PackageSetting) { 4319 final PackageSetting ps = (PackageSetting) obj; 4320 return new String[] { ps.name }; 4321 } 4322 } 4323 return null; 4324 } 4325 4326 @Override 4327 public String getNameForUid(int uid) { 4328 // reader 4329 synchronized (mPackages) { 4330 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4331 if (obj instanceof SharedUserSetting) { 4332 final SharedUserSetting sus = (SharedUserSetting) obj; 4333 return sus.name + ":" + sus.userId; 4334 } else if (obj instanceof PackageSetting) { 4335 final PackageSetting ps = (PackageSetting) obj; 4336 return ps.name; 4337 } 4338 } 4339 return null; 4340 } 4341 4342 @Override 4343 public int getUidForSharedUser(String sharedUserName) { 4344 if(sharedUserName == null) { 4345 return -1; 4346 } 4347 // reader 4348 synchronized (mPackages) { 4349 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4350 if (suid == null) { 4351 return -1; 4352 } 4353 return suid.userId; 4354 } 4355 } 4356 4357 @Override 4358 public int getFlagsForUid(int uid) { 4359 synchronized (mPackages) { 4360 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4361 if (obj instanceof SharedUserSetting) { 4362 final SharedUserSetting sus = (SharedUserSetting) obj; 4363 return sus.pkgFlags; 4364 } else if (obj instanceof PackageSetting) { 4365 final PackageSetting ps = (PackageSetting) obj; 4366 return ps.pkgFlags; 4367 } 4368 } 4369 return 0; 4370 } 4371 4372 @Override 4373 public int getPrivateFlagsForUid(int uid) { 4374 synchronized (mPackages) { 4375 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4376 if (obj instanceof SharedUserSetting) { 4377 final SharedUserSetting sus = (SharedUserSetting) obj; 4378 return sus.pkgPrivateFlags; 4379 } else if (obj instanceof PackageSetting) { 4380 final PackageSetting ps = (PackageSetting) obj; 4381 return ps.pkgPrivateFlags; 4382 } 4383 } 4384 return 0; 4385 } 4386 4387 @Override 4388 public boolean isUidPrivileged(int uid) { 4389 uid = UserHandle.getAppId(uid); 4390 // reader 4391 synchronized (mPackages) { 4392 Object obj = mSettings.getUserIdLPr(uid); 4393 if (obj instanceof SharedUserSetting) { 4394 final SharedUserSetting sus = (SharedUserSetting) obj; 4395 final Iterator<PackageSetting> it = sus.packages.iterator(); 4396 while (it.hasNext()) { 4397 if (it.next().isPrivileged()) { 4398 return true; 4399 } 4400 } 4401 } else if (obj instanceof PackageSetting) { 4402 final PackageSetting ps = (PackageSetting) obj; 4403 return ps.isPrivileged(); 4404 } 4405 } 4406 return false; 4407 } 4408 4409 @Override 4410 public String[] getAppOpPermissionPackages(String permissionName) { 4411 synchronized (mPackages) { 4412 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4413 if (pkgs == null) { 4414 return null; 4415 } 4416 return pkgs.toArray(new String[pkgs.size()]); 4417 } 4418 } 4419 4420 @Override 4421 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4422 int flags, int userId) { 4423 if (!sUserManager.exists(userId)) return null; 4424 flags = updateFlagsForResolve(flags, userId, intent); 4425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4426 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4427 final ResolveInfo bestChoice = 4428 chooseBestActivity(intent, resolvedType, flags, query, userId); 4429 4430 if (isEphemeralAllowed(intent, query, userId)) { 4431 final EphemeralResolveInfo ai = 4432 getEphemeralResolveInfo(intent, resolvedType, userId); 4433 if (ai != null) { 4434 if (DEBUG_EPHEMERAL) { 4435 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4436 } 4437 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4438 bestChoice.ephemeralResolveInfo = ai; 4439 } 4440 } 4441 return bestChoice; 4442 } 4443 4444 @Override 4445 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4446 IntentFilter filter, int match, ComponentName activity) { 4447 final int userId = UserHandle.getCallingUserId(); 4448 if (DEBUG_PREFERRED) { 4449 Log.v(TAG, "setLastChosenActivity intent=" + intent 4450 + " resolvedType=" + resolvedType 4451 + " flags=" + flags 4452 + " filter=" + filter 4453 + " match=" + match 4454 + " activity=" + activity); 4455 filter.dump(new PrintStreamPrinter(System.out), " "); 4456 } 4457 intent.setComponent(null); 4458 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4459 // Find any earlier preferred or last chosen entries and nuke them 4460 findPreferredActivity(intent, resolvedType, 4461 flags, query, 0, false, true, false, userId); 4462 // Add the new activity as the last chosen for this filter 4463 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4464 "Setting last chosen"); 4465 } 4466 4467 @Override 4468 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4469 final int userId = UserHandle.getCallingUserId(); 4470 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4471 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4472 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4473 false, false, false, userId); 4474 } 4475 4476 4477 private boolean isEphemeralAllowed( 4478 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4479 // Short circuit and return early if possible. 4480 final int callingUser = UserHandle.getCallingUserId(); 4481 if (callingUser != UserHandle.USER_SYSTEM) { 4482 return false; 4483 } 4484 if (mEphemeralResolverConnection == null) { 4485 return false; 4486 } 4487 if (intent.getComponent() != null) { 4488 return false; 4489 } 4490 if (intent.getPackage() != null) { 4491 return false; 4492 } 4493 final boolean isWebUri = hasWebURI(intent); 4494 if (!isWebUri) { 4495 return false; 4496 } 4497 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4498 synchronized (mPackages) { 4499 final int count = resolvedActivites.size(); 4500 for (int n = 0; n < count; n++) { 4501 ResolveInfo info = resolvedActivites.get(n); 4502 String packageName = info.activityInfo.packageName; 4503 PackageSetting ps = mSettings.mPackages.get(packageName); 4504 if (ps != null) { 4505 // Try to get the status from User settings first 4506 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4507 int status = (int) (packedStatus >> 32); 4508 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4509 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4510 if (DEBUG_EPHEMERAL) { 4511 Slog.v(TAG, "DENY ephemeral apps;" 4512 + " pkg: " + packageName + ", status: " + status); 4513 } 4514 return false; 4515 } 4516 } 4517 } 4518 } 4519 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4520 return true; 4521 } 4522 4523 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4524 int userId) { 4525 MessageDigest digest = null; 4526 try { 4527 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4528 } catch (NoSuchAlgorithmException e) { 4529 // If we can't create a digest, ignore ephemeral apps. 4530 return null; 4531 } 4532 4533 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4534 final byte[] digestBytes = digest.digest(hostBytes); 4535 int shaPrefix = 4536 digestBytes[0] << 24 4537 | digestBytes[1] << 16 4538 | digestBytes[2] << 8 4539 | digestBytes[3] << 0; 4540 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4541 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4542 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4543 // No hash prefix match; there are no ephemeral apps for this domain. 4544 return null; 4545 } 4546 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4547 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4548 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4549 continue; 4550 } 4551 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4552 // No filters; this should never happen. 4553 if (filters.isEmpty()) { 4554 continue; 4555 } 4556 // We have a domain match; resolve the filters to see if anything matches. 4557 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4558 for (int j = filters.size() - 1; j >= 0; --j) { 4559 final EphemeralResolveIntentInfo intentInfo = 4560 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4561 ephemeralResolver.addFilter(intentInfo); 4562 } 4563 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4564 intent, resolvedType, false /*defaultOnly*/, userId); 4565 if (!matchedResolveInfoList.isEmpty()) { 4566 return matchedResolveInfoList.get(0); 4567 } 4568 } 4569 // Hash or filter mis-match; no ephemeral apps for this domain. 4570 return null; 4571 } 4572 4573 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4574 int flags, List<ResolveInfo> query, int userId) { 4575 if (query != null) { 4576 final int N = query.size(); 4577 if (N == 1) { 4578 return query.get(0); 4579 } else if (N > 1) { 4580 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4581 // If there is more than one activity with the same priority, 4582 // then let the user decide between them. 4583 ResolveInfo r0 = query.get(0); 4584 ResolveInfo r1 = query.get(1); 4585 if (DEBUG_INTENT_MATCHING || debug) { 4586 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4587 + r1.activityInfo.name + "=" + r1.priority); 4588 } 4589 // If the first activity has a higher priority, or a different 4590 // default, then it is always desirable to pick it. 4591 if (r0.priority != r1.priority 4592 || r0.preferredOrder != r1.preferredOrder 4593 || r0.isDefault != r1.isDefault) { 4594 return query.get(0); 4595 } 4596 // If we have saved a preference for a preferred activity for 4597 // this Intent, use that. 4598 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4599 flags, query, r0.priority, true, false, debug, userId); 4600 if (ri != null) { 4601 return ri; 4602 } 4603 ri = new ResolveInfo(mResolveInfo); 4604 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4605 ri.activityInfo.applicationInfo = new ApplicationInfo( 4606 ri.activityInfo.applicationInfo); 4607 if (userId != 0) { 4608 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4609 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4610 } 4611 // Make sure that the resolver is displayable in car mode 4612 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4613 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4614 return ri; 4615 } 4616 } 4617 return null; 4618 } 4619 4620 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4621 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4622 final int N = query.size(); 4623 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4624 .get(userId); 4625 // Get the list of persistent preferred activities that handle the intent 4626 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4627 List<PersistentPreferredActivity> pprefs = ppir != null 4628 ? ppir.queryIntent(intent, resolvedType, 4629 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4630 : null; 4631 if (pprefs != null && pprefs.size() > 0) { 4632 final int M = pprefs.size(); 4633 for (int i=0; i<M; i++) { 4634 final PersistentPreferredActivity ppa = pprefs.get(i); 4635 if (DEBUG_PREFERRED || debug) { 4636 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4637 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4638 + "\n component=" + ppa.mComponent); 4639 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4640 } 4641 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4642 flags | MATCH_DISABLED_COMPONENTS, userId); 4643 if (DEBUG_PREFERRED || debug) { 4644 Slog.v(TAG, "Found persistent preferred activity:"); 4645 if (ai != null) { 4646 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4647 } else { 4648 Slog.v(TAG, " null"); 4649 } 4650 } 4651 if (ai == null) { 4652 // This previously registered persistent preferred activity 4653 // component is no longer known. Ignore it and do NOT remove it. 4654 continue; 4655 } 4656 for (int j=0; j<N; j++) { 4657 final ResolveInfo ri = query.get(j); 4658 if (!ri.activityInfo.applicationInfo.packageName 4659 .equals(ai.applicationInfo.packageName)) { 4660 continue; 4661 } 4662 if (!ri.activityInfo.name.equals(ai.name)) { 4663 continue; 4664 } 4665 // Found a persistent preference that can handle the intent. 4666 if (DEBUG_PREFERRED || debug) { 4667 Slog.v(TAG, "Returning persistent preferred activity: " + 4668 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4669 } 4670 return ri; 4671 } 4672 } 4673 } 4674 return null; 4675 } 4676 4677 // TODO: handle preferred activities missing while user has amnesia 4678 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4679 List<ResolveInfo> query, int priority, boolean always, 4680 boolean removeMatches, boolean debug, int userId) { 4681 if (!sUserManager.exists(userId)) return null; 4682 flags = updateFlagsForResolve(flags, userId, intent); 4683 // writer 4684 synchronized (mPackages) { 4685 if (intent.getSelector() != null) { 4686 intent = intent.getSelector(); 4687 } 4688 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4689 4690 // Try to find a matching persistent preferred activity. 4691 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4692 debug, userId); 4693 4694 // If a persistent preferred activity matched, use it. 4695 if (pri != null) { 4696 return pri; 4697 } 4698 4699 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4700 // Get the list of preferred activities that handle the intent 4701 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4702 List<PreferredActivity> prefs = pir != null 4703 ? pir.queryIntent(intent, resolvedType, 4704 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4705 : null; 4706 if (prefs != null && prefs.size() > 0) { 4707 boolean changed = false; 4708 try { 4709 // First figure out how good the original match set is. 4710 // We will only allow preferred activities that came 4711 // from the same match quality. 4712 int match = 0; 4713 4714 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4715 4716 final int N = query.size(); 4717 for (int j=0; j<N; j++) { 4718 final ResolveInfo ri = query.get(j); 4719 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4720 + ": 0x" + Integer.toHexString(match)); 4721 if (ri.match > match) { 4722 match = ri.match; 4723 } 4724 } 4725 4726 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4727 + Integer.toHexString(match)); 4728 4729 match &= IntentFilter.MATCH_CATEGORY_MASK; 4730 final int M = prefs.size(); 4731 for (int i=0; i<M; i++) { 4732 final PreferredActivity pa = prefs.get(i); 4733 if (DEBUG_PREFERRED || debug) { 4734 Slog.v(TAG, "Checking PreferredActivity ds=" 4735 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4736 + "\n component=" + pa.mPref.mComponent); 4737 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4738 } 4739 if (pa.mPref.mMatch != match) { 4740 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4741 + Integer.toHexString(pa.mPref.mMatch)); 4742 continue; 4743 } 4744 // If it's not an "always" type preferred activity and that's what we're 4745 // looking for, skip it. 4746 if (always && !pa.mPref.mAlways) { 4747 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4748 continue; 4749 } 4750 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4751 flags | MATCH_DISABLED_COMPONENTS, userId); 4752 if (DEBUG_PREFERRED || debug) { 4753 Slog.v(TAG, "Found preferred activity:"); 4754 if (ai != null) { 4755 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4756 } else { 4757 Slog.v(TAG, " null"); 4758 } 4759 } 4760 if (ai == null) { 4761 // This previously registered preferred activity 4762 // component is no longer known. Most likely an update 4763 // to the app was installed and in the new version this 4764 // component no longer exists. Clean it up by removing 4765 // it from the preferred activities list, and skip it. 4766 Slog.w(TAG, "Removing dangling preferred activity: " 4767 + pa.mPref.mComponent); 4768 pir.removeFilter(pa); 4769 changed = true; 4770 continue; 4771 } 4772 for (int j=0; j<N; j++) { 4773 final ResolveInfo ri = query.get(j); 4774 if (!ri.activityInfo.applicationInfo.packageName 4775 .equals(ai.applicationInfo.packageName)) { 4776 continue; 4777 } 4778 if (!ri.activityInfo.name.equals(ai.name)) { 4779 continue; 4780 } 4781 4782 if (removeMatches) { 4783 pir.removeFilter(pa); 4784 changed = true; 4785 if (DEBUG_PREFERRED) { 4786 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4787 } 4788 break; 4789 } 4790 4791 // Okay we found a previously set preferred or last chosen app. 4792 // If the result set is different from when this 4793 // was created, we need to clear it and re-ask the 4794 // user their preference, if we're looking for an "always" type entry. 4795 if (always && !pa.mPref.sameSet(query)) { 4796 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4797 + intent + " type " + resolvedType); 4798 if (DEBUG_PREFERRED) { 4799 Slog.v(TAG, "Removing preferred activity since set changed " 4800 + pa.mPref.mComponent); 4801 } 4802 pir.removeFilter(pa); 4803 // Re-add the filter as a "last chosen" entry (!always) 4804 PreferredActivity lastChosen = new PreferredActivity( 4805 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4806 pir.addFilter(lastChosen); 4807 changed = true; 4808 return null; 4809 } 4810 4811 // Yay! Either the set matched or we're looking for the last chosen 4812 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4813 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4814 return ri; 4815 } 4816 } 4817 } finally { 4818 if (changed) { 4819 if (DEBUG_PREFERRED) { 4820 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4821 } 4822 scheduleWritePackageRestrictionsLocked(userId); 4823 } 4824 } 4825 } 4826 } 4827 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4828 return null; 4829 } 4830 4831 /* 4832 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4833 */ 4834 @Override 4835 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4836 int targetUserId) { 4837 mContext.enforceCallingOrSelfPermission( 4838 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4839 List<CrossProfileIntentFilter> matches = 4840 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4841 if (matches != null) { 4842 int size = matches.size(); 4843 for (int i = 0; i < size; i++) { 4844 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4845 } 4846 } 4847 if (hasWebURI(intent)) { 4848 // cross-profile app linking works only towards the parent. 4849 final UserInfo parent = getProfileParent(sourceUserId); 4850 synchronized(mPackages) { 4851 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4852 intent, resolvedType, 0, sourceUserId, parent.id); 4853 return xpDomainInfo != null; 4854 } 4855 } 4856 return false; 4857 } 4858 4859 private UserInfo getProfileParent(int userId) { 4860 final long identity = Binder.clearCallingIdentity(); 4861 try { 4862 return sUserManager.getProfileParent(userId); 4863 } finally { 4864 Binder.restoreCallingIdentity(identity); 4865 } 4866 } 4867 4868 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4869 String resolvedType, int userId) { 4870 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4871 if (resolver != null) { 4872 return resolver.queryIntent(intent, resolvedType, false, userId); 4873 } 4874 return null; 4875 } 4876 4877 @Override 4878 public List<ResolveInfo> queryIntentActivities(Intent intent, 4879 String resolvedType, int flags, int userId) { 4880 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4881 flags = updateFlagsForResolve(flags, userId, intent); 4882 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4883 ComponentName comp = intent.getComponent(); 4884 if (comp == null) { 4885 if (intent.getSelector() != null) { 4886 intent = intent.getSelector(); 4887 comp = intent.getComponent(); 4888 } 4889 } 4890 4891 if (comp != null) { 4892 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4893 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4894 if (ai != null) { 4895 final ResolveInfo ri = new ResolveInfo(); 4896 ri.activityInfo = ai; 4897 list.add(ri); 4898 } 4899 return list; 4900 } 4901 4902 // reader 4903 synchronized (mPackages) { 4904 final String pkgName = intent.getPackage(); 4905 if (pkgName == null) { 4906 List<CrossProfileIntentFilter> matchingFilters = 4907 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4908 // Check for results that need to skip the current profile. 4909 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4910 resolvedType, flags, userId); 4911 if (xpResolveInfo != null) { 4912 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4913 result.add(xpResolveInfo); 4914 return filterIfNotSystemUser(result, userId); 4915 } 4916 4917 // Check for results in the current profile. 4918 List<ResolveInfo> result = mActivities.queryIntent( 4919 intent, resolvedType, flags, userId); 4920 result = filterIfNotSystemUser(result, userId); 4921 4922 // Check for cross profile results. 4923 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4924 xpResolveInfo = queryCrossProfileIntents( 4925 matchingFilters, intent, resolvedType, flags, userId, 4926 hasNonNegativePriorityResult); 4927 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4928 boolean isVisibleToUser = filterIfNotSystemUser( 4929 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4930 if (isVisibleToUser) { 4931 result.add(xpResolveInfo); 4932 Collections.sort(result, mResolvePrioritySorter); 4933 } 4934 } 4935 if (hasWebURI(intent)) { 4936 CrossProfileDomainInfo xpDomainInfo = null; 4937 final UserInfo parent = getProfileParent(userId); 4938 if (parent != null) { 4939 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4940 flags, userId, parent.id); 4941 } 4942 if (xpDomainInfo != null) { 4943 if (xpResolveInfo != null) { 4944 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4945 // in the result. 4946 result.remove(xpResolveInfo); 4947 } 4948 if (result.size() == 0) { 4949 result.add(xpDomainInfo.resolveInfo); 4950 return result; 4951 } 4952 } else if (result.size() <= 1) { 4953 return result; 4954 } 4955 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4956 xpDomainInfo, userId); 4957 Collections.sort(result, mResolvePrioritySorter); 4958 } 4959 return result; 4960 } 4961 final PackageParser.Package pkg = mPackages.get(pkgName); 4962 if (pkg != null) { 4963 return filterIfNotSystemUser( 4964 mActivities.queryIntentForPackage( 4965 intent, resolvedType, flags, pkg.activities, userId), 4966 userId); 4967 } 4968 return new ArrayList<ResolveInfo>(); 4969 } 4970 } 4971 4972 private static class CrossProfileDomainInfo { 4973 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4974 ResolveInfo resolveInfo; 4975 /* Best domain verification status of the activities found in the other profile */ 4976 int bestDomainVerificationStatus; 4977 } 4978 4979 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4980 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4981 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4982 sourceUserId)) { 4983 return null; 4984 } 4985 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4986 resolvedType, flags, parentUserId); 4987 4988 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4989 return null; 4990 } 4991 CrossProfileDomainInfo result = null; 4992 int size = resultTargetUser.size(); 4993 for (int i = 0; i < size; i++) { 4994 ResolveInfo riTargetUser = resultTargetUser.get(i); 4995 // Intent filter verification is only for filters that specify a host. So don't return 4996 // those that handle all web uris. 4997 if (riTargetUser.handleAllWebDataURI) { 4998 continue; 4999 } 5000 String packageName = riTargetUser.activityInfo.packageName; 5001 PackageSetting ps = mSettings.mPackages.get(packageName); 5002 if (ps == null) { 5003 continue; 5004 } 5005 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5006 int status = (int)(verificationState >> 32); 5007 if (result == null) { 5008 result = new CrossProfileDomainInfo(); 5009 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5010 sourceUserId, parentUserId); 5011 result.bestDomainVerificationStatus = status; 5012 } else { 5013 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5014 result.bestDomainVerificationStatus); 5015 } 5016 } 5017 // Don't consider matches with status NEVER across profiles. 5018 if (result != null && result.bestDomainVerificationStatus 5019 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5020 return null; 5021 } 5022 return result; 5023 } 5024 5025 /** 5026 * Verification statuses are ordered from the worse to the best, except for 5027 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5028 */ 5029 private int bestDomainVerificationStatus(int status1, int status2) { 5030 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5031 return status2; 5032 } 5033 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5034 return status1; 5035 } 5036 return (int) MathUtils.max(status1, status2); 5037 } 5038 5039 private boolean isUserEnabled(int userId) { 5040 long callingId = Binder.clearCallingIdentity(); 5041 try { 5042 UserInfo userInfo = sUserManager.getUserInfo(userId); 5043 return userInfo != null && userInfo.isEnabled(); 5044 } finally { 5045 Binder.restoreCallingIdentity(callingId); 5046 } 5047 } 5048 5049 /** 5050 * Filter out activities with systemUserOnly flag set, when current user is not System. 5051 * 5052 * @return filtered list 5053 */ 5054 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5055 if (userId == UserHandle.USER_SYSTEM) { 5056 return resolveInfos; 5057 } 5058 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5059 ResolveInfo info = resolveInfos.get(i); 5060 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5061 resolveInfos.remove(i); 5062 } 5063 } 5064 return resolveInfos; 5065 } 5066 5067 /** 5068 * @param resolveInfos list of resolve infos in descending priority order 5069 * @return if the list contains a resolve info with non-negative priority 5070 */ 5071 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5072 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5073 } 5074 5075 private static boolean hasWebURI(Intent intent) { 5076 if (intent.getData() == null) { 5077 return false; 5078 } 5079 final String scheme = intent.getScheme(); 5080 if (TextUtils.isEmpty(scheme)) { 5081 return false; 5082 } 5083 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5084 } 5085 5086 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5087 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5088 int userId) { 5089 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5090 5091 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5092 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5093 candidates.size()); 5094 } 5095 5096 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5097 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5098 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5099 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5100 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5101 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5102 5103 synchronized (mPackages) { 5104 final int count = candidates.size(); 5105 // First, try to use linked apps. Partition the candidates into four lists: 5106 // one for the final results, one for the "do not use ever", one for "undefined status" 5107 // and finally one for "browser app type". 5108 for (int n=0; n<count; n++) { 5109 ResolveInfo info = candidates.get(n); 5110 String packageName = info.activityInfo.packageName; 5111 PackageSetting ps = mSettings.mPackages.get(packageName); 5112 if (ps != null) { 5113 // Add to the special match all list (Browser use case) 5114 if (info.handleAllWebDataURI) { 5115 matchAllList.add(info); 5116 continue; 5117 } 5118 // Try to get the status from User settings first 5119 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5120 int status = (int)(packedStatus >> 32); 5121 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5122 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5123 if (DEBUG_DOMAIN_VERIFICATION) { 5124 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5125 + " : linkgen=" + linkGeneration); 5126 } 5127 // Use link-enabled generation as preferredOrder, i.e. 5128 // prefer newly-enabled over earlier-enabled. 5129 info.preferredOrder = linkGeneration; 5130 alwaysList.add(info); 5131 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5132 if (DEBUG_DOMAIN_VERIFICATION) { 5133 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5134 } 5135 neverList.add(info); 5136 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5137 if (DEBUG_DOMAIN_VERIFICATION) { 5138 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5139 } 5140 alwaysAskList.add(info); 5141 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5142 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5143 if (DEBUG_DOMAIN_VERIFICATION) { 5144 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5145 } 5146 undefinedList.add(info); 5147 } 5148 } 5149 } 5150 5151 // We'll want to include browser possibilities in a few cases 5152 boolean includeBrowser = false; 5153 5154 // First try to add the "always" resolution(s) for the current user, if any 5155 if (alwaysList.size() > 0) { 5156 result.addAll(alwaysList); 5157 } else { 5158 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5159 result.addAll(undefinedList); 5160 // Maybe add one for the other profile. 5161 if (xpDomainInfo != null && ( 5162 xpDomainInfo.bestDomainVerificationStatus 5163 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5164 result.add(xpDomainInfo.resolveInfo); 5165 } 5166 includeBrowser = true; 5167 } 5168 5169 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5170 // If there were 'always' entries their preferred order has been set, so we also 5171 // back that off to make the alternatives equivalent 5172 if (alwaysAskList.size() > 0) { 5173 for (ResolveInfo i : result) { 5174 i.preferredOrder = 0; 5175 } 5176 result.addAll(alwaysAskList); 5177 includeBrowser = true; 5178 } 5179 5180 if (includeBrowser) { 5181 // Also add browsers (all of them or only the default one) 5182 if (DEBUG_DOMAIN_VERIFICATION) { 5183 Slog.v(TAG, " ...including browsers in candidate set"); 5184 } 5185 if ((matchFlags & MATCH_ALL) != 0) { 5186 result.addAll(matchAllList); 5187 } else { 5188 // Browser/generic handling case. If there's a default browser, go straight 5189 // to that (but only if there is no other higher-priority match). 5190 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5191 int maxMatchPrio = 0; 5192 ResolveInfo defaultBrowserMatch = null; 5193 final int numCandidates = matchAllList.size(); 5194 for (int n = 0; n < numCandidates; n++) { 5195 ResolveInfo info = matchAllList.get(n); 5196 // track the highest overall match priority... 5197 if (info.priority > maxMatchPrio) { 5198 maxMatchPrio = info.priority; 5199 } 5200 // ...and the highest-priority default browser match 5201 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5202 if (defaultBrowserMatch == null 5203 || (defaultBrowserMatch.priority < info.priority)) { 5204 if (debug) { 5205 Slog.v(TAG, "Considering default browser match " + info); 5206 } 5207 defaultBrowserMatch = info; 5208 } 5209 } 5210 } 5211 if (defaultBrowserMatch != null 5212 && defaultBrowserMatch.priority >= maxMatchPrio 5213 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5214 { 5215 if (debug) { 5216 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5217 } 5218 result.add(defaultBrowserMatch); 5219 } else { 5220 result.addAll(matchAllList); 5221 } 5222 } 5223 5224 // If there is nothing selected, add all candidates and remove the ones that the user 5225 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5226 if (result.size() == 0) { 5227 result.addAll(candidates); 5228 result.removeAll(neverList); 5229 } 5230 } 5231 } 5232 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5233 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5234 result.size()); 5235 for (ResolveInfo info : result) { 5236 Slog.v(TAG, " + " + info.activityInfo); 5237 } 5238 } 5239 return result; 5240 } 5241 5242 // Returns a packed value as a long: 5243 // 5244 // high 'int'-sized word: link status: undefined/ask/never/always. 5245 // low 'int'-sized word: relative priority among 'always' results. 5246 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5247 long result = ps.getDomainVerificationStatusForUser(userId); 5248 // if none available, get the master status 5249 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5250 if (ps.getIntentFilterVerificationInfo() != null) { 5251 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5252 } 5253 } 5254 return result; 5255 } 5256 5257 private ResolveInfo querySkipCurrentProfileIntents( 5258 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5259 int flags, int sourceUserId) { 5260 if (matchingFilters != null) { 5261 int size = matchingFilters.size(); 5262 for (int i = 0; i < size; i ++) { 5263 CrossProfileIntentFilter filter = matchingFilters.get(i); 5264 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5265 // Checking if there are activities in the target user that can handle the 5266 // intent. 5267 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5268 resolvedType, flags, sourceUserId); 5269 if (resolveInfo != null) { 5270 return resolveInfo; 5271 } 5272 } 5273 } 5274 } 5275 return null; 5276 } 5277 5278 // Return matching ResolveInfo in target user if any. 5279 private ResolveInfo queryCrossProfileIntents( 5280 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5281 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5282 if (matchingFilters != null) { 5283 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5284 // match the same intent. For performance reasons, it is better not to 5285 // run queryIntent twice for the same userId 5286 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5287 int size = matchingFilters.size(); 5288 for (int i = 0; i < size; i++) { 5289 CrossProfileIntentFilter filter = matchingFilters.get(i); 5290 int targetUserId = filter.getTargetUserId(); 5291 boolean skipCurrentProfile = 5292 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5293 boolean skipCurrentProfileIfNoMatchFound = 5294 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5295 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5296 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5297 // Checking if there are activities in the target user that can handle the 5298 // intent. 5299 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5300 resolvedType, flags, sourceUserId); 5301 if (resolveInfo != null) return resolveInfo; 5302 alreadyTriedUserIds.put(targetUserId, true); 5303 } 5304 } 5305 } 5306 return null; 5307 } 5308 5309 /** 5310 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5311 * will forward the intent to the filter's target user. 5312 * Otherwise, returns null. 5313 */ 5314 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5315 String resolvedType, int flags, int sourceUserId) { 5316 int targetUserId = filter.getTargetUserId(); 5317 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5318 resolvedType, flags, targetUserId); 5319 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5320 && isUserEnabled(targetUserId)) { 5321 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5322 } 5323 return null; 5324 } 5325 5326 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5327 int sourceUserId, int targetUserId) { 5328 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5329 long ident = Binder.clearCallingIdentity(); 5330 boolean targetIsProfile; 5331 try { 5332 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5333 } finally { 5334 Binder.restoreCallingIdentity(ident); 5335 } 5336 String className; 5337 if (targetIsProfile) { 5338 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5339 } else { 5340 className = FORWARD_INTENT_TO_PARENT; 5341 } 5342 ComponentName forwardingActivityComponentName = new ComponentName( 5343 mAndroidApplication.packageName, className); 5344 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5345 sourceUserId); 5346 if (!targetIsProfile) { 5347 forwardingActivityInfo.showUserIcon = targetUserId; 5348 forwardingResolveInfo.noResourceId = true; 5349 } 5350 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5351 forwardingResolveInfo.priority = 0; 5352 forwardingResolveInfo.preferredOrder = 0; 5353 forwardingResolveInfo.match = 0; 5354 forwardingResolveInfo.isDefault = true; 5355 forwardingResolveInfo.filter = filter; 5356 forwardingResolveInfo.targetUserId = targetUserId; 5357 return forwardingResolveInfo; 5358 } 5359 5360 @Override 5361 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5362 Intent[] specifics, String[] specificTypes, Intent intent, 5363 String resolvedType, int flags, int userId) { 5364 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5365 flags = updateFlagsForResolve(flags, userId, intent); 5366 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5367 false, "query intent activity options"); 5368 final String resultsAction = intent.getAction(); 5369 5370 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5371 | PackageManager.GET_RESOLVED_FILTER, userId); 5372 5373 if (DEBUG_INTENT_MATCHING) { 5374 Log.v(TAG, "Query " + intent + ": " + results); 5375 } 5376 5377 int specificsPos = 0; 5378 int N; 5379 5380 // todo: note that the algorithm used here is O(N^2). This 5381 // isn't a problem in our current environment, but if we start running 5382 // into situations where we have more than 5 or 10 matches then this 5383 // should probably be changed to something smarter... 5384 5385 // First we go through and resolve each of the specific items 5386 // that were supplied, taking care of removing any corresponding 5387 // duplicate items in the generic resolve list. 5388 if (specifics != null) { 5389 for (int i=0; i<specifics.length; i++) { 5390 final Intent sintent = specifics[i]; 5391 if (sintent == null) { 5392 continue; 5393 } 5394 5395 if (DEBUG_INTENT_MATCHING) { 5396 Log.v(TAG, "Specific #" + i + ": " + sintent); 5397 } 5398 5399 String action = sintent.getAction(); 5400 if (resultsAction != null && resultsAction.equals(action)) { 5401 // If this action was explicitly requested, then don't 5402 // remove things that have it. 5403 action = null; 5404 } 5405 5406 ResolveInfo ri = null; 5407 ActivityInfo ai = null; 5408 5409 ComponentName comp = sintent.getComponent(); 5410 if (comp == null) { 5411 ri = resolveIntent( 5412 sintent, 5413 specificTypes != null ? specificTypes[i] : null, 5414 flags, userId); 5415 if (ri == null) { 5416 continue; 5417 } 5418 if (ri == mResolveInfo) { 5419 // ACK! Must do something better with this. 5420 } 5421 ai = ri.activityInfo; 5422 comp = new ComponentName(ai.applicationInfo.packageName, 5423 ai.name); 5424 } else { 5425 ai = getActivityInfo(comp, flags, userId); 5426 if (ai == null) { 5427 continue; 5428 } 5429 } 5430 5431 // Look for any generic query activities that are duplicates 5432 // of this specific one, and remove them from the results. 5433 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5434 N = results.size(); 5435 int j; 5436 for (j=specificsPos; j<N; j++) { 5437 ResolveInfo sri = results.get(j); 5438 if ((sri.activityInfo.name.equals(comp.getClassName()) 5439 && sri.activityInfo.applicationInfo.packageName.equals( 5440 comp.getPackageName())) 5441 || (action != null && sri.filter.matchAction(action))) { 5442 results.remove(j); 5443 if (DEBUG_INTENT_MATCHING) Log.v( 5444 TAG, "Removing duplicate item from " + j 5445 + " due to specific " + specificsPos); 5446 if (ri == null) { 5447 ri = sri; 5448 } 5449 j--; 5450 N--; 5451 } 5452 } 5453 5454 // Add this specific item to its proper place. 5455 if (ri == null) { 5456 ri = new ResolveInfo(); 5457 ri.activityInfo = ai; 5458 } 5459 results.add(specificsPos, ri); 5460 ri.specificIndex = i; 5461 specificsPos++; 5462 } 5463 } 5464 5465 // Now we go through the remaining generic results and remove any 5466 // duplicate actions that are found here. 5467 N = results.size(); 5468 for (int i=specificsPos; i<N-1; i++) { 5469 final ResolveInfo rii = results.get(i); 5470 if (rii.filter == null) { 5471 continue; 5472 } 5473 5474 // Iterate over all of the actions of this result's intent 5475 // filter... typically this should be just one. 5476 final Iterator<String> it = rii.filter.actionsIterator(); 5477 if (it == null) { 5478 continue; 5479 } 5480 while (it.hasNext()) { 5481 final String action = it.next(); 5482 if (resultsAction != null && resultsAction.equals(action)) { 5483 // If this action was explicitly requested, then don't 5484 // remove things that have it. 5485 continue; 5486 } 5487 for (int j=i+1; j<N; j++) { 5488 final ResolveInfo rij = results.get(j); 5489 if (rij.filter != null && rij.filter.hasAction(action)) { 5490 results.remove(j); 5491 if (DEBUG_INTENT_MATCHING) Log.v( 5492 TAG, "Removing duplicate item from " + j 5493 + " due to action " + action + " at " + i); 5494 j--; 5495 N--; 5496 } 5497 } 5498 } 5499 5500 // If the caller didn't request filter information, drop it now 5501 // so we don't have to marshall/unmarshall it. 5502 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5503 rii.filter = null; 5504 } 5505 } 5506 5507 // Filter out the caller activity if so requested. 5508 if (caller != null) { 5509 N = results.size(); 5510 for (int i=0; i<N; i++) { 5511 ActivityInfo ainfo = results.get(i).activityInfo; 5512 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5513 && caller.getClassName().equals(ainfo.name)) { 5514 results.remove(i); 5515 break; 5516 } 5517 } 5518 } 5519 5520 // If the caller didn't request filter information, 5521 // drop them now so we don't have to 5522 // marshall/unmarshall it. 5523 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5524 N = results.size(); 5525 for (int i=0; i<N; i++) { 5526 results.get(i).filter = null; 5527 } 5528 } 5529 5530 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5531 return results; 5532 } 5533 5534 @Override 5535 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5536 int userId) { 5537 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5538 flags = updateFlagsForResolve(flags, userId, intent); 5539 ComponentName comp = intent.getComponent(); 5540 if (comp == null) { 5541 if (intent.getSelector() != null) { 5542 intent = intent.getSelector(); 5543 comp = intent.getComponent(); 5544 } 5545 } 5546 if (comp != null) { 5547 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5548 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5549 if (ai != null) { 5550 ResolveInfo ri = new ResolveInfo(); 5551 ri.activityInfo = ai; 5552 list.add(ri); 5553 } 5554 return list; 5555 } 5556 5557 // reader 5558 synchronized (mPackages) { 5559 String pkgName = intent.getPackage(); 5560 if (pkgName == null) { 5561 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5562 } 5563 final PackageParser.Package pkg = mPackages.get(pkgName); 5564 if (pkg != null) { 5565 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5566 userId); 5567 } 5568 return null; 5569 } 5570 } 5571 5572 @Override 5573 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5574 if (!sUserManager.exists(userId)) return null; 5575 flags = updateFlagsForResolve(flags, userId, intent); 5576 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5577 if (query != null) { 5578 if (query.size() >= 1) { 5579 // If there is more than one service with the same priority, 5580 // just arbitrarily pick the first one. 5581 return query.get(0); 5582 } 5583 } 5584 return null; 5585 } 5586 5587 @Override 5588 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5589 int userId) { 5590 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5591 flags = updateFlagsForResolve(flags, userId, intent); 5592 ComponentName comp = intent.getComponent(); 5593 if (comp == null) { 5594 if (intent.getSelector() != null) { 5595 intent = intent.getSelector(); 5596 comp = intent.getComponent(); 5597 } 5598 } 5599 if (comp != null) { 5600 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5601 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5602 if (si != null) { 5603 final ResolveInfo ri = new ResolveInfo(); 5604 ri.serviceInfo = si; 5605 list.add(ri); 5606 } 5607 return list; 5608 } 5609 5610 // reader 5611 synchronized (mPackages) { 5612 String pkgName = intent.getPackage(); 5613 if (pkgName == null) { 5614 return mServices.queryIntent(intent, resolvedType, flags, userId); 5615 } 5616 final PackageParser.Package pkg = mPackages.get(pkgName); 5617 if (pkg != null) { 5618 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5619 userId); 5620 } 5621 return null; 5622 } 5623 } 5624 5625 @Override 5626 public List<ResolveInfo> queryIntentContentProviders( 5627 Intent intent, String resolvedType, int flags, int userId) { 5628 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5629 flags = updateFlagsForResolve(flags, userId, intent); 5630 ComponentName comp = intent.getComponent(); 5631 if (comp == null) { 5632 if (intent.getSelector() != null) { 5633 intent = intent.getSelector(); 5634 comp = intent.getComponent(); 5635 } 5636 } 5637 if (comp != null) { 5638 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5639 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5640 if (pi != null) { 5641 final ResolveInfo ri = new ResolveInfo(); 5642 ri.providerInfo = pi; 5643 list.add(ri); 5644 } 5645 return list; 5646 } 5647 5648 // reader 5649 synchronized (mPackages) { 5650 String pkgName = intent.getPackage(); 5651 if (pkgName == null) { 5652 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5653 } 5654 final PackageParser.Package pkg = mPackages.get(pkgName); 5655 if (pkg != null) { 5656 return mProviders.queryIntentForPackage( 5657 intent, resolvedType, flags, pkg.providers, userId); 5658 } 5659 return null; 5660 } 5661 } 5662 5663 @Override 5664 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5665 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5666 flags = updateFlagsForPackage(flags, userId, null); 5667 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5668 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5669 5670 // writer 5671 synchronized (mPackages) { 5672 ArrayList<PackageInfo> list; 5673 if (listUninstalled) { 5674 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5675 for (PackageSetting ps : mSettings.mPackages.values()) { 5676 PackageInfo pi; 5677 if (ps.pkg != null) { 5678 pi = generatePackageInfo(ps.pkg, flags, userId); 5679 } else { 5680 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5681 } 5682 if (pi != null) { 5683 list.add(pi); 5684 } 5685 } 5686 } else { 5687 list = new ArrayList<PackageInfo>(mPackages.size()); 5688 for (PackageParser.Package p : mPackages.values()) { 5689 PackageInfo pi = generatePackageInfo(p, flags, userId); 5690 if (pi != null) { 5691 list.add(pi); 5692 } 5693 } 5694 } 5695 5696 return new ParceledListSlice<PackageInfo>(list); 5697 } 5698 } 5699 5700 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5701 String[] permissions, boolean[] tmp, int flags, int userId) { 5702 int numMatch = 0; 5703 final PermissionsState permissionsState = ps.getPermissionsState(); 5704 for (int i=0; i<permissions.length; i++) { 5705 final String permission = permissions[i]; 5706 if (permissionsState.hasPermission(permission, userId)) { 5707 tmp[i] = true; 5708 numMatch++; 5709 } else { 5710 tmp[i] = false; 5711 } 5712 } 5713 if (numMatch == 0) { 5714 return; 5715 } 5716 PackageInfo pi; 5717 if (ps.pkg != null) { 5718 pi = generatePackageInfo(ps.pkg, flags, userId); 5719 } else { 5720 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5721 } 5722 // The above might return null in cases of uninstalled apps or install-state 5723 // skew across users/profiles. 5724 if (pi != null) { 5725 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5726 if (numMatch == permissions.length) { 5727 pi.requestedPermissions = permissions; 5728 } else { 5729 pi.requestedPermissions = new String[numMatch]; 5730 numMatch = 0; 5731 for (int i=0; i<permissions.length; i++) { 5732 if (tmp[i]) { 5733 pi.requestedPermissions[numMatch] = permissions[i]; 5734 numMatch++; 5735 } 5736 } 5737 } 5738 } 5739 list.add(pi); 5740 } 5741 } 5742 5743 @Override 5744 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5745 String[] permissions, int flags, int userId) { 5746 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5747 flags = updateFlagsForPackage(flags, userId, permissions); 5748 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5749 5750 // writer 5751 synchronized (mPackages) { 5752 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5753 boolean[] tmpBools = new boolean[permissions.length]; 5754 if (listUninstalled) { 5755 for (PackageSetting ps : mSettings.mPackages.values()) { 5756 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5757 } 5758 } else { 5759 for (PackageParser.Package pkg : mPackages.values()) { 5760 PackageSetting ps = (PackageSetting)pkg.mExtras; 5761 if (ps != null) { 5762 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5763 userId); 5764 } 5765 } 5766 } 5767 5768 return new ParceledListSlice<PackageInfo>(list); 5769 } 5770 } 5771 5772 @Override 5773 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5774 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5775 flags = updateFlagsForApplication(flags, userId, null); 5776 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5777 5778 // writer 5779 synchronized (mPackages) { 5780 ArrayList<ApplicationInfo> list; 5781 if (listUninstalled) { 5782 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5783 for (PackageSetting ps : mSettings.mPackages.values()) { 5784 ApplicationInfo ai; 5785 if (ps.pkg != null) { 5786 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5787 ps.readUserState(userId), userId); 5788 } else { 5789 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5790 } 5791 if (ai != null) { 5792 list.add(ai); 5793 } 5794 } 5795 } else { 5796 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5797 for (PackageParser.Package p : mPackages.values()) { 5798 if (p.mExtras != null) { 5799 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5800 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5801 if (ai != null) { 5802 list.add(ai); 5803 } 5804 } 5805 } 5806 } 5807 5808 return new ParceledListSlice<ApplicationInfo>(list); 5809 } 5810 } 5811 5812 @Override 5813 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5814 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5815 "getEphemeralApplications"); 5816 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5817 "getEphemeralApplications"); 5818 synchronized (mPackages) { 5819 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5820 .getEphemeralApplicationsLPw(userId); 5821 if (ephemeralApps != null) { 5822 return new ParceledListSlice<>(ephemeralApps); 5823 } 5824 } 5825 return null; 5826 } 5827 5828 @Override 5829 public boolean isEphemeralApplication(String packageName, int userId) { 5830 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5831 "isEphemeral"); 5832 if (!isCallerSameApp(packageName)) { 5833 return false; 5834 } 5835 synchronized (mPackages) { 5836 PackageParser.Package pkg = mPackages.get(packageName); 5837 if (pkg != null) { 5838 return pkg.applicationInfo.isEphemeralApp(); 5839 } 5840 } 5841 return false; 5842 } 5843 5844 @Override 5845 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5846 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5847 "getCookie"); 5848 if (!isCallerSameApp(packageName)) { 5849 return null; 5850 } 5851 synchronized (mPackages) { 5852 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5853 packageName, userId); 5854 } 5855 } 5856 5857 @Override 5858 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5859 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5860 "setCookie"); 5861 if (!isCallerSameApp(packageName)) { 5862 return false; 5863 } 5864 synchronized (mPackages) { 5865 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5866 packageName, cookie, userId); 5867 } 5868 } 5869 5870 @Override 5871 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5872 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5873 "getEphemeralApplicationIcon"); 5874 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5875 "getEphemeralApplicationIcon"); 5876 synchronized (mPackages) { 5877 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5878 packageName, userId); 5879 } 5880 } 5881 5882 private boolean isCallerSameApp(String packageName) { 5883 PackageParser.Package pkg = mPackages.get(packageName); 5884 return pkg != null 5885 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5886 } 5887 5888 public List<ApplicationInfo> getPersistentApplications(int flags) { 5889 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5890 5891 // reader 5892 synchronized (mPackages) { 5893 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5894 final int userId = UserHandle.getCallingUserId(); 5895 while (i.hasNext()) { 5896 final PackageParser.Package p = i.next(); 5897 if (p.applicationInfo != null 5898 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5899 && (!mSafeMode || isSystemApp(p))) { 5900 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5901 if (ps != null) { 5902 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5903 ps.readUserState(userId), userId); 5904 if (ai != null) { 5905 finalList.add(ai); 5906 } 5907 } 5908 } 5909 } 5910 } 5911 5912 return finalList; 5913 } 5914 5915 @Override 5916 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5917 if (!sUserManager.exists(userId)) return null; 5918 flags = updateFlagsForComponent(flags, userId, name); 5919 // reader 5920 synchronized (mPackages) { 5921 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5922 PackageSetting ps = provider != null 5923 ? mSettings.mPackages.get(provider.owner.packageName) 5924 : null; 5925 return ps != null 5926 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 5927 && (!mSafeMode || (provider.info.applicationInfo.flags 5928 &ApplicationInfo.FLAG_SYSTEM) != 0) 5929 ? PackageParser.generateProviderInfo(provider, flags, 5930 ps.readUserState(userId), userId) 5931 : null; 5932 } 5933 } 5934 5935 /** 5936 * @deprecated 5937 */ 5938 @Deprecated 5939 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5940 // reader 5941 synchronized (mPackages) { 5942 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5943 .entrySet().iterator(); 5944 final int userId = UserHandle.getCallingUserId(); 5945 while (i.hasNext()) { 5946 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5947 PackageParser.Provider p = entry.getValue(); 5948 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5949 5950 if (ps != null && p.syncable 5951 && (!mSafeMode || (p.info.applicationInfo.flags 5952 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5953 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5954 ps.readUserState(userId), userId); 5955 if (info != null) { 5956 outNames.add(entry.getKey()); 5957 outInfo.add(info); 5958 } 5959 } 5960 } 5961 } 5962 } 5963 5964 @Override 5965 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5966 int uid, int flags) { 5967 final int userId = processName != null ? UserHandle.getUserId(uid) 5968 : UserHandle.getCallingUserId(); 5969 if (!sUserManager.exists(userId)) return null; 5970 flags = updateFlagsForComponent(flags, userId, processName); 5971 5972 ArrayList<ProviderInfo> finalList = null; 5973 // reader 5974 synchronized (mPackages) { 5975 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5976 while (i.hasNext()) { 5977 final PackageParser.Provider p = i.next(); 5978 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5979 if (ps != null && p.info.authority != null 5980 && (processName == null 5981 || (p.info.processName.equals(processName) 5982 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5983 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId) 5984 && (!mSafeMode 5985 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5986 if (finalList == null) { 5987 finalList = new ArrayList<ProviderInfo>(3); 5988 } 5989 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5990 ps.readUserState(userId), userId); 5991 if (info != null) { 5992 finalList.add(info); 5993 } 5994 } 5995 } 5996 } 5997 5998 if (finalList != null) { 5999 Collections.sort(finalList, mProviderInitOrderSorter); 6000 return new ParceledListSlice<ProviderInfo>(finalList); 6001 } 6002 6003 return null; 6004 } 6005 6006 @Override 6007 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6008 // reader 6009 synchronized (mPackages) { 6010 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6011 return PackageParser.generateInstrumentationInfo(i, flags); 6012 } 6013 } 6014 6015 @Override 6016 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6017 int flags) { 6018 ArrayList<InstrumentationInfo> finalList = 6019 new ArrayList<InstrumentationInfo>(); 6020 6021 // reader 6022 synchronized (mPackages) { 6023 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6024 while (i.hasNext()) { 6025 final PackageParser.Instrumentation p = i.next(); 6026 if (targetPackage == null 6027 || targetPackage.equals(p.info.targetPackage)) { 6028 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6029 flags); 6030 if (ii != null) { 6031 finalList.add(ii); 6032 } 6033 } 6034 } 6035 } 6036 6037 return finalList; 6038 } 6039 6040 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6041 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6042 if (overlays == null) { 6043 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6044 return; 6045 } 6046 for (PackageParser.Package opkg : overlays.values()) { 6047 // Not much to do if idmap fails: we already logged the error 6048 // and we certainly don't want to abort installation of pkg simply 6049 // because an overlay didn't fit properly. For these reasons, 6050 // ignore the return value of createIdmapForPackagePairLI. 6051 createIdmapForPackagePairLI(pkg, opkg); 6052 } 6053 } 6054 6055 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6056 PackageParser.Package opkg) { 6057 if (!opkg.mTrustedOverlay) { 6058 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6059 opkg.baseCodePath + ": overlay not trusted"); 6060 return false; 6061 } 6062 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6063 if (overlaySet == null) { 6064 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6065 opkg.baseCodePath + " but target package has no known overlays"); 6066 return false; 6067 } 6068 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6069 // TODO: generate idmap for split APKs 6070 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6071 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6072 + opkg.baseCodePath); 6073 return false; 6074 } 6075 PackageParser.Package[] overlayArray = 6076 overlaySet.values().toArray(new PackageParser.Package[0]); 6077 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6078 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6079 return p1.mOverlayPriority - p2.mOverlayPriority; 6080 } 6081 }; 6082 Arrays.sort(overlayArray, cmp); 6083 6084 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6085 int i = 0; 6086 for (PackageParser.Package p : overlayArray) { 6087 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6088 } 6089 return true; 6090 } 6091 6092 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6093 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6094 try { 6095 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6096 } finally { 6097 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6098 } 6099 } 6100 6101 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6102 final File[] files = dir.listFiles(); 6103 if (ArrayUtils.isEmpty(files)) { 6104 Log.d(TAG, "No files in app dir " + dir); 6105 return; 6106 } 6107 6108 if (DEBUG_PACKAGE_SCANNING) { 6109 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6110 + " flags=0x" + Integer.toHexString(parseFlags)); 6111 } 6112 6113 for (File file : files) { 6114 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6115 && !PackageInstallerService.isStageName(file.getName()); 6116 if (!isPackage) { 6117 // Ignore entries which are not packages 6118 continue; 6119 } 6120 try { 6121 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6122 scanFlags, currentTime, null); 6123 } catch (PackageManagerException e) { 6124 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6125 6126 // Delete invalid userdata apps 6127 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6128 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6129 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6130 if (file.isDirectory()) { 6131 mInstaller.rmPackageDir(file.getAbsolutePath()); 6132 } else { 6133 file.delete(); 6134 } 6135 } 6136 } 6137 } 6138 } 6139 6140 private static File getSettingsProblemFile() { 6141 File dataDir = Environment.getDataDirectory(); 6142 File systemDir = new File(dataDir, "system"); 6143 File fname = new File(systemDir, "uiderrors.txt"); 6144 return fname; 6145 } 6146 6147 static void reportSettingsProblem(int priority, String msg) { 6148 logCriticalInfo(priority, msg); 6149 } 6150 6151 static void logCriticalInfo(int priority, String msg) { 6152 Slog.println(priority, TAG, msg); 6153 EventLogTags.writePmCriticalInfo(msg); 6154 try { 6155 File fname = getSettingsProblemFile(); 6156 FileOutputStream out = new FileOutputStream(fname, true); 6157 PrintWriter pw = new FastPrintWriter(out); 6158 SimpleDateFormat formatter = new SimpleDateFormat(); 6159 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6160 pw.println(dateString + ": " + msg); 6161 pw.close(); 6162 FileUtils.setPermissions( 6163 fname.toString(), 6164 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6165 -1, -1); 6166 } catch (java.io.IOException e) { 6167 } 6168 } 6169 6170 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6171 PackageParser.Package pkg, File srcFile, int parseFlags) 6172 throws PackageManagerException { 6173 if (ps != null 6174 && ps.codePath.equals(srcFile) 6175 && ps.timeStamp == srcFile.lastModified() 6176 && !isCompatSignatureUpdateNeeded(pkg) 6177 && !isRecoverSignatureUpdateNeeded(pkg)) { 6178 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6180 ArraySet<PublicKey> signingKs; 6181 synchronized (mPackages) { 6182 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6183 } 6184 if (ps.signatures.mSignatures != null 6185 && ps.signatures.mSignatures.length != 0 6186 && signingKs != null) { 6187 // Optimization: reuse the existing cached certificates 6188 // if the package appears to be unchanged. 6189 pkg.mSignatures = ps.signatures.mSignatures; 6190 pkg.mSigningKeys = signingKs; 6191 return; 6192 } 6193 6194 Slog.w(TAG, "PackageSetting for " + ps.name 6195 + " is missing signatures. Collecting certs again to recover them."); 6196 } else { 6197 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6198 } 6199 6200 try { 6201 pp.collectCertificates(pkg, parseFlags); 6202 } catch (PackageParserException e) { 6203 throw PackageManagerException.from(e); 6204 } 6205 } 6206 6207 /** 6208 * Traces a package scan. 6209 * @see #scanPackageLI(File, int, int, long, UserHandle) 6210 */ 6211 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6212 long currentTime, UserHandle user) throws PackageManagerException { 6213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6214 try { 6215 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6216 } finally { 6217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6218 } 6219 } 6220 6221 /** 6222 * Scans a package and returns the newly parsed package. 6223 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6224 */ 6225 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6226 long currentTime, UserHandle user) throws PackageManagerException { 6227 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6228 parseFlags |= mDefParseFlags; 6229 PackageParser pp = new PackageParser(); 6230 pp.setSeparateProcesses(mSeparateProcesses); 6231 pp.setOnlyCoreApps(mOnlyCore); 6232 pp.setDisplayMetrics(mMetrics); 6233 6234 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6235 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6236 } 6237 6238 final PackageParser.Package pkg; 6239 try { 6240 pkg = pp.parsePackage(scanFile, parseFlags); 6241 } catch (PackageParserException e) { 6242 throw PackageManagerException.from(e); 6243 } 6244 6245 PackageSetting ps = null; 6246 PackageSetting updatedPkg; 6247 // reader 6248 synchronized (mPackages) { 6249 // Look to see if we already know about this package. 6250 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6251 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6252 // This package has been renamed to its original name. Let's 6253 // use that. 6254 ps = mSettings.peekPackageLPr(oldName); 6255 } 6256 // If there was no original package, see one for the real package name. 6257 if (ps == null) { 6258 ps = mSettings.peekPackageLPr(pkg.packageName); 6259 } 6260 // Check to see if this package could be hiding/updating a system 6261 // package. Must look for it either under the original or real 6262 // package name depending on our state. 6263 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6264 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6265 } 6266 boolean updatedPkgBetter = false; 6267 // First check if this is a system package that may involve an update 6268 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6269 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6270 // it needs to drop FLAG_PRIVILEGED. 6271 if (locationIsPrivileged(scanFile)) { 6272 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6273 } else { 6274 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6275 } 6276 6277 if (ps != null && !ps.codePath.equals(scanFile)) { 6278 // The path has changed from what was last scanned... check the 6279 // version of the new path against what we have stored to determine 6280 // what to do. 6281 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6282 if (pkg.mVersionCode <= ps.versionCode) { 6283 // The system package has been updated and the code path does not match 6284 // Ignore entry. Skip it. 6285 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6286 + " ignored: updated version " + ps.versionCode 6287 + " better than this " + pkg.mVersionCode); 6288 if (!updatedPkg.codePath.equals(scanFile)) { 6289 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6290 + ps.name + " changing from " + updatedPkg.codePathString 6291 + " to " + scanFile); 6292 updatedPkg.codePath = scanFile; 6293 updatedPkg.codePathString = scanFile.toString(); 6294 updatedPkg.resourcePath = scanFile; 6295 updatedPkg.resourcePathString = scanFile.toString(); 6296 } 6297 updatedPkg.pkg = pkg; 6298 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6299 "Package " + ps.name + " at " + scanFile 6300 + " ignored: updated version " + ps.versionCode 6301 + " better than this " + pkg.mVersionCode); 6302 } else { 6303 // The current app on the system partition is better than 6304 // what we have updated to on the data partition; switch 6305 // back to the system partition version. 6306 // At this point, its safely assumed that package installation for 6307 // apps in system partition will go through. If not there won't be a working 6308 // version of the app 6309 // writer 6310 synchronized (mPackages) { 6311 // Just remove the loaded entries from package lists. 6312 mPackages.remove(ps.name); 6313 } 6314 6315 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6316 + " reverting from " + ps.codePathString 6317 + ": new version " + pkg.mVersionCode 6318 + " better than installed " + ps.versionCode); 6319 6320 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6321 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6322 synchronized (mInstallLock) { 6323 args.cleanUpResourcesLI(); 6324 } 6325 synchronized (mPackages) { 6326 mSettings.enableSystemPackageLPw(ps.name); 6327 } 6328 updatedPkgBetter = true; 6329 } 6330 } 6331 } 6332 6333 if (updatedPkg != null) { 6334 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6335 // initially 6336 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6337 6338 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6339 // flag set initially 6340 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6341 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6342 } 6343 } 6344 6345 // Verify certificates against what was last scanned 6346 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6347 6348 /* 6349 * A new system app appeared, but we already had a non-system one of the 6350 * same name installed earlier. 6351 */ 6352 boolean shouldHideSystemApp = false; 6353 if (updatedPkg == null && ps != null 6354 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6355 /* 6356 * Check to make sure the signatures match first. If they don't, 6357 * wipe the installed application and its data. 6358 */ 6359 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6360 != PackageManager.SIGNATURE_MATCH) { 6361 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6362 + " signatures don't match existing userdata copy; removing"); 6363 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6364 ps = null; 6365 } else { 6366 /* 6367 * If the newly-added system app is an older version than the 6368 * already installed version, hide it. It will be scanned later 6369 * and re-added like an update. 6370 */ 6371 if (pkg.mVersionCode <= ps.versionCode) { 6372 shouldHideSystemApp = true; 6373 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6374 + " but new version " + pkg.mVersionCode + " better than installed " 6375 + ps.versionCode + "; hiding system"); 6376 } else { 6377 /* 6378 * The newly found system app is a newer version that the 6379 * one previously installed. Simply remove the 6380 * already-installed application and replace it with our own 6381 * while keeping the application data. 6382 */ 6383 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6384 + " reverting from " + ps.codePathString + ": new version " 6385 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6386 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6387 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6388 synchronized (mInstallLock) { 6389 args.cleanUpResourcesLI(); 6390 } 6391 } 6392 } 6393 } 6394 6395 // The apk is forward locked (not public) if its code and resources 6396 // are kept in different files. (except for app in either system or 6397 // vendor path). 6398 // TODO grab this value from PackageSettings 6399 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6400 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6401 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6402 } 6403 } 6404 6405 // TODO: extend to support forward-locked splits 6406 String resourcePath = null; 6407 String baseResourcePath = null; 6408 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6409 if (ps != null && ps.resourcePathString != null) { 6410 resourcePath = ps.resourcePathString; 6411 baseResourcePath = ps.resourcePathString; 6412 } else { 6413 // Should not happen at all. Just log an error. 6414 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6415 } 6416 } else { 6417 resourcePath = pkg.codePath; 6418 baseResourcePath = pkg.baseCodePath; 6419 } 6420 6421 // Set application objects path explicitly. 6422 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6423 pkg.applicationInfo.setCodePath(pkg.codePath); 6424 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6425 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6426 pkg.applicationInfo.setResourcePath(resourcePath); 6427 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6428 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6429 6430 // Note that we invoke the following method only if we are about to unpack an application 6431 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6432 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6433 6434 /* 6435 * If the system app should be overridden by a previously installed 6436 * data, hide the system app now and let the /data/app scan pick it up 6437 * again. 6438 */ 6439 if (shouldHideSystemApp) { 6440 synchronized (mPackages) { 6441 mSettings.disableSystemPackageLPw(pkg.packageName); 6442 } 6443 } 6444 6445 return scannedPkg; 6446 } 6447 6448 private static String fixProcessName(String defProcessName, 6449 String processName, int uid) { 6450 if (processName == null) { 6451 return defProcessName; 6452 } 6453 return processName; 6454 } 6455 6456 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6457 throws PackageManagerException { 6458 if (pkgSetting.signatures.mSignatures != null) { 6459 // Already existing package. Make sure signatures match 6460 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6461 == PackageManager.SIGNATURE_MATCH; 6462 if (!match) { 6463 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6464 == PackageManager.SIGNATURE_MATCH; 6465 } 6466 if (!match) { 6467 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6468 == PackageManager.SIGNATURE_MATCH; 6469 } 6470 if (!match) { 6471 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6472 + pkg.packageName + " signatures do not match the " 6473 + "previously installed version; ignoring!"); 6474 } 6475 } 6476 6477 // Check for shared user signatures 6478 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6479 // Already existing package. Make sure signatures match 6480 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6481 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6482 if (!match) { 6483 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6484 == PackageManager.SIGNATURE_MATCH; 6485 } 6486 if (!match) { 6487 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6488 == PackageManager.SIGNATURE_MATCH; 6489 } 6490 if (!match) { 6491 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6492 "Package " + pkg.packageName 6493 + " has no signatures that match those in shared user " 6494 + pkgSetting.sharedUser.name + "; ignoring!"); 6495 } 6496 } 6497 } 6498 6499 /** 6500 * Enforces that only the system UID or root's UID can call a method exposed 6501 * via Binder. 6502 * 6503 * @param message used as message if SecurityException is thrown 6504 * @throws SecurityException if the caller is not system or root 6505 */ 6506 private static final void enforceSystemOrRoot(String message) { 6507 final int uid = Binder.getCallingUid(); 6508 if (uid != Process.SYSTEM_UID && uid != 0) { 6509 throw new SecurityException(message); 6510 } 6511 } 6512 6513 @Override 6514 public void performFstrimIfNeeded() { 6515 enforceSystemOrRoot("Only the system can request fstrim"); 6516 6517 // Before everything else, see whether we need to fstrim. 6518 try { 6519 IMountService ms = PackageHelper.getMountService(); 6520 if (ms != null) { 6521 final boolean isUpgrade = isUpgrade(); 6522 boolean doTrim = isUpgrade; 6523 if (doTrim) { 6524 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6525 } else { 6526 final long interval = android.provider.Settings.Global.getLong( 6527 mContext.getContentResolver(), 6528 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6529 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6530 if (interval > 0) { 6531 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6532 if (timeSinceLast > interval) { 6533 doTrim = true; 6534 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6535 + "; running immediately"); 6536 } 6537 } 6538 } 6539 if (doTrim) { 6540 if (!isFirstBoot()) { 6541 try { 6542 ActivityManagerNative.getDefault().showBootMessage( 6543 mContext.getResources().getString( 6544 R.string.android_upgrading_fstrim), true); 6545 } catch (RemoteException e) { 6546 } 6547 } 6548 ms.runMaintenance(); 6549 } 6550 } else { 6551 Slog.e(TAG, "Mount service unavailable!"); 6552 } 6553 } catch (RemoteException e) { 6554 // Can't happen; MountService is local 6555 } 6556 } 6557 6558 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6559 List<ResolveInfo> ris = null; 6560 try { 6561 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6562 intent, null, 0, userId); 6563 } catch (RemoteException e) { 6564 } 6565 ArraySet<String> pkgNames = new ArraySet<String>(); 6566 if (ris != null) { 6567 for (ResolveInfo ri : ris) { 6568 pkgNames.add(ri.activityInfo.packageName); 6569 } 6570 } 6571 return pkgNames; 6572 } 6573 6574 @Override 6575 public void notifyPackageUse(String packageName) { 6576 synchronized (mPackages) { 6577 PackageParser.Package p = mPackages.get(packageName); 6578 if (p == null) { 6579 return; 6580 } 6581 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6582 } 6583 } 6584 6585 @Override 6586 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6587 return performDexOptTraced(packageName, instructionSet); 6588 } 6589 6590 public boolean performDexOpt(String packageName, String instructionSet) { 6591 return performDexOptTraced(packageName, instructionSet); 6592 } 6593 6594 private boolean performDexOptTraced(String packageName, String instructionSet) { 6595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6596 try { 6597 return performDexOptInternal(packageName, instructionSet); 6598 } finally { 6599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6600 } 6601 } 6602 6603 private boolean performDexOptInternal(String packageName, String instructionSet) { 6604 PackageParser.Package p; 6605 final String targetInstructionSet; 6606 synchronized (mPackages) { 6607 p = mPackages.get(packageName); 6608 if (p == null) { 6609 return false; 6610 } 6611 mPackageUsage.write(false); 6612 6613 targetInstructionSet = instructionSet != null ? instructionSet : 6614 getPrimaryInstructionSet(p.applicationInfo); 6615 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6616 return false; 6617 } 6618 } 6619 long callingId = Binder.clearCallingIdentity(); 6620 try { 6621 synchronized (mInstallLock) { 6622 final String[] instructionSets = new String[] { targetInstructionSet }; 6623 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6624 true /* inclDependencies */); 6625 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6626 } 6627 } finally { 6628 Binder.restoreCallingIdentity(callingId); 6629 } 6630 } 6631 6632 public ArraySet<String> getPackagesThatNeedDexOpt() { 6633 ArraySet<String> pkgs = null; 6634 synchronized (mPackages) { 6635 for (PackageParser.Package p : mPackages.values()) { 6636 if (DEBUG_DEXOPT) { 6637 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6638 } 6639 if (!p.mDexOptPerformed.isEmpty()) { 6640 continue; 6641 } 6642 if (pkgs == null) { 6643 pkgs = new ArraySet<String>(); 6644 } 6645 pkgs.add(p.packageName); 6646 } 6647 } 6648 return pkgs; 6649 } 6650 6651 public void shutdown() { 6652 mPackageUsage.write(true); 6653 } 6654 6655 @Override 6656 public void forceDexOpt(String packageName) { 6657 enforceSystemOrRoot("forceDexOpt"); 6658 6659 PackageParser.Package pkg; 6660 synchronized (mPackages) { 6661 pkg = mPackages.get(packageName); 6662 if (pkg == null) { 6663 throw new IllegalArgumentException("Unknown package: " + packageName); 6664 } 6665 } 6666 6667 synchronized (mInstallLock) { 6668 final String[] instructionSets = new String[] { 6669 getPrimaryInstructionSet(pkg.applicationInfo) }; 6670 6671 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6672 6673 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6674 true /* inclDependencies */); 6675 6676 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6677 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6678 throw new IllegalStateException("Failed to dexopt: " + res); 6679 } 6680 } 6681 } 6682 6683 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6684 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6685 Slog.w(TAG, "Unable to update from " + oldPkg.name 6686 + " to " + newPkg.packageName 6687 + ": old package not in system partition"); 6688 return false; 6689 } else if (mPackages.get(oldPkg.name) != null) { 6690 Slog.w(TAG, "Unable to update from " + oldPkg.name 6691 + " to " + newPkg.packageName 6692 + ": old package still exists"); 6693 return false; 6694 } 6695 return true; 6696 } 6697 6698 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6699 throws PackageManagerException { 6700 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6701 if (res != 0) { 6702 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6703 "Failed to install " + packageName + ": " + res); 6704 } 6705 6706 final int[] users = sUserManager.getUserIds(); 6707 for (int user : users) { 6708 if (user != 0) { 6709 res = mInstaller.createUserData(volumeUuid, packageName, 6710 UserHandle.getUid(user, uid), user, seinfo); 6711 if (res != 0) { 6712 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6713 "Failed to createUserData " + packageName + ": " + res); 6714 } 6715 } 6716 } 6717 } 6718 6719 private int removeDataDirsLI(String volumeUuid, String packageName) { 6720 int[] users = sUserManager.getUserIds(); 6721 int res = 0; 6722 for (int user : users) { 6723 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6724 if (resInner < 0) { 6725 res = resInner; 6726 } 6727 } 6728 6729 return res; 6730 } 6731 6732 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6733 int[] users = sUserManager.getUserIds(); 6734 int res = 0; 6735 for (int user : users) { 6736 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6737 if (resInner < 0) { 6738 res = resInner; 6739 } 6740 } 6741 return res; 6742 } 6743 6744 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6745 PackageParser.Package changingLib) { 6746 if (file.path != null) { 6747 usesLibraryFiles.add(file.path); 6748 return; 6749 } 6750 PackageParser.Package p = mPackages.get(file.apk); 6751 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6752 // If we are doing this while in the middle of updating a library apk, 6753 // then we need to make sure to use that new apk for determining the 6754 // dependencies here. (We haven't yet finished committing the new apk 6755 // to the package manager state.) 6756 if (p == null || p.packageName.equals(changingLib.packageName)) { 6757 p = changingLib; 6758 } 6759 } 6760 if (p != null) { 6761 usesLibraryFiles.addAll(p.getAllCodePaths()); 6762 } 6763 } 6764 6765 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6766 PackageParser.Package changingLib) throws PackageManagerException { 6767 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6768 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6769 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6770 for (int i=0; i<N; i++) { 6771 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6772 if (file == null) { 6773 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6774 "Package " + pkg.packageName + " requires unavailable shared library " 6775 + pkg.usesLibraries.get(i) + "; failing!"); 6776 } 6777 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6778 } 6779 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6780 for (int i=0; i<N; i++) { 6781 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6782 if (file == null) { 6783 Slog.w(TAG, "Package " + pkg.packageName 6784 + " desires unavailable shared library " 6785 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6786 } else { 6787 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6788 } 6789 } 6790 N = usesLibraryFiles.size(); 6791 if (N > 0) { 6792 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6793 } else { 6794 pkg.usesLibraryFiles = null; 6795 } 6796 } 6797 } 6798 6799 private static boolean hasString(List<String> list, List<String> which) { 6800 if (list == null) { 6801 return false; 6802 } 6803 for (int i=list.size()-1; i>=0; i--) { 6804 for (int j=which.size()-1; j>=0; j--) { 6805 if (which.get(j).equals(list.get(i))) { 6806 return true; 6807 } 6808 } 6809 } 6810 return false; 6811 } 6812 6813 private void updateAllSharedLibrariesLPw() { 6814 for (PackageParser.Package pkg : mPackages.values()) { 6815 try { 6816 updateSharedLibrariesLPw(pkg, null); 6817 } catch (PackageManagerException e) { 6818 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6819 } 6820 } 6821 } 6822 6823 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6824 PackageParser.Package changingPkg) { 6825 ArrayList<PackageParser.Package> res = null; 6826 for (PackageParser.Package pkg : mPackages.values()) { 6827 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6828 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6829 if (res == null) { 6830 res = new ArrayList<PackageParser.Package>(); 6831 } 6832 res.add(pkg); 6833 try { 6834 updateSharedLibrariesLPw(pkg, changingPkg); 6835 } catch (PackageManagerException e) { 6836 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6837 } 6838 } 6839 } 6840 return res; 6841 } 6842 6843 /** 6844 * Derive the value of the {@code cpuAbiOverride} based on the provided 6845 * value and an optional stored value from the package settings. 6846 */ 6847 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6848 String cpuAbiOverride = null; 6849 6850 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6851 cpuAbiOverride = null; 6852 } else if (abiOverride != null) { 6853 cpuAbiOverride = abiOverride; 6854 } else if (settings != null) { 6855 cpuAbiOverride = settings.cpuAbiOverrideString; 6856 } 6857 6858 return cpuAbiOverride; 6859 } 6860 6861 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6862 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6864 try { 6865 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6866 } finally { 6867 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6868 } 6869 } 6870 6871 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6872 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6873 boolean success = false; 6874 try { 6875 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6876 currentTime, user); 6877 success = true; 6878 return res; 6879 } finally { 6880 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6881 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6882 } 6883 } 6884 } 6885 6886 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6887 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6888 final File scanFile = new File(pkg.codePath); 6889 if (pkg.applicationInfo.getCodePath() == null || 6890 pkg.applicationInfo.getResourcePath() == null) { 6891 // Bail out. The resource and code paths haven't been set. 6892 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6893 "Code and resource paths haven't been set correctly"); 6894 } 6895 6896 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6897 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6898 } else { 6899 // Only allow system apps to be flagged as core apps. 6900 pkg.coreApp = false; 6901 } 6902 6903 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6904 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6905 } 6906 6907 if (mCustomResolverComponentName != null && 6908 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6909 setUpCustomResolverActivity(pkg); 6910 } 6911 6912 if (pkg.packageName.equals("android")) { 6913 synchronized (mPackages) { 6914 if (mAndroidApplication != null) { 6915 Slog.w(TAG, "*************************************************"); 6916 Slog.w(TAG, "Core android package being redefined. Skipping."); 6917 Slog.w(TAG, " file=" + scanFile); 6918 Slog.w(TAG, "*************************************************"); 6919 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6920 "Core android package being redefined. Skipping."); 6921 } 6922 6923 // Set up information for our fall-back user intent resolution activity. 6924 mPlatformPackage = pkg; 6925 pkg.mVersionCode = mSdkVersion; 6926 mAndroidApplication = pkg.applicationInfo; 6927 6928 if (!mResolverReplaced) { 6929 mResolveActivity.applicationInfo = mAndroidApplication; 6930 mResolveActivity.name = ResolverActivity.class.getName(); 6931 mResolveActivity.packageName = mAndroidApplication.packageName; 6932 mResolveActivity.processName = "system:ui"; 6933 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6934 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6935 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6936 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6937 mResolveActivity.exported = true; 6938 mResolveActivity.enabled = true; 6939 mResolveInfo.activityInfo = mResolveActivity; 6940 mResolveInfo.priority = 0; 6941 mResolveInfo.preferredOrder = 0; 6942 mResolveInfo.match = 0; 6943 mResolveComponentName = new ComponentName( 6944 mAndroidApplication.packageName, mResolveActivity.name); 6945 } 6946 } 6947 } 6948 6949 if (DEBUG_PACKAGE_SCANNING) { 6950 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6951 Log.d(TAG, "Scanning package " + pkg.packageName); 6952 } 6953 6954 if (mPackages.containsKey(pkg.packageName) 6955 || mSharedLibraries.containsKey(pkg.packageName)) { 6956 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6957 "Application package " + pkg.packageName 6958 + " already installed. Skipping duplicate."); 6959 } 6960 6961 // If we're only installing presumed-existing packages, require that the 6962 // scanned APK is both already known and at the path previously established 6963 // for it. Previously unknown packages we pick up normally, but if we have an 6964 // a priori expectation about this package's install presence, enforce it. 6965 // With a singular exception for new system packages. When an OTA contains 6966 // a new system package, we allow the codepath to change from a system location 6967 // to the user-installed location. If we don't allow this change, any newer, 6968 // user-installed version of the application will be ignored. 6969 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6970 if (mExpectingBetter.containsKey(pkg.packageName)) { 6971 logCriticalInfo(Log.WARN, 6972 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6973 } else { 6974 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6975 if (known != null) { 6976 if (DEBUG_PACKAGE_SCANNING) { 6977 Log.d(TAG, "Examining " + pkg.codePath 6978 + " and requiring known paths " + known.codePathString 6979 + " & " + known.resourcePathString); 6980 } 6981 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6982 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6983 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6984 "Application package " + pkg.packageName 6985 + " found at " + pkg.applicationInfo.getCodePath() 6986 + " but expected at " + known.codePathString + "; ignoring."); 6987 } 6988 } 6989 } 6990 } 6991 6992 // Initialize package source and resource directories 6993 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6994 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6995 6996 SharedUserSetting suid = null; 6997 PackageSetting pkgSetting = null; 6998 6999 if (!isSystemApp(pkg)) { 7000 // Only system apps can use these features. 7001 pkg.mOriginalPackages = null; 7002 pkg.mRealPackage = null; 7003 pkg.mAdoptPermissions = null; 7004 } 7005 7006 // writer 7007 synchronized (mPackages) { 7008 if (pkg.mSharedUserId != null) { 7009 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7010 if (suid == null) { 7011 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7012 "Creating application package " + pkg.packageName 7013 + " for shared user failed"); 7014 } 7015 if (DEBUG_PACKAGE_SCANNING) { 7016 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7017 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7018 + "): packages=" + suid.packages); 7019 } 7020 } 7021 7022 // Check if we are renaming from an original package name. 7023 PackageSetting origPackage = null; 7024 String realName = null; 7025 if (pkg.mOriginalPackages != null) { 7026 // This package may need to be renamed to a previously 7027 // installed name. Let's check on that... 7028 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7029 if (pkg.mOriginalPackages.contains(renamed)) { 7030 // This package had originally been installed as the 7031 // original name, and we have already taken care of 7032 // transitioning to the new one. Just update the new 7033 // one to continue using the old name. 7034 realName = pkg.mRealPackage; 7035 if (!pkg.packageName.equals(renamed)) { 7036 // Callers into this function may have already taken 7037 // care of renaming the package; only do it here if 7038 // it is not already done. 7039 pkg.setPackageName(renamed); 7040 } 7041 7042 } else { 7043 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7044 if ((origPackage = mSettings.peekPackageLPr( 7045 pkg.mOriginalPackages.get(i))) != null) { 7046 // We do have the package already installed under its 7047 // original name... should we use it? 7048 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7049 // New package is not compatible with original. 7050 origPackage = null; 7051 continue; 7052 } else if (origPackage.sharedUser != null) { 7053 // Make sure uid is compatible between packages. 7054 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7055 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7056 + " to " + pkg.packageName + ": old uid " 7057 + origPackage.sharedUser.name 7058 + " differs from " + pkg.mSharedUserId); 7059 origPackage = null; 7060 continue; 7061 } 7062 } else { 7063 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7064 + pkg.packageName + " to old name " + origPackage.name); 7065 } 7066 break; 7067 } 7068 } 7069 } 7070 } 7071 7072 if (mTransferedPackages.contains(pkg.packageName)) { 7073 Slog.w(TAG, "Package " + pkg.packageName 7074 + " was transferred to another, but its .apk remains"); 7075 } 7076 7077 // Just create the setting, don't add it yet. For already existing packages 7078 // the PkgSetting exists already and doesn't have to be created. 7079 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7080 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7081 pkg.applicationInfo.primaryCpuAbi, 7082 pkg.applicationInfo.secondaryCpuAbi, 7083 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7084 user, false); 7085 if (pkgSetting == null) { 7086 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7087 "Creating application package " + pkg.packageName + " failed"); 7088 } 7089 7090 if (pkgSetting.origPackage != null) { 7091 // If we are first transitioning from an original package, 7092 // fix up the new package's name now. We need to do this after 7093 // looking up the package under its new name, so getPackageLP 7094 // can take care of fiddling things correctly. 7095 pkg.setPackageName(origPackage.name); 7096 7097 // File a report about this. 7098 String msg = "New package " + pkgSetting.realName 7099 + " renamed to replace old package " + pkgSetting.name; 7100 reportSettingsProblem(Log.WARN, msg); 7101 7102 // Make a note of it. 7103 mTransferedPackages.add(origPackage.name); 7104 7105 // No longer need to retain this. 7106 pkgSetting.origPackage = null; 7107 } 7108 7109 if (realName != null) { 7110 // Make a note of it. 7111 mTransferedPackages.add(pkg.packageName); 7112 } 7113 7114 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7115 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7116 } 7117 7118 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7119 // Check all shared libraries and map to their actual file path. 7120 // We only do this here for apps not on a system dir, because those 7121 // are the only ones that can fail an install due to this. We 7122 // will take care of the system apps by updating all of their 7123 // library paths after the scan is done. 7124 updateSharedLibrariesLPw(pkg, null); 7125 } 7126 7127 if (mFoundPolicyFile) { 7128 SELinuxMMAC.assignSeinfoValue(pkg); 7129 } 7130 7131 pkg.applicationInfo.uid = pkgSetting.appId; 7132 pkg.mExtras = pkgSetting; 7133 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7134 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7135 // We just determined the app is signed correctly, so bring 7136 // over the latest parsed certs. 7137 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7138 } else { 7139 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7140 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7141 "Package " + pkg.packageName + " upgrade keys do not match the " 7142 + "previously installed version"); 7143 } else { 7144 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7145 String msg = "System package " + pkg.packageName 7146 + " signature changed; retaining data."; 7147 reportSettingsProblem(Log.WARN, msg); 7148 } 7149 } 7150 } else { 7151 try { 7152 verifySignaturesLP(pkgSetting, pkg); 7153 // We just determined the app is signed correctly, so bring 7154 // over the latest parsed certs. 7155 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7156 } catch (PackageManagerException e) { 7157 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7158 throw e; 7159 } 7160 // The signature has changed, but this package is in the system 7161 // image... let's recover! 7162 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7163 // However... if this package is part of a shared user, but it 7164 // doesn't match the signature of the shared user, let's fail. 7165 // What this means is that you can't change the signatures 7166 // associated with an overall shared user, which doesn't seem all 7167 // that unreasonable. 7168 if (pkgSetting.sharedUser != null) { 7169 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7170 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7171 throw new PackageManagerException( 7172 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7173 "Signature mismatch for shared user: " 7174 + pkgSetting.sharedUser); 7175 } 7176 } 7177 // File a report about this. 7178 String msg = "System package " + pkg.packageName 7179 + " signature changed; retaining data."; 7180 reportSettingsProblem(Log.WARN, msg); 7181 } 7182 } 7183 // Verify that this new package doesn't have any content providers 7184 // that conflict with existing packages. Only do this if the 7185 // package isn't already installed, since we don't want to break 7186 // things that are installed. 7187 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7188 final int N = pkg.providers.size(); 7189 int i; 7190 for (i=0; i<N; i++) { 7191 PackageParser.Provider p = pkg.providers.get(i); 7192 if (p.info.authority != null) { 7193 String names[] = p.info.authority.split(";"); 7194 for (int j = 0; j < names.length; j++) { 7195 if (mProvidersByAuthority.containsKey(names[j])) { 7196 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7197 final String otherPackageName = 7198 ((other != null && other.getComponentName() != null) ? 7199 other.getComponentName().getPackageName() : "?"); 7200 throw new PackageManagerException( 7201 INSTALL_FAILED_CONFLICTING_PROVIDER, 7202 "Can't install because provider name " + names[j] 7203 + " (in package " + pkg.applicationInfo.packageName 7204 + ") is already used by " + otherPackageName); 7205 } 7206 } 7207 } 7208 } 7209 } 7210 7211 if (pkg.mAdoptPermissions != null) { 7212 // This package wants to adopt ownership of permissions from 7213 // another package. 7214 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7215 final String origName = pkg.mAdoptPermissions.get(i); 7216 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7217 if (orig != null) { 7218 if (verifyPackageUpdateLPr(orig, pkg)) { 7219 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7220 + pkg.packageName); 7221 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7222 } 7223 } 7224 } 7225 } 7226 } 7227 7228 final String pkgName = pkg.packageName; 7229 7230 final long scanFileTime = scanFile.lastModified(); 7231 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7232 pkg.applicationInfo.processName = fixProcessName( 7233 pkg.applicationInfo.packageName, 7234 pkg.applicationInfo.processName, 7235 pkg.applicationInfo.uid); 7236 7237 if (pkg != mPlatformPackage) { 7238 // This is a normal package, need to make its data directory. 7239 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7240 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7241 7242 boolean uidError = false; 7243 if (dataPath.exists()) { 7244 int currentUid = 0; 7245 try { 7246 StructStat stat = Os.stat(dataPath.getPath()); 7247 currentUid = stat.st_uid; 7248 } catch (ErrnoException e) { 7249 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7250 } 7251 7252 // If we have mismatched owners for the data path, we have a problem. 7253 if (currentUid != pkg.applicationInfo.uid) { 7254 boolean recovered = false; 7255 if (currentUid == 0) { 7256 // The directory somehow became owned by root. Wow. 7257 // This is probably because the system was stopped while 7258 // installd was in the middle of messing with its libs 7259 // directory. Ask installd to fix that. 7260 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7261 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7262 if (ret >= 0) { 7263 recovered = true; 7264 String msg = "Package " + pkg.packageName 7265 + " unexpectedly changed to uid 0; recovered to " + 7266 + pkg.applicationInfo.uid; 7267 reportSettingsProblem(Log.WARN, msg); 7268 } 7269 } 7270 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7271 || (scanFlags&SCAN_BOOTING) != 0)) { 7272 // If this is a system app, we can at least delete its 7273 // current data so the application will still work. 7274 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7275 if (ret >= 0) { 7276 // TODO: Kill the processes first 7277 // Old data gone! 7278 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7279 ? "System package " : "Third party package "; 7280 String msg = prefix + pkg.packageName 7281 + " has changed from uid: " 7282 + currentUid + " to " 7283 + pkg.applicationInfo.uid + "; old data erased"; 7284 reportSettingsProblem(Log.WARN, msg); 7285 recovered = true; 7286 } 7287 if (!recovered) { 7288 mHasSystemUidErrors = true; 7289 } 7290 } else if (!recovered) { 7291 // If we allow this install to proceed, we will be broken. 7292 // Abort, abort! 7293 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7294 "scanPackageLI"); 7295 } 7296 if (!recovered) { 7297 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7298 + pkg.applicationInfo.uid + "/fs_" 7299 + currentUid; 7300 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7301 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7302 String msg = "Package " + pkg.packageName 7303 + " has mismatched uid: " 7304 + currentUid + " on disk, " 7305 + pkg.applicationInfo.uid + " in settings"; 7306 // writer 7307 synchronized (mPackages) { 7308 mSettings.mReadMessages.append(msg); 7309 mSettings.mReadMessages.append('\n'); 7310 uidError = true; 7311 if (!pkgSetting.uidError) { 7312 reportSettingsProblem(Log.ERROR, msg); 7313 } 7314 } 7315 } 7316 } 7317 7318 // Ensure that directories are prepared 7319 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7320 pkg.applicationInfo.seinfo); 7321 7322 if (mShouldRestoreconData) { 7323 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7324 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7325 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7326 } 7327 } else { 7328 if (DEBUG_PACKAGE_SCANNING) { 7329 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7330 Log.v(TAG, "Want this data dir: " + dataPath); 7331 } 7332 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7333 pkg.applicationInfo.seinfo); 7334 } 7335 7336 // Get all of our default paths setup 7337 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7338 7339 pkgSetting.uidError = uidError; 7340 } 7341 7342 final String path = scanFile.getPath(); 7343 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7344 7345 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7346 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7347 7348 // Some system apps still use directory structure for native libraries 7349 // in which case we might end up not detecting abi solely based on apk 7350 // structure. Try to detect abi based on directory structure. 7351 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7352 pkg.applicationInfo.primaryCpuAbi == null) { 7353 setBundledAppAbisAndRoots(pkg, pkgSetting); 7354 setNativeLibraryPaths(pkg); 7355 } 7356 7357 } else { 7358 if ((scanFlags & SCAN_MOVE) != 0) { 7359 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7360 // but we already have this packages package info in the PackageSetting. We just 7361 // use that and derive the native library path based on the new codepath. 7362 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7363 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7364 } 7365 7366 // Set native library paths again. For moves, the path will be updated based on the 7367 // ABIs we've determined above. For non-moves, the path will be updated based on the 7368 // ABIs we determined during compilation, but the path will depend on the final 7369 // package path (after the rename away from the stage path). 7370 setNativeLibraryPaths(pkg); 7371 } 7372 7373 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7374 final int[] userIds = sUserManager.getUserIds(); 7375 synchronized (mInstallLock) { 7376 // Make sure all user data directories are ready to roll; we're okay 7377 // if they already exist 7378 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7379 for (int userId : userIds) { 7380 if (userId != UserHandle.USER_SYSTEM) { 7381 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7382 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7383 pkg.applicationInfo.seinfo); 7384 } 7385 } 7386 } 7387 7388 // Create a native library symlink only if we have native libraries 7389 // and if the native libraries are 32 bit libraries. We do not provide 7390 // this symlink for 64 bit libraries. 7391 if (pkg.applicationInfo.primaryCpuAbi != null && 7392 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7394 try { 7395 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7396 for (int userId : userIds) { 7397 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7398 nativeLibPath, userId) < 0) { 7399 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7400 "Failed linking native library dir (user=" + userId + ")"); 7401 } 7402 } 7403 } finally { 7404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7405 } 7406 } 7407 } 7408 7409 // This is a special case for the "system" package, where the ABI is 7410 // dictated by the zygote configuration (and init.rc). We should keep track 7411 // of this ABI so that we can deal with "normal" applications that run under 7412 // the same UID correctly. 7413 if (mPlatformPackage == pkg) { 7414 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7415 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7416 } 7417 7418 // If there's a mismatch between the abi-override in the package setting 7419 // and the abiOverride specified for the install. Warn about this because we 7420 // would've already compiled the app without taking the package setting into 7421 // account. 7422 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7423 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7424 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7425 " for package " + pkg.packageName); 7426 } 7427 } 7428 7429 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7430 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7431 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7432 7433 // Copy the derived override back to the parsed package, so that we can 7434 // update the package settings accordingly. 7435 pkg.cpuAbiOverride = cpuAbiOverride; 7436 7437 if (DEBUG_ABI_SELECTION) { 7438 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7439 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7440 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7441 } 7442 7443 // Push the derived path down into PackageSettings so we know what to 7444 // clean up at uninstall time. 7445 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7446 7447 if (DEBUG_ABI_SELECTION) { 7448 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7449 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7450 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7451 } 7452 7453 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7454 // We don't do this here during boot because we can do it all 7455 // at once after scanning all existing packages. 7456 // 7457 // We also do this *before* we perform dexopt on this package, so that 7458 // we can avoid redundant dexopts, and also to make sure we've got the 7459 // code and package path correct. 7460 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7461 pkg, true /* boot complete */); 7462 } 7463 7464 if (mFactoryTest && pkg.requestedPermissions.contains( 7465 android.Manifest.permission.FACTORY_TEST)) { 7466 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7467 } 7468 7469 ArrayList<PackageParser.Package> clientLibPkgs = null; 7470 7471 // writer 7472 synchronized (mPackages) { 7473 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7474 // Only system apps can add new shared libraries. 7475 if (pkg.libraryNames != null) { 7476 for (int i=0; i<pkg.libraryNames.size(); i++) { 7477 String name = pkg.libraryNames.get(i); 7478 boolean allowed = false; 7479 if (pkg.isUpdatedSystemApp()) { 7480 // New library entries can only be added through the 7481 // system image. This is important to get rid of a lot 7482 // of nasty edge cases: for example if we allowed a non- 7483 // system update of the app to add a library, then uninstalling 7484 // the update would make the library go away, and assumptions 7485 // we made such as through app install filtering would now 7486 // have allowed apps on the device which aren't compatible 7487 // with it. Better to just have the restriction here, be 7488 // conservative, and create many fewer cases that can negatively 7489 // impact the user experience. 7490 final PackageSetting sysPs = mSettings 7491 .getDisabledSystemPkgLPr(pkg.packageName); 7492 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7493 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7494 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7495 allowed = true; 7496 break; 7497 } 7498 } 7499 } 7500 } else { 7501 allowed = true; 7502 } 7503 if (allowed) { 7504 if (!mSharedLibraries.containsKey(name)) { 7505 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7506 } else if (!name.equals(pkg.packageName)) { 7507 Slog.w(TAG, "Package " + pkg.packageName + " library " 7508 + name + " already exists; skipping"); 7509 } 7510 } else { 7511 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7512 + name + " that is not declared on system image; skipping"); 7513 } 7514 } 7515 if ((scanFlags & SCAN_BOOTING) == 0) { 7516 // If we are not booting, we need to update any applications 7517 // that are clients of our shared library. If we are booting, 7518 // this will all be done once the scan is complete. 7519 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7520 } 7521 } 7522 } 7523 } 7524 7525 // Request the ActivityManager to kill the process(only for existing packages) 7526 // so that we do not end up in a confused state while the user is still using the older 7527 // version of the application while the new one gets installed. 7528 if ((scanFlags & SCAN_REPLACING) != 0) { 7529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7530 7531 killApplication(pkg.applicationInfo.packageName, 7532 pkg.applicationInfo.uid, "replace pkg"); 7533 7534 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7535 } 7536 7537 // Also need to kill any apps that are dependent on the library. 7538 if (clientLibPkgs != null) { 7539 for (int i=0; i<clientLibPkgs.size(); i++) { 7540 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7541 killApplication(clientPkg.applicationInfo.packageName, 7542 clientPkg.applicationInfo.uid, "update lib"); 7543 } 7544 } 7545 7546 // Make sure we're not adding any bogus keyset info 7547 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7548 ksms.assertScannedPackageValid(pkg); 7549 7550 // writer 7551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7552 7553 boolean createIdmapFailed = false; 7554 synchronized (mPackages) { 7555 // We don't expect installation to fail beyond this point 7556 7557 // Add the new setting to mSettings 7558 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7559 // Add the new setting to mPackages 7560 mPackages.put(pkg.applicationInfo.packageName, pkg); 7561 // Make sure we don't accidentally delete its data. 7562 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7563 while (iter.hasNext()) { 7564 PackageCleanItem item = iter.next(); 7565 if (pkgName.equals(item.packageName)) { 7566 iter.remove(); 7567 } 7568 } 7569 7570 // Take care of first install / last update times. 7571 if (currentTime != 0) { 7572 if (pkgSetting.firstInstallTime == 0) { 7573 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7574 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7575 pkgSetting.lastUpdateTime = currentTime; 7576 } 7577 } else if (pkgSetting.firstInstallTime == 0) { 7578 // We need *something*. Take time time stamp of the file. 7579 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7580 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7581 if (scanFileTime != pkgSetting.timeStamp) { 7582 // A package on the system image has changed; consider this 7583 // to be an update. 7584 pkgSetting.lastUpdateTime = scanFileTime; 7585 } 7586 } 7587 7588 // Add the package's KeySets to the global KeySetManagerService 7589 ksms.addScannedPackageLPw(pkg); 7590 7591 int N = pkg.providers.size(); 7592 StringBuilder r = null; 7593 int i; 7594 for (i=0; i<N; i++) { 7595 PackageParser.Provider p = pkg.providers.get(i); 7596 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7597 p.info.processName, pkg.applicationInfo.uid); 7598 mProviders.addProvider(p); 7599 p.syncable = p.info.isSyncable; 7600 if (p.info.authority != null) { 7601 String names[] = p.info.authority.split(";"); 7602 p.info.authority = null; 7603 for (int j = 0; j < names.length; j++) { 7604 if (j == 1 && p.syncable) { 7605 // We only want the first authority for a provider to possibly be 7606 // syncable, so if we already added this provider using a different 7607 // authority clear the syncable flag. We copy the provider before 7608 // changing it because the mProviders object contains a reference 7609 // to a provider that we don't want to change. 7610 // Only do this for the second authority since the resulting provider 7611 // object can be the same for all future authorities for this provider. 7612 p = new PackageParser.Provider(p); 7613 p.syncable = false; 7614 } 7615 if (!mProvidersByAuthority.containsKey(names[j])) { 7616 mProvidersByAuthority.put(names[j], p); 7617 if (p.info.authority == null) { 7618 p.info.authority = names[j]; 7619 } else { 7620 p.info.authority = p.info.authority + ";" + names[j]; 7621 } 7622 if (DEBUG_PACKAGE_SCANNING) { 7623 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7624 Log.d(TAG, "Registered content provider: " + names[j] 7625 + ", className = " + p.info.name + ", isSyncable = " 7626 + p.info.isSyncable); 7627 } 7628 } else { 7629 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7630 Slog.w(TAG, "Skipping provider name " + names[j] + 7631 " (in package " + pkg.applicationInfo.packageName + 7632 "): name already used by " 7633 + ((other != null && other.getComponentName() != null) 7634 ? other.getComponentName().getPackageName() : "?")); 7635 } 7636 } 7637 } 7638 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7639 if (r == null) { 7640 r = new StringBuilder(256); 7641 } else { 7642 r.append(' '); 7643 } 7644 r.append(p.info.name); 7645 } 7646 } 7647 if (r != null) { 7648 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7649 } 7650 7651 N = pkg.services.size(); 7652 r = null; 7653 for (i=0; i<N; i++) { 7654 PackageParser.Service s = pkg.services.get(i); 7655 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7656 s.info.processName, pkg.applicationInfo.uid); 7657 mServices.addService(s); 7658 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7659 if (r == null) { 7660 r = new StringBuilder(256); 7661 } else { 7662 r.append(' '); 7663 } 7664 r.append(s.info.name); 7665 } 7666 } 7667 if (r != null) { 7668 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7669 } 7670 7671 N = pkg.receivers.size(); 7672 r = null; 7673 for (i=0; i<N; i++) { 7674 PackageParser.Activity a = pkg.receivers.get(i); 7675 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7676 a.info.processName, pkg.applicationInfo.uid); 7677 mReceivers.addActivity(a, "receiver"); 7678 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7679 if (r == null) { 7680 r = new StringBuilder(256); 7681 } else { 7682 r.append(' '); 7683 } 7684 r.append(a.info.name); 7685 } 7686 } 7687 if (r != null) { 7688 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7689 } 7690 7691 N = pkg.activities.size(); 7692 r = null; 7693 for (i=0; i<N; i++) { 7694 PackageParser.Activity a = pkg.activities.get(i); 7695 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7696 a.info.processName, pkg.applicationInfo.uid); 7697 mActivities.addActivity(a, "activity"); 7698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7699 if (r == null) { 7700 r = new StringBuilder(256); 7701 } else { 7702 r.append(' '); 7703 } 7704 r.append(a.info.name); 7705 } 7706 } 7707 if (r != null) { 7708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7709 } 7710 7711 N = pkg.permissionGroups.size(); 7712 r = null; 7713 for (i=0; i<N; i++) { 7714 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7715 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7716 if (cur == null) { 7717 mPermissionGroups.put(pg.info.name, pg); 7718 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7719 if (r == null) { 7720 r = new StringBuilder(256); 7721 } else { 7722 r.append(' '); 7723 } 7724 r.append(pg.info.name); 7725 } 7726 } else { 7727 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7728 + pg.info.packageName + " ignored: original from " 7729 + cur.info.packageName); 7730 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7731 if (r == null) { 7732 r = new StringBuilder(256); 7733 } else { 7734 r.append(' '); 7735 } 7736 r.append("DUP:"); 7737 r.append(pg.info.name); 7738 } 7739 } 7740 } 7741 if (r != null) { 7742 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7743 } 7744 7745 N = pkg.permissions.size(); 7746 r = null; 7747 for (i=0; i<N; i++) { 7748 PackageParser.Permission p = pkg.permissions.get(i); 7749 7750 // Assume by default that we did not install this permission into the system. 7751 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7752 7753 // Now that permission groups have a special meaning, we ignore permission 7754 // groups for legacy apps to prevent unexpected behavior. In particular, 7755 // permissions for one app being granted to someone just becuase they happen 7756 // to be in a group defined by another app (before this had no implications). 7757 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7758 p.group = mPermissionGroups.get(p.info.group); 7759 // Warn for a permission in an unknown group. 7760 if (p.info.group != null && p.group == null) { 7761 Slog.w(TAG, "Permission " + p.info.name + " from package " 7762 + p.info.packageName + " in an unknown group " + p.info.group); 7763 } 7764 } 7765 7766 ArrayMap<String, BasePermission> permissionMap = 7767 p.tree ? mSettings.mPermissionTrees 7768 : mSettings.mPermissions; 7769 BasePermission bp = permissionMap.get(p.info.name); 7770 7771 // Allow system apps to redefine non-system permissions 7772 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7773 final boolean currentOwnerIsSystem = (bp.perm != null 7774 && isSystemApp(bp.perm.owner)); 7775 if (isSystemApp(p.owner)) { 7776 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7777 // It's a built-in permission and no owner, take ownership now 7778 bp.packageSetting = pkgSetting; 7779 bp.perm = p; 7780 bp.uid = pkg.applicationInfo.uid; 7781 bp.sourcePackage = p.info.packageName; 7782 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7783 } else if (!currentOwnerIsSystem) { 7784 String msg = "New decl " + p.owner + " of permission " 7785 + p.info.name + " is system; overriding " + bp.sourcePackage; 7786 reportSettingsProblem(Log.WARN, msg); 7787 bp = null; 7788 } 7789 } 7790 } 7791 7792 if (bp == null) { 7793 bp = new BasePermission(p.info.name, p.info.packageName, 7794 BasePermission.TYPE_NORMAL); 7795 permissionMap.put(p.info.name, bp); 7796 } 7797 7798 if (bp.perm == null) { 7799 if (bp.sourcePackage == null 7800 || bp.sourcePackage.equals(p.info.packageName)) { 7801 BasePermission tree = findPermissionTreeLP(p.info.name); 7802 if (tree == null 7803 || tree.sourcePackage.equals(p.info.packageName)) { 7804 bp.packageSetting = pkgSetting; 7805 bp.perm = p; 7806 bp.uid = pkg.applicationInfo.uid; 7807 bp.sourcePackage = p.info.packageName; 7808 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7809 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7810 if (r == null) { 7811 r = new StringBuilder(256); 7812 } else { 7813 r.append(' '); 7814 } 7815 r.append(p.info.name); 7816 } 7817 } else { 7818 Slog.w(TAG, "Permission " + p.info.name + " from package " 7819 + p.info.packageName + " ignored: base tree " 7820 + tree.name + " is from package " 7821 + tree.sourcePackage); 7822 } 7823 } else { 7824 Slog.w(TAG, "Permission " + p.info.name + " from package " 7825 + p.info.packageName + " ignored: original from " 7826 + bp.sourcePackage); 7827 } 7828 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7829 if (r == null) { 7830 r = new StringBuilder(256); 7831 } else { 7832 r.append(' '); 7833 } 7834 r.append("DUP:"); 7835 r.append(p.info.name); 7836 } 7837 if (bp.perm == p) { 7838 bp.protectionLevel = p.info.protectionLevel; 7839 } 7840 } 7841 7842 if (r != null) { 7843 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7844 } 7845 7846 N = pkg.instrumentation.size(); 7847 r = null; 7848 for (i=0; i<N; i++) { 7849 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7850 a.info.packageName = pkg.applicationInfo.packageName; 7851 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7852 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7853 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7854 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7855 a.info.dataDir = pkg.applicationInfo.dataDir; 7856 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7857 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7858 7859 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7860 // need other information about the application, like the ABI and what not ? 7861 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7862 mInstrumentation.put(a.getComponentName(), a); 7863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7864 if (r == null) { 7865 r = new StringBuilder(256); 7866 } else { 7867 r.append(' '); 7868 } 7869 r.append(a.info.name); 7870 } 7871 } 7872 if (r != null) { 7873 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7874 } 7875 7876 if (pkg.protectedBroadcasts != null) { 7877 N = pkg.protectedBroadcasts.size(); 7878 for (i=0; i<N; i++) { 7879 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7880 } 7881 } 7882 7883 pkgSetting.setTimeStamp(scanFileTime); 7884 7885 // Create idmap files for pairs of (packages, overlay packages). 7886 // Note: "android", ie framework-res.apk, is handled by native layers. 7887 if (pkg.mOverlayTarget != null) { 7888 // This is an overlay package. 7889 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7890 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7891 mOverlays.put(pkg.mOverlayTarget, 7892 new ArrayMap<String, PackageParser.Package>()); 7893 } 7894 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7895 map.put(pkg.packageName, pkg); 7896 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7897 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7898 createIdmapFailed = true; 7899 } 7900 } 7901 } else if (mOverlays.containsKey(pkg.packageName) && 7902 !pkg.packageName.equals("android")) { 7903 // This is a regular package, with one or more known overlay packages. 7904 createIdmapsForPackageLI(pkg); 7905 } 7906 } 7907 7908 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7909 7910 if (createIdmapFailed) { 7911 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7912 "scanPackageLI failed to createIdmap"); 7913 } 7914 return pkg; 7915 } 7916 7917 /** 7918 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7919 * is derived purely on the basis of the contents of {@code scanFile} and 7920 * {@code cpuAbiOverride}. 7921 * 7922 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7923 */ 7924 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7925 String cpuAbiOverride, boolean extractLibs) 7926 throws PackageManagerException { 7927 // TODO: We can probably be smarter about this stuff. For installed apps, 7928 // we can calculate this information at install time once and for all. For 7929 // system apps, we can probably assume that this information doesn't change 7930 // after the first boot scan. As things stand, we do lots of unnecessary work. 7931 7932 // Give ourselves some initial paths; we'll come back for another 7933 // pass once we've determined ABI below. 7934 setNativeLibraryPaths(pkg); 7935 7936 // We would never need to extract libs for forward-locked and external packages, 7937 // since the container service will do it for us. We shouldn't attempt to 7938 // extract libs from system app when it was not updated. 7939 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7940 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7941 extractLibs = false; 7942 } 7943 7944 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7945 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7946 7947 NativeLibraryHelper.Handle handle = null; 7948 try { 7949 handle = NativeLibraryHelper.Handle.create(pkg); 7950 // TODO(multiArch): This can be null for apps that didn't go through the 7951 // usual installation process. We can calculate it again, like we 7952 // do during install time. 7953 // 7954 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7955 // unnecessary. 7956 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7957 7958 // Null out the abis so that they can be recalculated. 7959 pkg.applicationInfo.primaryCpuAbi = null; 7960 pkg.applicationInfo.secondaryCpuAbi = null; 7961 if (isMultiArch(pkg.applicationInfo)) { 7962 // Warn if we've set an abiOverride for multi-lib packages.. 7963 // By definition, we need to copy both 32 and 64 bit libraries for 7964 // such packages. 7965 if (pkg.cpuAbiOverride != null 7966 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7967 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7968 } 7969 7970 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7971 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7972 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7973 if (extractLibs) { 7974 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7975 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7976 useIsaSpecificSubdirs); 7977 } else { 7978 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7979 } 7980 } 7981 7982 maybeThrowExceptionForMultiArchCopy( 7983 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7984 7985 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7986 if (extractLibs) { 7987 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7988 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7989 useIsaSpecificSubdirs); 7990 } else { 7991 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7992 } 7993 } 7994 7995 maybeThrowExceptionForMultiArchCopy( 7996 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7997 7998 if (abi64 >= 0) { 7999 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8000 } 8001 8002 if (abi32 >= 0) { 8003 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8004 if (abi64 >= 0) { 8005 pkg.applicationInfo.secondaryCpuAbi = abi; 8006 } else { 8007 pkg.applicationInfo.primaryCpuAbi = abi; 8008 } 8009 } 8010 } else { 8011 String[] abiList = (cpuAbiOverride != null) ? 8012 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8013 8014 // Enable gross and lame hacks for apps that are built with old 8015 // SDK tools. We must scan their APKs for renderscript bitcode and 8016 // not launch them if it's present. Don't bother checking on devices 8017 // that don't have 64 bit support. 8018 boolean needsRenderScriptOverride = false; 8019 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8020 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8021 abiList = Build.SUPPORTED_32_BIT_ABIS; 8022 needsRenderScriptOverride = true; 8023 } 8024 8025 final int copyRet; 8026 if (extractLibs) { 8027 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8028 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8029 } else { 8030 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8031 } 8032 8033 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8034 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8035 "Error unpackaging native libs for app, errorCode=" + copyRet); 8036 } 8037 8038 if (copyRet >= 0) { 8039 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8040 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8041 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8042 } else if (needsRenderScriptOverride) { 8043 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8044 } 8045 } 8046 } catch (IOException ioe) { 8047 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8048 } finally { 8049 IoUtils.closeQuietly(handle); 8050 } 8051 8052 // Now that we've calculated the ABIs and determined if it's an internal app, 8053 // we will go ahead and populate the nativeLibraryPath. 8054 setNativeLibraryPaths(pkg); 8055 } 8056 8057 /** 8058 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8059 * i.e, so that all packages can be run inside a single process if required. 8060 * 8061 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8062 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8063 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8064 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8065 * updating a package that belongs to a shared user. 8066 * 8067 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8068 * adds unnecessary complexity. 8069 */ 8070 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8071 PackageParser.Package scannedPackage, boolean bootComplete) { 8072 String requiredInstructionSet = null; 8073 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8074 requiredInstructionSet = VMRuntime.getInstructionSet( 8075 scannedPackage.applicationInfo.primaryCpuAbi); 8076 } 8077 8078 PackageSetting requirer = null; 8079 for (PackageSetting ps : packagesForUser) { 8080 // If packagesForUser contains scannedPackage, we skip it. This will happen 8081 // when scannedPackage is an update of an existing package. Without this check, 8082 // we will never be able to change the ABI of any package belonging to a shared 8083 // user, even if it's compatible with other packages. 8084 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8085 if (ps.primaryCpuAbiString == null) { 8086 continue; 8087 } 8088 8089 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8090 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8091 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8092 // this but there's not much we can do. 8093 String errorMessage = "Instruction set mismatch, " 8094 + ((requirer == null) ? "[caller]" : requirer) 8095 + " requires " + requiredInstructionSet + " whereas " + ps 8096 + " requires " + instructionSet; 8097 Slog.w(TAG, errorMessage); 8098 } 8099 8100 if (requiredInstructionSet == null) { 8101 requiredInstructionSet = instructionSet; 8102 requirer = ps; 8103 } 8104 } 8105 } 8106 8107 if (requiredInstructionSet != null) { 8108 String adjustedAbi; 8109 if (requirer != null) { 8110 // requirer != null implies that either scannedPackage was null or that scannedPackage 8111 // did not require an ABI, in which case we have to adjust scannedPackage to match 8112 // the ABI of the set (which is the same as requirer's ABI) 8113 adjustedAbi = requirer.primaryCpuAbiString; 8114 if (scannedPackage != null) { 8115 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8116 } 8117 } else { 8118 // requirer == null implies that we're updating all ABIs in the set to 8119 // match scannedPackage. 8120 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8121 } 8122 8123 for (PackageSetting ps : packagesForUser) { 8124 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8125 if (ps.primaryCpuAbiString != null) { 8126 continue; 8127 } 8128 8129 ps.primaryCpuAbiString = adjustedAbi; 8130 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8131 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8132 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8133 mInstaller.rmdex(ps.codePathString, 8134 getDexCodeInstructionSet(getPreferredInstructionSet())); 8135 } 8136 } 8137 } 8138 } 8139 } 8140 8141 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8142 synchronized (mPackages) { 8143 mResolverReplaced = true; 8144 // Set up information for custom user intent resolution activity. 8145 mResolveActivity.applicationInfo = pkg.applicationInfo; 8146 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8147 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8148 mResolveActivity.processName = pkg.applicationInfo.packageName; 8149 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8150 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8151 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8152 mResolveActivity.theme = 0; 8153 mResolveActivity.exported = true; 8154 mResolveActivity.enabled = true; 8155 mResolveInfo.activityInfo = mResolveActivity; 8156 mResolveInfo.priority = 0; 8157 mResolveInfo.preferredOrder = 0; 8158 mResolveInfo.match = 0; 8159 mResolveComponentName = mCustomResolverComponentName; 8160 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8161 mResolveComponentName); 8162 } 8163 } 8164 8165 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8166 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8167 8168 // Set up information for ephemeral installer activity 8169 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8170 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8171 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8172 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8173 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8174 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8175 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8176 mEphemeralInstallerActivity.theme = 0; 8177 mEphemeralInstallerActivity.exported = true; 8178 mEphemeralInstallerActivity.enabled = true; 8179 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8180 mEphemeralInstallerInfo.priority = 0; 8181 mEphemeralInstallerInfo.preferredOrder = 0; 8182 mEphemeralInstallerInfo.match = 0; 8183 8184 if (DEBUG_EPHEMERAL) { 8185 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8186 } 8187 } 8188 8189 private static String calculateBundledApkRoot(final String codePathString) { 8190 final File codePath = new File(codePathString); 8191 final File codeRoot; 8192 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8193 codeRoot = Environment.getRootDirectory(); 8194 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8195 codeRoot = Environment.getOemDirectory(); 8196 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8197 codeRoot = Environment.getVendorDirectory(); 8198 } else { 8199 // Unrecognized code path; take its top real segment as the apk root: 8200 // e.g. /something/app/blah.apk => /something 8201 try { 8202 File f = codePath.getCanonicalFile(); 8203 File parent = f.getParentFile(); // non-null because codePath is a file 8204 File tmp; 8205 while ((tmp = parent.getParentFile()) != null) { 8206 f = parent; 8207 parent = tmp; 8208 } 8209 codeRoot = f; 8210 Slog.w(TAG, "Unrecognized code path " 8211 + codePath + " - using " + codeRoot); 8212 } catch (IOException e) { 8213 // Can't canonicalize the code path -- shenanigans? 8214 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8215 return Environment.getRootDirectory().getPath(); 8216 } 8217 } 8218 return codeRoot.getPath(); 8219 } 8220 8221 /** 8222 * Derive and set the location of native libraries for the given package, 8223 * which varies depending on where and how the package was installed. 8224 */ 8225 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8226 final ApplicationInfo info = pkg.applicationInfo; 8227 final String codePath = pkg.codePath; 8228 final File codeFile = new File(codePath); 8229 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8230 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8231 8232 info.nativeLibraryRootDir = null; 8233 info.nativeLibraryRootRequiresIsa = false; 8234 info.nativeLibraryDir = null; 8235 info.secondaryNativeLibraryDir = null; 8236 8237 if (isApkFile(codeFile)) { 8238 // Monolithic install 8239 if (bundledApp) { 8240 // If "/system/lib64/apkname" exists, assume that is the per-package 8241 // native library directory to use; otherwise use "/system/lib/apkname". 8242 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8243 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8244 getPrimaryInstructionSet(info)); 8245 8246 // This is a bundled system app so choose the path based on the ABI. 8247 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8248 // is just the default path. 8249 final String apkName = deriveCodePathName(codePath); 8250 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8251 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8252 apkName).getAbsolutePath(); 8253 8254 if (info.secondaryCpuAbi != null) { 8255 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8256 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8257 secondaryLibDir, apkName).getAbsolutePath(); 8258 } 8259 } else if (asecApp) { 8260 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8261 .getAbsolutePath(); 8262 } else { 8263 final String apkName = deriveCodePathName(codePath); 8264 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8265 .getAbsolutePath(); 8266 } 8267 8268 info.nativeLibraryRootRequiresIsa = false; 8269 info.nativeLibraryDir = info.nativeLibraryRootDir; 8270 } else { 8271 // Cluster install 8272 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8273 info.nativeLibraryRootRequiresIsa = true; 8274 8275 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8276 getPrimaryInstructionSet(info)).getAbsolutePath(); 8277 8278 if (info.secondaryCpuAbi != null) { 8279 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8280 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8281 } 8282 } 8283 } 8284 8285 /** 8286 * Calculate the abis and roots for a bundled app. These can uniquely 8287 * be determined from the contents of the system partition, i.e whether 8288 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8289 * of this information, and instead assume that the system was built 8290 * sensibly. 8291 */ 8292 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8293 PackageSetting pkgSetting) { 8294 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8295 8296 // If "/system/lib64/apkname" exists, assume that is the per-package 8297 // native library directory to use; otherwise use "/system/lib/apkname". 8298 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8299 setBundledAppAbi(pkg, apkRoot, apkName); 8300 // pkgSetting might be null during rescan following uninstall of updates 8301 // to a bundled app, so accommodate that possibility. The settings in 8302 // that case will be established later from the parsed package. 8303 // 8304 // If the settings aren't null, sync them up with what we've just derived. 8305 // note that apkRoot isn't stored in the package settings. 8306 if (pkgSetting != null) { 8307 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8308 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8309 } 8310 } 8311 8312 /** 8313 * Deduces the ABI of a bundled app and sets the relevant fields on the 8314 * parsed pkg object. 8315 * 8316 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8317 * under which system libraries are installed. 8318 * @param apkName the name of the installed package. 8319 */ 8320 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8321 final File codeFile = new File(pkg.codePath); 8322 8323 final boolean has64BitLibs; 8324 final boolean has32BitLibs; 8325 if (isApkFile(codeFile)) { 8326 // Monolithic install 8327 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8328 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8329 } else { 8330 // Cluster install 8331 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8332 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8333 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8334 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8335 has64BitLibs = (new File(rootDir, isa)).exists(); 8336 } else { 8337 has64BitLibs = false; 8338 } 8339 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8340 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8341 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8342 has32BitLibs = (new File(rootDir, isa)).exists(); 8343 } else { 8344 has32BitLibs = false; 8345 } 8346 } 8347 8348 if (has64BitLibs && !has32BitLibs) { 8349 // The package has 64 bit libs, but not 32 bit libs. Its primary 8350 // ABI should be 64 bit. We can safely assume here that the bundled 8351 // native libraries correspond to the most preferred ABI in the list. 8352 8353 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8354 pkg.applicationInfo.secondaryCpuAbi = null; 8355 } else if (has32BitLibs && !has64BitLibs) { 8356 // The package has 32 bit libs but not 64 bit libs. Its primary 8357 // ABI should be 32 bit. 8358 8359 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8360 pkg.applicationInfo.secondaryCpuAbi = null; 8361 } else if (has32BitLibs && has64BitLibs) { 8362 // The application has both 64 and 32 bit bundled libraries. We check 8363 // here that the app declares multiArch support, and warn if it doesn't. 8364 // 8365 // We will be lenient here and record both ABIs. The primary will be the 8366 // ABI that's higher on the list, i.e, a device that's configured to prefer 8367 // 64 bit apps will see a 64 bit primary ABI, 8368 8369 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8370 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8371 } 8372 8373 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8374 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8375 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8376 } else { 8377 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8378 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8379 } 8380 } else { 8381 pkg.applicationInfo.primaryCpuAbi = null; 8382 pkg.applicationInfo.secondaryCpuAbi = null; 8383 } 8384 } 8385 8386 private void killApplication(String pkgName, int appId, String reason) { 8387 // Request the ActivityManager to kill the process(only for existing packages) 8388 // so that we do not end up in a confused state while the user is still using the older 8389 // version of the application while the new one gets installed. 8390 IActivityManager am = ActivityManagerNative.getDefault(); 8391 if (am != null) { 8392 try { 8393 am.killApplicationWithAppId(pkgName, appId, reason); 8394 } catch (RemoteException e) { 8395 } 8396 } 8397 } 8398 8399 void removePackageLI(PackageSetting ps, boolean chatty) { 8400 if (DEBUG_INSTALL) { 8401 if (chatty) 8402 Log.d(TAG, "Removing package " + ps.name); 8403 } 8404 8405 // writer 8406 synchronized (mPackages) { 8407 mPackages.remove(ps.name); 8408 final PackageParser.Package pkg = ps.pkg; 8409 if (pkg != null) { 8410 cleanPackageDataStructuresLILPw(pkg, chatty); 8411 } 8412 } 8413 } 8414 8415 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8416 if (DEBUG_INSTALL) { 8417 if (chatty) 8418 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8419 } 8420 8421 // writer 8422 synchronized (mPackages) { 8423 mPackages.remove(pkg.applicationInfo.packageName); 8424 cleanPackageDataStructuresLILPw(pkg, chatty); 8425 } 8426 } 8427 8428 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8429 int N = pkg.providers.size(); 8430 StringBuilder r = null; 8431 int i; 8432 for (i=0; i<N; i++) { 8433 PackageParser.Provider p = pkg.providers.get(i); 8434 mProviders.removeProvider(p); 8435 if (p.info.authority == null) { 8436 8437 /* There was another ContentProvider with this authority when 8438 * this app was installed so this authority is null, 8439 * Ignore it as we don't have to unregister the provider. 8440 */ 8441 continue; 8442 } 8443 String names[] = p.info.authority.split(";"); 8444 for (int j = 0; j < names.length; j++) { 8445 if (mProvidersByAuthority.get(names[j]) == p) { 8446 mProvidersByAuthority.remove(names[j]); 8447 if (DEBUG_REMOVE) { 8448 if (chatty) 8449 Log.d(TAG, "Unregistered content provider: " + names[j] 8450 + ", className = " + p.info.name + ", isSyncable = " 8451 + p.info.isSyncable); 8452 } 8453 } 8454 } 8455 if (DEBUG_REMOVE && chatty) { 8456 if (r == null) { 8457 r = new StringBuilder(256); 8458 } else { 8459 r.append(' '); 8460 } 8461 r.append(p.info.name); 8462 } 8463 } 8464 if (r != null) { 8465 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8466 } 8467 8468 N = pkg.services.size(); 8469 r = null; 8470 for (i=0; i<N; i++) { 8471 PackageParser.Service s = pkg.services.get(i); 8472 mServices.removeService(s); 8473 if (chatty) { 8474 if (r == null) { 8475 r = new StringBuilder(256); 8476 } else { 8477 r.append(' '); 8478 } 8479 r.append(s.info.name); 8480 } 8481 } 8482 if (r != null) { 8483 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8484 } 8485 8486 N = pkg.receivers.size(); 8487 r = null; 8488 for (i=0; i<N; i++) { 8489 PackageParser.Activity a = pkg.receivers.get(i); 8490 mReceivers.removeActivity(a, "receiver"); 8491 if (DEBUG_REMOVE && chatty) { 8492 if (r == null) { 8493 r = new StringBuilder(256); 8494 } else { 8495 r.append(' '); 8496 } 8497 r.append(a.info.name); 8498 } 8499 } 8500 if (r != null) { 8501 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8502 } 8503 8504 N = pkg.activities.size(); 8505 r = null; 8506 for (i=0; i<N; i++) { 8507 PackageParser.Activity a = pkg.activities.get(i); 8508 mActivities.removeActivity(a, "activity"); 8509 if (DEBUG_REMOVE && chatty) { 8510 if (r == null) { 8511 r = new StringBuilder(256); 8512 } else { 8513 r.append(' '); 8514 } 8515 r.append(a.info.name); 8516 } 8517 } 8518 if (r != null) { 8519 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8520 } 8521 8522 N = pkg.permissions.size(); 8523 r = null; 8524 for (i=0; i<N; i++) { 8525 PackageParser.Permission p = pkg.permissions.get(i); 8526 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8527 if (bp == null) { 8528 bp = mSettings.mPermissionTrees.get(p.info.name); 8529 } 8530 if (bp != null && bp.perm == p) { 8531 bp.perm = null; 8532 if (DEBUG_REMOVE && chatty) { 8533 if (r == null) { 8534 r = new StringBuilder(256); 8535 } else { 8536 r.append(' '); 8537 } 8538 r.append(p.info.name); 8539 } 8540 } 8541 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8542 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8543 if (appOpPkgs != null) { 8544 appOpPkgs.remove(pkg.packageName); 8545 } 8546 } 8547 } 8548 if (r != null) { 8549 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8550 } 8551 8552 N = pkg.requestedPermissions.size(); 8553 r = null; 8554 for (i=0; i<N; i++) { 8555 String perm = pkg.requestedPermissions.get(i); 8556 BasePermission bp = mSettings.mPermissions.get(perm); 8557 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8558 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8559 if (appOpPkgs != null) { 8560 appOpPkgs.remove(pkg.packageName); 8561 if (appOpPkgs.isEmpty()) { 8562 mAppOpPermissionPackages.remove(perm); 8563 } 8564 } 8565 } 8566 } 8567 if (r != null) { 8568 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8569 } 8570 8571 N = pkg.instrumentation.size(); 8572 r = null; 8573 for (i=0; i<N; i++) { 8574 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8575 mInstrumentation.remove(a.getComponentName()); 8576 if (DEBUG_REMOVE && chatty) { 8577 if (r == null) { 8578 r = new StringBuilder(256); 8579 } else { 8580 r.append(' '); 8581 } 8582 r.append(a.info.name); 8583 } 8584 } 8585 if (r != null) { 8586 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8587 } 8588 8589 r = null; 8590 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8591 // Only system apps can hold shared libraries. 8592 if (pkg.libraryNames != null) { 8593 for (i=0; i<pkg.libraryNames.size(); i++) { 8594 String name = pkg.libraryNames.get(i); 8595 SharedLibraryEntry cur = mSharedLibraries.get(name); 8596 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8597 mSharedLibraries.remove(name); 8598 if (DEBUG_REMOVE && chatty) { 8599 if (r == null) { 8600 r = new StringBuilder(256); 8601 } else { 8602 r.append(' '); 8603 } 8604 r.append(name); 8605 } 8606 } 8607 } 8608 } 8609 } 8610 if (r != null) { 8611 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8612 } 8613 } 8614 8615 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8616 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8617 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8618 return true; 8619 } 8620 } 8621 return false; 8622 } 8623 8624 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8625 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8626 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8627 8628 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8629 int flags) { 8630 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8631 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8632 } 8633 8634 private void updatePermissionsLPw(String changingPkg, 8635 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8636 // Make sure there are no dangling permission trees. 8637 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8638 while (it.hasNext()) { 8639 final BasePermission bp = it.next(); 8640 if (bp.packageSetting == null) { 8641 // We may not yet have parsed the package, so just see if 8642 // we still know about its settings. 8643 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8644 } 8645 if (bp.packageSetting == null) { 8646 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8647 + " from package " + bp.sourcePackage); 8648 it.remove(); 8649 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8650 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8651 Slog.i(TAG, "Removing old permission tree: " + bp.name 8652 + " from package " + bp.sourcePackage); 8653 flags |= UPDATE_PERMISSIONS_ALL; 8654 it.remove(); 8655 } 8656 } 8657 } 8658 8659 // Make sure all dynamic permissions have been assigned to a package, 8660 // and make sure there are no dangling permissions. 8661 it = mSettings.mPermissions.values().iterator(); 8662 while (it.hasNext()) { 8663 final BasePermission bp = it.next(); 8664 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8665 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8666 + bp.name + " pkg=" + bp.sourcePackage 8667 + " info=" + bp.pendingInfo); 8668 if (bp.packageSetting == null && bp.pendingInfo != null) { 8669 final BasePermission tree = findPermissionTreeLP(bp.name); 8670 if (tree != null && tree.perm != null) { 8671 bp.packageSetting = tree.packageSetting; 8672 bp.perm = new PackageParser.Permission(tree.perm.owner, 8673 new PermissionInfo(bp.pendingInfo)); 8674 bp.perm.info.packageName = tree.perm.info.packageName; 8675 bp.perm.info.name = bp.name; 8676 bp.uid = tree.uid; 8677 } 8678 } 8679 } 8680 if (bp.packageSetting == null) { 8681 // We may not yet have parsed the package, so just see if 8682 // we still know about its settings. 8683 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8684 } 8685 if (bp.packageSetting == null) { 8686 Slog.w(TAG, "Removing dangling permission: " + bp.name 8687 + " from package " + bp.sourcePackage); 8688 it.remove(); 8689 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8690 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8691 Slog.i(TAG, "Removing old permission: " + bp.name 8692 + " from package " + bp.sourcePackage); 8693 flags |= UPDATE_PERMISSIONS_ALL; 8694 it.remove(); 8695 } 8696 } 8697 } 8698 8699 // Now update the permissions for all packages, in particular 8700 // replace the granted permissions of the system packages. 8701 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8702 for (PackageParser.Package pkg : mPackages.values()) { 8703 if (pkg != pkgInfo) { 8704 // Only replace for packages on requested volume 8705 final String volumeUuid = getVolumeUuidForPackage(pkg); 8706 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8707 && Objects.equals(replaceVolumeUuid, volumeUuid); 8708 grantPermissionsLPw(pkg, replace, changingPkg); 8709 } 8710 } 8711 } 8712 8713 if (pkgInfo != null) { 8714 // Only replace for packages on requested volume 8715 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8716 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8717 && Objects.equals(replaceVolumeUuid, volumeUuid); 8718 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8719 } 8720 } 8721 8722 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8723 String packageOfInterest) { 8724 // IMPORTANT: There are two types of permissions: install and runtime. 8725 // Install time permissions are granted when the app is installed to 8726 // all device users and users added in the future. Runtime permissions 8727 // are granted at runtime explicitly to specific users. Normal and signature 8728 // protected permissions are install time permissions. Dangerous permissions 8729 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8730 // otherwise they are runtime permissions. This function does not manage 8731 // runtime permissions except for the case an app targeting Lollipop MR1 8732 // being upgraded to target a newer SDK, in which case dangerous permissions 8733 // are transformed from install time to runtime ones. 8734 8735 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8736 if (ps == null) { 8737 return; 8738 } 8739 8740 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8741 8742 PermissionsState permissionsState = ps.getPermissionsState(); 8743 PermissionsState origPermissions = permissionsState; 8744 8745 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8746 8747 boolean runtimePermissionsRevoked = false; 8748 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8749 8750 boolean changedInstallPermission = false; 8751 8752 if (replace) { 8753 ps.installPermissionsFixed = false; 8754 if (!ps.isSharedUser()) { 8755 origPermissions = new PermissionsState(permissionsState); 8756 permissionsState.reset(); 8757 } else { 8758 // We need to know only about runtime permission changes since the 8759 // calling code always writes the install permissions state but 8760 // the runtime ones are written only if changed. The only cases of 8761 // changed runtime permissions here are promotion of an install to 8762 // runtime and revocation of a runtime from a shared user. 8763 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8764 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8765 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8766 runtimePermissionsRevoked = true; 8767 } 8768 } 8769 } 8770 8771 permissionsState.setGlobalGids(mGlobalGids); 8772 8773 final int N = pkg.requestedPermissions.size(); 8774 for (int i=0; i<N; i++) { 8775 final String name = pkg.requestedPermissions.get(i); 8776 final BasePermission bp = mSettings.mPermissions.get(name); 8777 8778 if (DEBUG_INSTALL) { 8779 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8780 } 8781 8782 if (bp == null || bp.packageSetting == null) { 8783 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8784 Slog.w(TAG, "Unknown permission " + name 8785 + " in package " + pkg.packageName); 8786 } 8787 continue; 8788 } 8789 8790 final String perm = bp.name; 8791 boolean allowedSig = false; 8792 int grant = GRANT_DENIED; 8793 8794 // Keep track of app op permissions. 8795 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8796 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8797 if (pkgs == null) { 8798 pkgs = new ArraySet<>(); 8799 mAppOpPermissionPackages.put(bp.name, pkgs); 8800 } 8801 pkgs.add(pkg.packageName); 8802 } 8803 8804 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8805 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8806 >= Build.VERSION_CODES.M; 8807 switch (level) { 8808 case PermissionInfo.PROTECTION_NORMAL: { 8809 // For all apps normal permissions are install time ones. 8810 grant = GRANT_INSTALL; 8811 } break; 8812 8813 case PermissionInfo.PROTECTION_DANGEROUS: { 8814 // If a permission review is required for legacy apps we represent 8815 // their permissions as always granted runtime ones since we need 8816 // to keep the review required permission flag per user while an 8817 // install permission's state is shared across all users. 8818 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8819 // For legacy apps dangerous permissions are install time ones. 8820 grant = GRANT_INSTALL; 8821 } else if (origPermissions.hasInstallPermission(bp.name)) { 8822 // For legacy apps that became modern, install becomes runtime. 8823 grant = GRANT_UPGRADE; 8824 } else if (mPromoteSystemApps 8825 && isSystemApp(ps) 8826 && mExistingSystemPackages.contains(ps.name)) { 8827 // For legacy system apps, install becomes runtime. 8828 // We cannot check hasInstallPermission() for system apps since those 8829 // permissions were granted implicitly and not persisted pre-M. 8830 grant = GRANT_UPGRADE; 8831 } else { 8832 // For modern apps keep runtime permissions unchanged. 8833 grant = GRANT_RUNTIME; 8834 } 8835 } break; 8836 8837 case PermissionInfo.PROTECTION_SIGNATURE: { 8838 // For all apps signature permissions are install time ones. 8839 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8840 if (allowedSig) { 8841 grant = GRANT_INSTALL; 8842 } 8843 } break; 8844 } 8845 8846 if (DEBUG_INSTALL) { 8847 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8848 } 8849 8850 if (grant != GRANT_DENIED) { 8851 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8852 // If this is an existing, non-system package, then 8853 // we can't add any new permissions to it. 8854 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8855 // Except... if this is a permission that was added 8856 // to the platform (note: need to only do this when 8857 // updating the platform). 8858 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8859 grant = GRANT_DENIED; 8860 } 8861 } 8862 } 8863 8864 switch (grant) { 8865 case GRANT_INSTALL: { 8866 // Revoke this as runtime permission to handle the case of 8867 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8868 for (int userId : UserManagerService.getInstance().getUserIds()) { 8869 if (origPermissions.getRuntimePermissionState( 8870 bp.name, userId) != null) { 8871 // Revoke the runtime permission and clear the flags. 8872 origPermissions.revokeRuntimePermission(bp, userId); 8873 origPermissions.updatePermissionFlags(bp, userId, 8874 PackageManager.MASK_PERMISSION_FLAGS, 0); 8875 // If we revoked a permission permission, we have to write. 8876 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8877 changedRuntimePermissionUserIds, userId); 8878 } 8879 } 8880 // Grant an install permission. 8881 if (permissionsState.grantInstallPermission(bp) != 8882 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8883 changedInstallPermission = true; 8884 } 8885 } break; 8886 8887 case GRANT_RUNTIME: { 8888 // Grant previously granted runtime permissions. 8889 for (int userId : UserManagerService.getInstance().getUserIds()) { 8890 PermissionState permissionState = origPermissions 8891 .getRuntimePermissionState(bp.name, userId); 8892 int flags = permissionState != null 8893 ? permissionState.getFlags() : 0; 8894 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8895 if (permissionsState.grantRuntimePermission(bp, userId) == 8896 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8897 // If we cannot put the permission as it was, we have to write. 8898 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8899 changedRuntimePermissionUserIds, userId); 8900 } 8901 // If the app supports runtime permissions no need for a review. 8902 if (Build.PERMISSIONS_REVIEW_REQUIRED 8903 && appSupportsRuntimePermissions 8904 && (flags & PackageManager 8905 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8906 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8907 // Since we changed the flags, we have to write. 8908 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8909 changedRuntimePermissionUserIds, userId); 8910 } 8911 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8912 && !appSupportsRuntimePermissions) { 8913 // For legacy apps that need a permission review, every new 8914 // runtime permission is granted but it is pending a review. 8915 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8916 permissionsState.grantRuntimePermission(bp, userId); 8917 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8918 // We changed the permission and flags, hence have to write. 8919 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8920 changedRuntimePermissionUserIds, userId); 8921 } 8922 } 8923 // Propagate the permission flags. 8924 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8925 } 8926 } break; 8927 8928 case GRANT_UPGRADE: { 8929 // Grant runtime permissions for a previously held install permission. 8930 PermissionState permissionState = origPermissions 8931 .getInstallPermissionState(bp.name); 8932 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8933 8934 if (origPermissions.revokeInstallPermission(bp) 8935 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8936 // We will be transferring the permission flags, so clear them. 8937 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8938 PackageManager.MASK_PERMISSION_FLAGS, 0); 8939 changedInstallPermission = true; 8940 } 8941 8942 // If the permission is not to be promoted to runtime we ignore it and 8943 // also its other flags as they are not applicable to install permissions. 8944 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8945 for (int userId : currentUserIds) { 8946 if (permissionsState.grantRuntimePermission(bp, userId) != 8947 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8948 // Transfer the permission flags. 8949 permissionsState.updatePermissionFlags(bp, userId, 8950 flags, flags); 8951 // If we granted the permission, we have to write. 8952 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8953 changedRuntimePermissionUserIds, userId); 8954 } 8955 } 8956 } 8957 } break; 8958 8959 default: { 8960 if (packageOfInterest == null 8961 || packageOfInterest.equals(pkg.packageName)) { 8962 Slog.w(TAG, "Not granting permission " + perm 8963 + " to package " + pkg.packageName 8964 + " because it was previously installed without"); 8965 } 8966 } break; 8967 } 8968 } else { 8969 if (permissionsState.revokeInstallPermission(bp) != 8970 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8971 // Also drop the permission flags. 8972 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8973 PackageManager.MASK_PERMISSION_FLAGS, 0); 8974 changedInstallPermission = true; 8975 Slog.i(TAG, "Un-granting permission " + perm 8976 + " from package " + pkg.packageName 8977 + " (protectionLevel=" + bp.protectionLevel 8978 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8979 + ")"); 8980 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8981 // Don't print warning for app op permissions, since it is fine for them 8982 // not to be granted, there is a UI for the user to decide. 8983 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8984 Slog.w(TAG, "Not granting permission " + perm 8985 + " to package " + pkg.packageName 8986 + " (protectionLevel=" + bp.protectionLevel 8987 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8988 + ")"); 8989 } 8990 } 8991 } 8992 } 8993 8994 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8995 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8996 // This is the first that we have heard about this package, so the 8997 // permissions we have now selected are fixed until explicitly 8998 // changed. 8999 ps.installPermissionsFixed = true; 9000 } 9001 9002 // Persist the runtime permissions state for users with changes. If permissions 9003 // were revoked because no app in the shared user declares them we have to 9004 // write synchronously to avoid losing runtime permissions state. 9005 for (int userId : changedRuntimePermissionUserIds) { 9006 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9007 } 9008 9009 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9010 } 9011 9012 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9013 boolean allowed = false; 9014 final int NP = PackageParser.NEW_PERMISSIONS.length; 9015 for (int ip=0; ip<NP; ip++) { 9016 final PackageParser.NewPermissionInfo npi 9017 = PackageParser.NEW_PERMISSIONS[ip]; 9018 if (npi.name.equals(perm) 9019 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9020 allowed = true; 9021 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9022 + pkg.packageName); 9023 break; 9024 } 9025 } 9026 return allowed; 9027 } 9028 9029 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9030 BasePermission bp, PermissionsState origPermissions) { 9031 boolean allowed; 9032 allowed = (compareSignatures( 9033 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9034 == PackageManager.SIGNATURE_MATCH) 9035 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9036 == PackageManager.SIGNATURE_MATCH); 9037 if (!allowed && (bp.protectionLevel 9038 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9039 if (isSystemApp(pkg)) { 9040 // For updated system applications, a system permission 9041 // is granted only if it had been defined by the original application. 9042 if (pkg.isUpdatedSystemApp()) { 9043 final PackageSetting sysPs = mSettings 9044 .getDisabledSystemPkgLPr(pkg.packageName); 9045 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9046 // If the original was granted this permission, we take 9047 // that grant decision as read and propagate it to the 9048 // update. 9049 if (sysPs.isPrivileged()) { 9050 allowed = true; 9051 } 9052 } else { 9053 // The system apk may have been updated with an older 9054 // version of the one on the data partition, but which 9055 // granted a new system permission that it didn't have 9056 // before. In this case we do want to allow the app to 9057 // now get the new permission if the ancestral apk is 9058 // privileged to get it. 9059 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9060 for (int j=0; 9061 j<sysPs.pkg.requestedPermissions.size(); j++) { 9062 if (perm.equals( 9063 sysPs.pkg.requestedPermissions.get(j))) { 9064 allowed = true; 9065 break; 9066 } 9067 } 9068 } 9069 } 9070 } else { 9071 allowed = isPrivilegedApp(pkg); 9072 } 9073 } 9074 } 9075 if (!allowed) { 9076 if (!allowed && (bp.protectionLevel 9077 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9078 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9079 // If this was a previously normal/dangerous permission that got moved 9080 // to a system permission as part of the runtime permission redesign, then 9081 // we still want to blindly grant it to old apps. 9082 allowed = true; 9083 } 9084 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9085 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9086 // If this permission is to be granted to the system installer and 9087 // this app is an installer, then it gets the permission. 9088 allowed = true; 9089 } 9090 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9091 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9092 // If this permission is to be granted to the system verifier and 9093 // this app is a verifier, then it gets the permission. 9094 allowed = true; 9095 } 9096 if (!allowed && (bp.protectionLevel 9097 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9098 && isSystemApp(pkg)) { 9099 // Any pre-installed system app is allowed to get this permission. 9100 allowed = true; 9101 } 9102 if (!allowed && (bp.protectionLevel 9103 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9104 // For development permissions, a development permission 9105 // is granted only if it was already granted. 9106 allowed = origPermissions.hasInstallPermission(perm); 9107 } 9108 } 9109 return allowed; 9110 } 9111 9112 final class ActivityIntentResolver 9113 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9114 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9115 boolean defaultOnly, int userId) { 9116 if (!sUserManager.exists(userId)) return null; 9117 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9118 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9119 } 9120 9121 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9122 int userId) { 9123 if (!sUserManager.exists(userId)) return null; 9124 mFlags = flags; 9125 return super.queryIntent(intent, resolvedType, 9126 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9127 } 9128 9129 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9130 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9131 if (!sUserManager.exists(userId)) return null; 9132 if (packageActivities == null) { 9133 return null; 9134 } 9135 mFlags = flags; 9136 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9137 final int N = packageActivities.size(); 9138 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9139 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9140 9141 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9142 for (int i = 0; i < N; ++i) { 9143 intentFilters = packageActivities.get(i).intents; 9144 if (intentFilters != null && intentFilters.size() > 0) { 9145 PackageParser.ActivityIntentInfo[] array = 9146 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9147 intentFilters.toArray(array); 9148 listCut.add(array); 9149 } 9150 } 9151 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9152 } 9153 9154 public final void addActivity(PackageParser.Activity a, String type) { 9155 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9156 mActivities.put(a.getComponentName(), a); 9157 if (DEBUG_SHOW_INFO) 9158 Log.v( 9159 TAG, " " + type + " " + 9160 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9161 if (DEBUG_SHOW_INFO) 9162 Log.v(TAG, " Class=" + a.info.name); 9163 final int NI = a.intents.size(); 9164 for (int j=0; j<NI; j++) { 9165 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9166 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9167 intent.setPriority(0); 9168 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9169 + a.className + " with priority > 0, forcing to 0"); 9170 } 9171 if (DEBUG_SHOW_INFO) { 9172 Log.v(TAG, " IntentFilter:"); 9173 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9174 } 9175 if (!intent.debugCheck()) { 9176 Log.w(TAG, "==> For Activity " + a.info.name); 9177 } 9178 addFilter(intent); 9179 } 9180 } 9181 9182 public final void removeActivity(PackageParser.Activity a, String type) { 9183 mActivities.remove(a.getComponentName()); 9184 if (DEBUG_SHOW_INFO) { 9185 Log.v(TAG, " " + type + " " 9186 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9187 : a.info.name) + ":"); 9188 Log.v(TAG, " Class=" + a.info.name); 9189 } 9190 final int NI = a.intents.size(); 9191 for (int j=0; j<NI; j++) { 9192 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9193 if (DEBUG_SHOW_INFO) { 9194 Log.v(TAG, " IntentFilter:"); 9195 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9196 } 9197 removeFilter(intent); 9198 } 9199 } 9200 9201 @Override 9202 protected boolean allowFilterResult( 9203 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9204 ActivityInfo filterAi = filter.activity.info; 9205 for (int i=dest.size()-1; i>=0; i--) { 9206 ActivityInfo destAi = dest.get(i).activityInfo; 9207 if (destAi.name == filterAi.name 9208 && destAi.packageName == filterAi.packageName) { 9209 return false; 9210 } 9211 } 9212 return true; 9213 } 9214 9215 @Override 9216 protected ActivityIntentInfo[] newArray(int size) { 9217 return new ActivityIntentInfo[size]; 9218 } 9219 9220 @Override 9221 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9222 if (!sUserManager.exists(userId)) return true; 9223 PackageParser.Package p = filter.activity.owner; 9224 if (p != null) { 9225 PackageSetting ps = (PackageSetting)p.mExtras; 9226 if (ps != null) { 9227 // System apps are never considered stopped for purposes of 9228 // filtering, because there may be no way for the user to 9229 // actually re-launch them. 9230 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9231 && ps.getStopped(userId); 9232 } 9233 } 9234 return false; 9235 } 9236 9237 @Override 9238 protected boolean isPackageForFilter(String packageName, 9239 PackageParser.ActivityIntentInfo info) { 9240 return packageName.equals(info.activity.owner.packageName); 9241 } 9242 9243 @Override 9244 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9245 int match, int userId) { 9246 if (!sUserManager.exists(userId)) return null; 9247 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9248 return null; 9249 } 9250 final PackageParser.Activity activity = info.activity; 9251 if (mSafeMode && (activity.info.applicationInfo.flags 9252 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9253 return null; 9254 } 9255 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9256 if (ps == null) { 9257 return null; 9258 } 9259 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9260 ps.readUserState(userId), userId); 9261 if (ai == null) { 9262 return null; 9263 } 9264 final ResolveInfo res = new ResolveInfo(); 9265 res.activityInfo = ai; 9266 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9267 res.filter = info; 9268 } 9269 if (info != null) { 9270 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9271 } 9272 res.priority = info.getPriority(); 9273 res.preferredOrder = activity.owner.mPreferredOrder; 9274 //System.out.println("Result: " + res.activityInfo.className + 9275 // " = " + res.priority); 9276 res.match = match; 9277 res.isDefault = info.hasDefault; 9278 res.labelRes = info.labelRes; 9279 res.nonLocalizedLabel = info.nonLocalizedLabel; 9280 if (userNeedsBadging(userId)) { 9281 res.noResourceId = true; 9282 } else { 9283 res.icon = info.icon; 9284 } 9285 res.iconResourceId = info.icon; 9286 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9287 return res; 9288 } 9289 9290 @Override 9291 protected void sortResults(List<ResolveInfo> results) { 9292 Collections.sort(results, mResolvePrioritySorter); 9293 } 9294 9295 @Override 9296 protected void dumpFilter(PrintWriter out, String prefix, 9297 PackageParser.ActivityIntentInfo filter) { 9298 out.print(prefix); out.print( 9299 Integer.toHexString(System.identityHashCode(filter.activity))); 9300 out.print(' '); 9301 filter.activity.printComponentShortName(out); 9302 out.print(" filter "); 9303 out.println(Integer.toHexString(System.identityHashCode(filter))); 9304 } 9305 9306 @Override 9307 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9308 return filter.activity; 9309 } 9310 9311 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9312 PackageParser.Activity activity = (PackageParser.Activity)label; 9313 out.print(prefix); out.print( 9314 Integer.toHexString(System.identityHashCode(activity))); 9315 out.print(' '); 9316 activity.printComponentShortName(out); 9317 if (count > 1) { 9318 out.print(" ("); out.print(count); out.print(" filters)"); 9319 } 9320 out.println(); 9321 } 9322 9323// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9324// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9325// final List<ResolveInfo> retList = Lists.newArrayList(); 9326// while (i.hasNext()) { 9327// final ResolveInfo resolveInfo = i.next(); 9328// if (isEnabledLP(resolveInfo.activityInfo)) { 9329// retList.add(resolveInfo); 9330// } 9331// } 9332// return retList; 9333// } 9334 9335 // Keys are String (activity class name), values are Activity. 9336 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9337 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9338 private int mFlags; 9339 } 9340 9341 private final class ServiceIntentResolver 9342 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9343 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9344 boolean defaultOnly, int userId) { 9345 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9346 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9347 } 9348 9349 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9350 int userId) { 9351 if (!sUserManager.exists(userId)) return null; 9352 mFlags = flags; 9353 return super.queryIntent(intent, resolvedType, 9354 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9355 } 9356 9357 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9358 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9359 if (!sUserManager.exists(userId)) return null; 9360 if (packageServices == null) { 9361 return null; 9362 } 9363 mFlags = flags; 9364 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9365 final int N = packageServices.size(); 9366 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9367 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9368 9369 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9370 for (int i = 0; i < N; ++i) { 9371 intentFilters = packageServices.get(i).intents; 9372 if (intentFilters != null && intentFilters.size() > 0) { 9373 PackageParser.ServiceIntentInfo[] array = 9374 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9375 intentFilters.toArray(array); 9376 listCut.add(array); 9377 } 9378 } 9379 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9380 } 9381 9382 public final void addService(PackageParser.Service s) { 9383 mServices.put(s.getComponentName(), s); 9384 if (DEBUG_SHOW_INFO) { 9385 Log.v(TAG, " " 9386 + (s.info.nonLocalizedLabel != null 9387 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9388 Log.v(TAG, " Class=" + s.info.name); 9389 } 9390 final int NI = s.intents.size(); 9391 int j; 9392 for (j=0; j<NI; j++) { 9393 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9394 if (DEBUG_SHOW_INFO) { 9395 Log.v(TAG, " IntentFilter:"); 9396 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9397 } 9398 if (!intent.debugCheck()) { 9399 Log.w(TAG, "==> For Service " + s.info.name); 9400 } 9401 addFilter(intent); 9402 } 9403 } 9404 9405 public final void removeService(PackageParser.Service s) { 9406 mServices.remove(s.getComponentName()); 9407 if (DEBUG_SHOW_INFO) { 9408 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9409 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9410 Log.v(TAG, " Class=" + s.info.name); 9411 } 9412 final int NI = s.intents.size(); 9413 int j; 9414 for (j=0; j<NI; j++) { 9415 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9416 if (DEBUG_SHOW_INFO) { 9417 Log.v(TAG, " IntentFilter:"); 9418 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9419 } 9420 removeFilter(intent); 9421 } 9422 } 9423 9424 @Override 9425 protected boolean allowFilterResult( 9426 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9427 ServiceInfo filterSi = filter.service.info; 9428 for (int i=dest.size()-1; i>=0; i--) { 9429 ServiceInfo destAi = dest.get(i).serviceInfo; 9430 if (destAi.name == filterSi.name 9431 && destAi.packageName == filterSi.packageName) { 9432 return false; 9433 } 9434 } 9435 return true; 9436 } 9437 9438 @Override 9439 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9440 return new PackageParser.ServiceIntentInfo[size]; 9441 } 9442 9443 @Override 9444 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9445 if (!sUserManager.exists(userId)) return true; 9446 PackageParser.Package p = filter.service.owner; 9447 if (p != null) { 9448 PackageSetting ps = (PackageSetting)p.mExtras; 9449 if (ps != null) { 9450 // System apps are never considered stopped for purposes of 9451 // filtering, because there may be no way for the user to 9452 // actually re-launch them. 9453 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9454 && ps.getStopped(userId); 9455 } 9456 } 9457 return false; 9458 } 9459 9460 @Override 9461 protected boolean isPackageForFilter(String packageName, 9462 PackageParser.ServiceIntentInfo info) { 9463 return packageName.equals(info.service.owner.packageName); 9464 } 9465 9466 @Override 9467 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9468 int match, int userId) { 9469 if (!sUserManager.exists(userId)) return null; 9470 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9471 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9472 return null; 9473 } 9474 final PackageParser.Service service = info.service; 9475 if (mSafeMode && (service.info.applicationInfo.flags 9476 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9477 return null; 9478 } 9479 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9480 if (ps == null) { 9481 return null; 9482 } 9483 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9484 ps.readUserState(userId), userId); 9485 if (si == null) { 9486 return null; 9487 } 9488 final ResolveInfo res = new ResolveInfo(); 9489 res.serviceInfo = si; 9490 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9491 res.filter = filter; 9492 } 9493 res.priority = info.getPriority(); 9494 res.preferredOrder = service.owner.mPreferredOrder; 9495 res.match = match; 9496 res.isDefault = info.hasDefault; 9497 res.labelRes = info.labelRes; 9498 res.nonLocalizedLabel = info.nonLocalizedLabel; 9499 res.icon = info.icon; 9500 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9501 return res; 9502 } 9503 9504 @Override 9505 protected void sortResults(List<ResolveInfo> results) { 9506 Collections.sort(results, mResolvePrioritySorter); 9507 } 9508 9509 @Override 9510 protected void dumpFilter(PrintWriter out, String prefix, 9511 PackageParser.ServiceIntentInfo filter) { 9512 out.print(prefix); out.print( 9513 Integer.toHexString(System.identityHashCode(filter.service))); 9514 out.print(' '); 9515 filter.service.printComponentShortName(out); 9516 out.print(" filter "); 9517 out.println(Integer.toHexString(System.identityHashCode(filter))); 9518 } 9519 9520 @Override 9521 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9522 return filter.service; 9523 } 9524 9525 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9526 PackageParser.Service service = (PackageParser.Service)label; 9527 out.print(prefix); out.print( 9528 Integer.toHexString(System.identityHashCode(service))); 9529 out.print(' '); 9530 service.printComponentShortName(out); 9531 if (count > 1) { 9532 out.print(" ("); out.print(count); out.print(" filters)"); 9533 } 9534 out.println(); 9535 } 9536 9537// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9538// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9539// final List<ResolveInfo> retList = Lists.newArrayList(); 9540// while (i.hasNext()) { 9541// final ResolveInfo resolveInfo = (ResolveInfo) i; 9542// if (isEnabledLP(resolveInfo.serviceInfo)) { 9543// retList.add(resolveInfo); 9544// } 9545// } 9546// return retList; 9547// } 9548 9549 // Keys are String (activity class name), values are Activity. 9550 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9551 = new ArrayMap<ComponentName, PackageParser.Service>(); 9552 private int mFlags; 9553 }; 9554 9555 private final class ProviderIntentResolver 9556 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9557 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9558 boolean defaultOnly, int userId) { 9559 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9560 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9561 } 9562 9563 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9564 int userId) { 9565 if (!sUserManager.exists(userId)) 9566 return null; 9567 mFlags = flags; 9568 return super.queryIntent(intent, resolvedType, 9569 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9570 } 9571 9572 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9573 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9574 if (!sUserManager.exists(userId)) 9575 return null; 9576 if (packageProviders == null) { 9577 return null; 9578 } 9579 mFlags = flags; 9580 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9581 final int N = packageProviders.size(); 9582 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9583 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9584 9585 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9586 for (int i = 0; i < N; ++i) { 9587 intentFilters = packageProviders.get(i).intents; 9588 if (intentFilters != null && intentFilters.size() > 0) { 9589 PackageParser.ProviderIntentInfo[] array = 9590 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9591 intentFilters.toArray(array); 9592 listCut.add(array); 9593 } 9594 } 9595 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9596 } 9597 9598 public final void addProvider(PackageParser.Provider p) { 9599 if (mProviders.containsKey(p.getComponentName())) { 9600 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9601 return; 9602 } 9603 9604 mProviders.put(p.getComponentName(), p); 9605 if (DEBUG_SHOW_INFO) { 9606 Log.v(TAG, " " 9607 + (p.info.nonLocalizedLabel != null 9608 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9609 Log.v(TAG, " Class=" + p.info.name); 9610 } 9611 final int NI = p.intents.size(); 9612 int j; 9613 for (j = 0; j < NI; j++) { 9614 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9615 if (DEBUG_SHOW_INFO) { 9616 Log.v(TAG, " IntentFilter:"); 9617 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9618 } 9619 if (!intent.debugCheck()) { 9620 Log.w(TAG, "==> For Provider " + p.info.name); 9621 } 9622 addFilter(intent); 9623 } 9624 } 9625 9626 public final void removeProvider(PackageParser.Provider p) { 9627 mProviders.remove(p.getComponentName()); 9628 if (DEBUG_SHOW_INFO) { 9629 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9630 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9631 Log.v(TAG, " Class=" + p.info.name); 9632 } 9633 final int NI = p.intents.size(); 9634 int j; 9635 for (j = 0; j < NI; j++) { 9636 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9637 if (DEBUG_SHOW_INFO) { 9638 Log.v(TAG, " IntentFilter:"); 9639 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9640 } 9641 removeFilter(intent); 9642 } 9643 } 9644 9645 @Override 9646 protected boolean allowFilterResult( 9647 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9648 ProviderInfo filterPi = filter.provider.info; 9649 for (int i = dest.size() - 1; i >= 0; i--) { 9650 ProviderInfo destPi = dest.get(i).providerInfo; 9651 if (destPi.name == filterPi.name 9652 && destPi.packageName == filterPi.packageName) { 9653 return false; 9654 } 9655 } 9656 return true; 9657 } 9658 9659 @Override 9660 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9661 return new PackageParser.ProviderIntentInfo[size]; 9662 } 9663 9664 @Override 9665 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9666 if (!sUserManager.exists(userId)) 9667 return true; 9668 PackageParser.Package p = filter.provider.owner; 9669 if (p != null) { 9670 PackageSetting ps = (PackageSetting) p.mExtras; 9671 if (ps != null) { 9672 // System apps are never considered stopped for purposes of 9673 // filtering, because there may be no way for the user to 9674 // actually re-launch them. 9675 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9676 && ps.getStopped(userId); 9677 } 9678 } 9679 return false; 9680 } 9681 9682 @Override 9683 protected boolean isPackageForFilter(String packageName, 9684 PackageParser.ProviderIntentInfo info) { 9685 return packageName.equals(info.provider.owner.packageName); 9686 } 9687 9688 @Override 9689 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9690 int match, int userId) { 9691 if (!sUserManager.exists(userId)) 9692 return null; 9693 final PackageParser.ProviderIntentInfo info = filter; 9694 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9695 return null; 9696 } 9697 final PackageParser.Provider provider = info.provider; 9698 if (mSafeMode && (provider.info.applicationInfo.flags 9699 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9700 return null; 9701 } 9702 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9703 if (ps == null) { 9704 return null; 9705 } 9706 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9707 ps.readUserState(userId), userId); 9708 if (pi == null) { 9709 return null; 9710 } 9711 final ResolveInfo res = new ResolveInfo(); 9712 res.providerInfo = pi; 9713 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9714 res.filter = filter; 9715 } 9716 res.priority = info.getPriority(); 9717 res.preferredOrder = provider.owner.mPreferredOrder; 9718 res.match = match; 9719 res.isDefault = info.hasDefault; 9720 res.labelRes = info.labelRes; 9721 res.nonLocalizedLabel = info.nonLocalizedLabel; 9722 res.icon = info.icon; 9723 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9724 return res; 9725 } 9726 9727 @Override 9728 protected void sortResults(List<ResolveInfo> results) { 9729 Collections.sort(results, mResolvePrioritySorter); 9730 } 9731 9732 @Override 9733 protected void dumpFilter(PrintWriter out, String prefix, 9734 PackageParser.ProviderIntentInfo filter) { 9735 out.print(prefix); 9736 out.print( 9737 Integer.toHexString(System.identityHashCode(filter.provider))); 9738 out.print(' '); 9739 filter.provider.printComponentShortName(out); 9740 out.print(" filter "); 9741 out.println(Integer.toHexString(System.identityHashCode(filter))); 9742 } 9743 9744 @Override 9745 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9746 return filter.provider; 9747 } 9748 9749 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9750 PackageParser.Provider provider = (PackageParser.Provider)label; 9751 out.print(prefix); out.print( 9752 Integer.toHexString(System.identityHashCode(provider))); 9753 out.print(' '); 9754 provider.printComponentShortName(out); 9755 if (count > 1) { 9756 out.print(" ("); out.print(count); out.print(" filters)"); 9757 } 9758 out.println(); 9759 } 9760 9761 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9762 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9763 private int mFlags; 9764 } 9765 9766 private static final class EphemeralIntentResolver 9767 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9768 @Override 9769 protected EphemeralResolveIntentInfo[] newArray(int size) { 9770 return new EphemeralResolveIntentInfo[size]; 9771 } 9772 9773 @Override 9774 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9775 return true; 9776 } 9777 9778 @Override 9779 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9780 int userId) { 9781 if (!sUserManager.exists(userId)) { 9782 return null; 9783 } 9784 return info.getEphemeralResolveInfo(); 9785 } 9786 } 9787 9788 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9789 new Comparator<ResolveInfo>() { 9790 public int compare(ResolveInfo r1, ResolveInfo r2) { 9791 int v1 = r1.priority; 9792 int v2 = r2.priority; 9793 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9794 if (v1 != v2) { 9795 return (v1 > v2) ? -1 : 1; 9796 } 9797 v1 = r1.preferredOrder; 9798 v2 = r2.preferredOrder; 9799 if (v1 != v2) { 9800 return (v1 > v2) ? -1 : 1; 9801 } 9802 if (r1.isDefault != r2.isDefault) { 9803 return r1.isDefault ? -1 : 1; 9804 } 9805 v1 = r1.match; 9806 v2 = r2.match; 9807 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9808 if (v1 != v2) { 9809 return (v1 > v2) ? -1 : 1; 9810 } 9811 if (r1.system != r2.system) { 9812 return r1.system ? -1 : 1; 9813 } 9814 if (r1.activityInfo != null) { 9815 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9816 } 9817 if (r1.serviceInfo != null) { 9818 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9819 } 9820 if (r1.providerInfo != null) { 9821 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9822 } 9823 return 0; 9824 } 9825 }; 9826 9827 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9828 new Comparator<ProviderInfo>() { 9829 public int compare(ProviderInfo p1, ProviderInfo p2) { 9830 final int v1 = p1.initOrder; 9831 final int v2 = p2.initOrder; 9832 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9833 } 9834 }; 9835 9836 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9837 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9838 final int[] userIds) { 9839 mHandler.post(new Runnable() { 9840 @Override 9841 public void run() { 9842 try { 9843 final IActivityManager am = ActivityManagerNative.getDefault(); 9844 if (am == null) return; 9845 final int[] resolvedUserIds; 9846 if (userIds == null) { 9847 resolvedUserIds = am.getRunningUserIds(); 9848 } else { 9849 resolvedUserIds = userIds; 9850 } 9851 for (int id : resolvedUserIds) { 9852 final Intent intent = new Intent(action, 9853 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9854 if (extras != null) { 9855 intent.putExtras(extras); 9856 } 9857 if (targetPkg != null) { 9858 intent.setPackage(targetPkg); 9859 } 9860 // Modify the UID when posting to other users 9861 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9862 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9863 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9864 intent.putExtra(Intent.EXTRA_UID, uid); 9865 } 9866 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9867 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9868 if (DEBUG_BROADCASTS) { 9869 RuntimeException here = new RuntimeException("here"); 9870 here.fillInStackTrace(); 9871 Slog.d(TAG, "Sending to user " + id + ": " 9872 + intent.toShortString(false, true, false, false) 9873 + " " + intent.getExtras(), here); 9874 } 9875 am.broadcastIntent(null, intent, null, finishedReceiver, 9876 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9877 null, finishedReceiver != null, false, id); 9878 } 9879 } catch (RemoteException ex) { 9880 } 9881 } 9882 }); 9883 } 9884 9885 /** 9886 * Check if the external storage media is available. This is true if there 9887 * is a mounted external storage medium or if the external storage is 9888 * emulated. 9889 */ 9890 private boolean isExternalMediaAvailable() { 9891 return mMediaMounted || Environment.isExternalStorageEmulated(); 9892 } 9893 9894 @Override 9895 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9896 // writer 9897 synchronized (mPackages) { 9898 if (!isExternalMediaAvailable()) { 9899 // If the external storage is no longer mounted at this point, 9900 // the caller may not have been able to delete all of this 9901 // packages files and can not delete any more. Bail. 9902 return null; 9903 } 9904 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9905 if (lastPackage != null) { 9906 pkgs.remove(lastPackage); 9907 } 9908 if (pkgs.size() > 0) { 9909 return pkgs.get(0); 9910 } 9911 } 9912 return null; 9913 } 9914 9915 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9916 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9917 userId, andCode ? 1 : 0, packageName); 9918 if (mSystemReady) { 9919 msg.sendToTarget(); 9920 } else { 9921 if (mPostSystemReadyMessages == null) { 9922 mPostSystemReadyMessages = new ArrayList<>(); 9923 } 9924 mPostSystemReadyMessages.add(msg); 9925 } 9926 } 9927 9928 void startCleaningPackages() { 9929 // reader 9930 synchronized (mPackages) { 9931 if (!isExternalMediaAvailable()) { 9932 return; 9933 } 9934 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9935 return; 9936 } 9937 } 9938 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9939 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9940 IActivityManager am = ActivityManagerNative.getDefault(); 9941 if (am != null) { 9942 try { 9943 am.startService(null, intent, null, mContext.getOpPackageName(), 9944 UserHandle.USER_SYSTEM); 9945 } catch (RemoteException e) { 9946 } 9947 } 9948 } 9949 9950 @Override 9951 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9952 int installFlags, String installerPackageName, VerificationParams verificationParams, 9953 String packageAbiOverride) { 9954 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9955 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9956 } 9957 9958 @Override 9959 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9960 int installFlags, String installerPackageName, VerificationParams verificationParams, 9961 String packageAbiOverride, int userId) { 9962 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9963 9964 final int callingUid = Binder.getCallingUid(); 9965 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9966 9967 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9968 try { 9969 if (observer != null) { 9970 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9971 } 9972 } catch (RemoteException re) { 9973 } 9974 return; 9975 } 9976 9977 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9978 installFlags |= PackageManager.INSTALL_FROM_ADB; 9979 9980 } else { 9981 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9982 // about installerPackageName. 9983 9984 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9985 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9986 } 9987 9988 UserHandle user; 9989 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9990 user = UserHandle.ALL; 9991 } else { 9992 user = new UserHandle(userId); 9993 } 9994 9995 // Only system components can circumvent runtime permissions when installing. 9996 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9997 && mContext.checkCallingOrSelfPermission(Manifest.permission 9998 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9999 throw new SecurityException("You need the " 10000 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10001 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10002 } 10003 10004 verificationParams.setInstallerUid(callingUid); 10005 10006 final File originFile = new File(originPath); 10007 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10008 10009 final Message msg = mHandler.obtainMessage(INIT_COPY); 10010 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10011 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10012 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10013 msg.obj = params; 10014 10015 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10016 System.identityHashCode(msg.obj)); 10017 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10018 System.identityHashCode(msg.obj)); 10019 10020 mHandler.sendMessage(msg); 10021 } 10022 10023 void installStage(String packageName, File stagedDir, String stagedCid, 10024 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10025 String installerPackageName, int installerUid, UserHandle user) { 10026 if (DEBUG_EPHEMERAL) { 10027 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10028 Slog.d(TAG, "Ephemeral install of " + packageName); 10029 } 10030 } 10031 final VerificationParams verifParams = new VerificationParams( 10032 null, sessionParams.originatingUri, sessionParams.referrerUri, 10033 sessionParams.originatingUid); 10034 verifParams.setInstallerUid(installerUid); 10035 10036 final OriginInfo origin; 10037 if (stagedDir != null) { 10038 origin = OriginInfo.fromStagedFile(stagedDir); 10039 } else { 10040 origin = OriginInfo.fromStagedContainer(stagedCid); 10041 } 10042 10043 final Message msg = mHandler.obtainMessage(INIT_COPY); 10044 final InstallParams params = new InstallParams(origin, null, observer, 10045 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10046 verifParams, user, sessionParams.abiOverride, 10047 sessionParams.grantedRuntimePermissions); 10048 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10049 msg.obj = params; 10050 10051 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10052 System.identityHashCode(msg.obj)); 10053 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10054 System.identityHashCode(msg.obj)); 10055 10056 mHandler.sendMessage(msg); 10057 } 10058 10059 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10060 Bundle extras = new Bundle(1); 10061 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10062 10063 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10064 packageName, extras, 0, null, null, new int[] {userId}); 10065 try { 10066 IActivityManager am = ActivityManagerNative.getDefault(); 10067 final boolean isSystem = 10068 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10069 if (isSystem && am.isUserRunning(userId, 0)) { 10070 // The just-installed/enabled app is bundled on the system, so presumed 10071 // to be able to run automatically without needing an explicit launch. 10072 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10073 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10074 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10075 .setPackage(packageName); 10076 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10077 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10078 } 10079 } catch (RemoteException e) { 10080 // shouldn't happen 10081 Slog.w(TAG, "Unable to bootstrap installed package", e); 10082 } 10083 } 10084 10085 @Override 10086 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10087 int userId) { 10088 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10089 PackageSetting pkgSetting; 10090 final int uid = Binder.getCallingUid(); 10091 enforceCrossUserPermission(uid, userId, true, true, 10092 "setApplicationHiddenSetting for user " + userId); 10093 10094 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10095 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10096 return false; 10097 } 10098 10099 long callingId = Binder.clearCallingIdentity(); 10100 try { 10101 boolean sendAdded = false; 10102 boolean sendRemoved = false; 10103 // writer 10104 synchronized (mPackages) { 10105 pkgSetting = mSettings.mPackages.get(packageName); 10106 if (pkgSetting == null) { 10107 return false; 10108 } 10109 if (pkgSetting.getHidden(userId) != hidden) { 10110 pkgSetting.setHidden(hidden, userId); 10111 mSettings.writePackageRestrictionsLPr(userId); 10112 if (hidden) { 10113 sendRemoved = true; 10114 } else { 10115 sendAdded = true; 10116 } 10117 } 10118 } 10119 if (sendAdded) { 10120 sendPackageAddedForUser(packageName, pkgSetting, userId); 10121 return true; 10122 } 10123 if (sendRemoved) { 10124 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10125 "hiding pkg"); 10126 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10127 return true; 10128 } 10129 } finally { 10130 Binder.restoreCallingIdentity(callingId); 10131 } 10132 return false; 10133 } 10134 10135 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10136 int userId) { 10137 final PackageRemovedInfo info = new PackageRemovedInfo(); 10138 info.removedPackage = packageName; 10139 info.removedUsers = new int[] {userId}; 10140 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10141 info.sendBroadcast(false, false, false); 10142 } 10143 10144 /** 10145 * Returns true if application is not found or there was an error. Otherwise it returns 10146 * the hidden state of the package for the given user. 10147 */ 10148 @Override 10149 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10150 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10151 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10152 false, "getApplicationHidden for user " + userId); 10153 PackageSetting pkgSetting; 10154 long callingId = Binder.clearCallingIdentity(); 10155 try { 10156 // writer 10157 synchronized (mPackages) { 10158 pkgSetting = mSettings.mPackages.get(packageName); 10159 if (pkgSetting == null) { 10160 return true; 10161 } 10162 return pkgSetting.getHidden(userId); 10163 } 10164 } finally { 10165 Binder.restoreCallingIdentity(callingId); 10166 } 10167 } 10168 10169 /** 10170 * @hide 10171 */ 10172 @Override 10173 public int installExistingPackageAsUser(String packageName, int userId) { 10174 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10175 null); 10176 PackageSetting pkgSetting; 10177 final int uid = Binder.getCallingUid(); 10178 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10179 + userId); 10180 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10181 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10182 } 10183 10184 long callingId = Binder.clearCallingIdentity(); 10185 try { 10186 boolean sendAdded = false; 10187 10188 // writer 10189 synchronized (mPackages) { 10190 pkgSetting = mSettings.mPackages.get(packageName); 10191 if (pkgSetting == null) { 10192 return PackageManager.INSTALL_FAILED_INVALID_URI; 10193 } 10194 if (!pkgSetting.getInstalled(userId)) { 10195 pkgSetting.setInstalled(true, userId); 10196 pkgSetting.setHidden(false, userId); 10197 mSettings.writePackageRestrictionsLPr(userId); 10198 sendAdded = true; 10199 } 10200 } 10201 10202 if (sendAdded) { 10203 sendPackageAddedForUser(packageName, pkgSetting, userId); 10204 } 10205 } finally { 10206 Binder.restoreCallingIdentity(callingId); 10207 } 10208 10209 return PackageManager.INSTALL_SUCCEEDED; 10210 } 10211 10212 boolean isUserRestricted(int userId, String restrictionKey) { 10213 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10214 if (restrictions.getBoolean(restrictionKey, false)) { 10215 Log.w(TAG, "User is restricted: " + restrictionKey); 10216 return true; 10217 } 10218 return false; 10219 } 10220 10221 @Override 10222 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10223 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10224 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10225 "setPackageSuspended for user " + userId); 10226 10227 long callingId = Binder.clearCallingIdentity(); 10228 try { 10229 synchronized (mPackages) { 10230 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10231 if (pkgSetting != null) { 10232 if (pkgSetting.getSuspended(userId) != suspended) { 10233 pkgSetting.setSuspended(suspended, userId); 10234 mSettings.writePackageRestrictionsLPr(userId); 10235 } 10236 10237 // TODO: 10238 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10239 // * remove app from recents (kill app it if it is running) 10240 // * erase existing notifications for this app 10241 return true; 10242 } 10243 10244 return false; 10245 } 10246 } finally { 10247 Binder.restoreCallingIdentity(callingId); 10248 } 10249 } 10250 10251 @Override 10252 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10253 mContext.enforceCallingOrSelfPermission( 10254 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10255 "Only package verification agents can verify applications"); 10256 10257 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10258 final PackageVerificationResponse response = new PackageVerificationResponse( 10259 verificationCode, Binder.getCallingUid()); 10260 msg.arg1 = id; 10261 msg.obj = response; 10262 mHandler.sendMessage(msg); 10263 } 10264 10265 @Override 10266 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10267 long millisecondsToDelay) { 10268 mContext.enforceCallingOrSelfPermission( 10269 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10270 "Only package verification agents can extend verification timeouts"); 10271 10272 final PackageVerificationState state = mPendingVerification.get(id); 10273 final PackageVerificationResponse response = new PackageVerificationResponse( 10274 verificationCodeAtTimeout, Binder.getCallingUid()); 10275 10276 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10277 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10278 } 10279 if (millisecondsToDelay < 0) { 10280 millisecondsToDelay = 0; 10281 } 10282 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10283 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10284 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10285 } 10286 10287 if ((state != null) && !state.timeoutExtended()) { 10288 state.extendTimeout(); 10289 10290 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10291 msg.arg1 = id; 10292 msg.obj = response; 10293 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10294 } 10295 } 10296 10297 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10298 int verificationCode, UserHandle user) { 10299 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10300 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10301 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10302 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10303 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10304 10305 mContext.sendBroadcastAsUser(intent, user, 10306 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10307 } 10308 10309 private ComponentName matchComponentForVerifier(String packageName, 10310 List<ResolveInfo> receivers) { 10311 ActivityInfo targetReceiver = null; 10312 10313 final int NR = receivers.size(); 10314 for (int i = 0; i < NR; i++) { 10315 final ResolveInfo info = receivers.get(i); 10316 if (info.activityInfo == null) { 10317 continue; 10318 } 10319 10320 if (packageName.equals(info.activityInfo.packageName)) { 10321 targetReceiver = info.activityInfo; 10322 break; 10323 } 10324 } 10325 10326 if (targetReceiver == null) { 10327 return null; 10328 } 10329 10330 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10331 } 10332 10333 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10334 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10335 if (pkgInfo.verifiers.length == 0) { 10336 return null; 10337 } 10338 10339 final int N = pkgInfo.verifiers.length; 10340 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10341 for (int i = 0; i < N; i++) { 10342 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10343 10344 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10345 receivers); 10346 if (comp == null) { 10347 continue; 10348 } 10349 10350 final int verifierUid = getUidForVerifier(verifierInfo); 10351 if (verifierUid == -1) { 10352 continue; 10353 } 10354 10355 if (DEBUG_VERIFY) { 10356 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10357 + " with the correct signature"); 10358 } 10359 sufficientVerifiers.add(comp); 10360 verificationState.addSufficientVerifier(verifierUid); 10361 } 10362 10363 return sufficientVerifiers; 10364 } 10365 10366 private int getUidForVerifier(VerifierInfo verifierInfo) { 10367 synchronized (mPackages) { 10368 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10369 if (pkg == null) { 10370 return -1; 10371 } else if (pkg.mSignatures.length != 1) { 10372 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10373 + " has more than one signature; ignoring"); 10374 return -1; 10375 } 10376 10377 /* 10378 * If the public key of the package's signature does not match 10379 * our expected public key, then this is a different package and 10380 * we should skip. 10381 */ 10382 10383 final byte[] expectedPublicKey; 10384 try { 10385 final Signature verifierSig = pkg.mSignatures[0]; 10386 final PublicKey publicKey = verifierSig.getPublicKey(); 10387 expectedPublicKey = publicKey.getEncoded(); 10388 } catch (CertificateException e) { 10389 return -1; 10390 } 10391 10392 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10393 10394 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10395 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10396 + " does not have the expected public key; ignoring"); 10397 return -1; 10398 } 10399 10400 return pkg.applicationInfo.uid; 10401 } 10402 } 10403 10404 @Override 10405 public void finishPackageInstall(int token) { 10406 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10407 10408 if (DEBUG_INSTALL) { 10409 Slog.v(TAG, "BM finishing package install for " + token); 10410 } 10411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10412 10413 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10414 mHandler.sendMessage(msg); 10415 } 10416 10417 /** 10418 * Get the verification agent timeout. 10419 * 10420 * @return verification timeout in milliseconds 10421 */ 10422 private long getVerificationTimeout() { 10423 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10424 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10425 DEFAULT_VERIFICATION_TIMEOUT); 10426 } 10427 10428 /** 10429 * Get the default verification agent response code. 10430 * 10431 * @return default verification response code 10432 */ 10433 private int getDefaultVerificationResponse() { 10434 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10435 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10436 DEFAULT_VERIFICATION_RESPONSE); 10437 } 10438 10439 /** 10440 * Check whether or not package verification has been enabled. 10441 * 10442 * @return true if verification should be performed 10443 */ 10444 private boolean isVerificationEnabled(int userId, int installFlags) { 10445 if (!DEFAULT_VERIFY_ENABLE) { 10446 return false; 10447 } 10448 // Ephemeral apps don't get the full verification treatment 10449 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10450 if (DEBUG_EPHEMERAL) { 10451 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10452 } 10453 return false; 10454 } 10455 10456 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10457 10458 // Check if installing from ADB 10459 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10460 // Do not run verification in a test harness environment 10461 if (ActivityManager.isRunningInTestHarness()) { 10462 return false; 10463 } 10464 if (ensureVerifyAppsEnabled) { 10465 return true; 10466 } 10467 // Check if the developer does not want package verification for ADB installs 10468 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10469 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10470 return false; 10471 } 10472 } 10473 10474 if (ensureVerifyAppsEnabled) { 10475 return true; 10476 } 10477 10478 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10479 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10480 } 10481 10482 @Override 10483 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10484 throws RemoteException { 10485 mContext.enforceCallingOrSelfPermission( 10486 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10487 "Only intentfilter verification agents can verify applications"); 10488 10489 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10490 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10491 Binder.getCallingUid(), verificationCode, failedDomains); 10492 msg.arg1 = id; 10493 msg.obj = response; 10494 mHandler.sendMessage(msg); 10495 } 10496 10497 @Override 10498 public int getIntentVerificationStatus(String packageName, int userId) { 10499 synchronized (mPackages) { 10500 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10501 } 10502 } 10503 10504 @Override 10505 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10506 mContext.enforceCallingOrSelfPermission( 10507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10508 10509 boolean result = false; 10510 synchronized (mPackages) { 10511 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10512 } 10513 if (result) { 10514 scheduleWritePackageRestrictionsLocked(userId); 10515 } 10516 return result; 10517 } 10518 10519 @Override 10520 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10521 synchronized (mPackages) { 10522 return mSettings.getIntentFilterVerificationsLPr(packageName); 10523 } 10524 } 10525 10526 @Override 10527 public List<IntentFilter> getAllIntentFilters(String packageName) { 10528 if (TextUtils.isEmpty(packageName)) { 10529 return Collections.<IntentFilter>emptyList(); 10530 } 10531 synchronized (mPackages) { 10532 PackageParser.Package pkg = mPackages.get(packageName); 10533 if (pkg == null || pkg.activities == null) { 10534 return Collections.<IntentFilter>emptyList(); 10535 } 10536 final int count = pkg.activities.size(); 10537 ArrayList<IntentFilter> result = new ArrayList<>(); 10538 for (int n=0; n<count; n++) { 10539 PackageParser.Activity activity = pkg.activities.get(n); 10540 if (activity.intents != null && activity.intents.size() > 0) { 10541 result.addAll(activity.intents); 10542 } 10543 } 10544 return result; 10545 } 10546 } 10547 10548 @Override 10549 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10550 mContext.enforceCallingOrSelfPermission( 10551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10552 10553 synchronized (mPackages) { 10554 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10555 if (packageName != null) { 10556 result |= updateIntentVerificationStatus(packageName, 10557 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10558 userId); 10559 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10560 packageName, userId); 10561 } 10562 return result; 10563 } 10564 } 10565 10566 @Override 10567 public String getDefaultBrowserPackageName(int userId) { 10568 synchronized (mPackages) { 10569 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10570 } 10571 } 10572 10573 /** 10574 * Get the "allow unknown sources" setting. 10575 * 10576 * @return the current "allow unknown sources" setting 10577 */ 10578 private int getUnknownSourcesSettings() { 10579 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10580 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10581 -1); 10582 } 10583 10584 @Override 10585 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10586 final int uid = Binder.getCallingUid(); 10587 // writer 10588 synchronized (mPackages) { 10589 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10590 if (targetPackageSetting == null) { 10591 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10592 } 10593 10594 PackageSetting installerPackageSetting; 10595 if (installerPackageName != null) { 10596 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10597 if (installerPackageSetting == null) { 10598 throw new IllegalArgumentException("Unknown installer package: " 10599 + installerPackageName); 10600 } 10601 } else { 10602 installerPackageSetting = null; 10603 } 10604 10605 Signature[] callerSignature; 10606 Object obj = mSettings.getUserIdLPr(uid); 10607 if (obj != null) { 10608 if (obj instanceof SharedUserSetting) { 10609 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10610 } else if (obj instanceof PackageSetting) { 10611 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10612 } else { 10613 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10614 } 10615 } else { 10616 throw new SecurityException("Unknown calling UID: " + uid); 10617 } 10618 10619 // Verify: can't set installerPackageName to a package that is 10620 // not signed with the same cert as the caller. 10621 if (installerPackageSetting != null) { 10622 if (compareSignatures(callerSignature, 10623 installerPackageSetting.signatures.mSignatures) 10624 != PackageManager.SIGNATURE_MATCH) { 10625 throw new SecurityException( 10626 "Caller does not have same cert as new installer package " 10627 + installerPackageName); 10628 } 10629 } 10630 10631 // Verify: if target already has an installer package, it must 10632 // be signed with the same cert as the caller. 10633 if (targetPackageSetting.installerPackageName != null) { 10634 PackageSetting setting = mSettings.mPackages.get( 10635 targetPackageSetting.installerPackageName); 10636 // If the currently set package isn't valid, then it's always 10637 // okay to change it. 10638 if (setting != null) { 10639 if (compareSignatures(callerSignature, 10640 setting.signatures.mSignatures) 10641 != PackageManager.SIGNATURE_MATCH) { 10642 throw new SecurityException( 10643 "Caller does not have same cert as old installer package " 10644 + targetPackageSetting.installerPackageName); 10645 } 10646 } 10647 } 10648 10649 // Okay! 10650 targetPackageSetting.installerPackageName = installerPackageName; 10651 scheduleWriteSettingsLocked(); 10652 } 10653 } 10654 10655 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10656 // Queue up an async operation since the package installation may take a little while. 10657 mHandler.post(new Runnable() { 10658 public void run() { 10659 mHandler.removeCallbacks(this); 10660 // Result object to be returned 10661 PackageInstalledInfo res = new PackageInstalledInfo(); 10662 res.returnCode = currentStatus; 10663 res.uid = -1; 10664 res.pkg = null; 10665 res.removedInfo = new PackageRemovedInfo(); 10666 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10667 args.doPreInstall(res.returnCode); 10668 synchronized (mInstallLock) { 10669 installPackageTracedLI(args, res); 10670 } 10671 args.doPostInstall(res.returnCode, res.uid); 10672 } 10673 10674 // A restore should be performed at this point if (a) the install 10675 // succeeded, (b) the operation is not an update, and (c) the new 10676 // package has not opted out of backup participation. 10677 final boolean update = res.removedInfo.removedPackage != null; 10678 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10679 boolean doRestore = !update 10680 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10681 10682 // Set up the post-install work request bookkeeping. This will be used 10683 // and cleaned up by the post-install event handling regardless of whether 10684 // there's a restore pass performed. Token values are >= 1. 10685 int token; 10686 if (mNextInstallToken < 0) mNextInstallToken = 1; 10687 token = mNextInstallToken++; 10688 10689 PostInstallData data = new PostInstallData(args, res); 10690 mRunningInstalls.put(token, data); 10691 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10692 10693 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10694 // Pass responsibility to the Backup Manager. It will perform a 10695 // restore if appropriate, then pass responsibility back to the 10696 // Package Manager to run the post-install observer callbacks 10697 // and broadcasts. 10698 IBackupManager bm = IBackupManager.Stub.asInterface( 10699 ServiceManager.getService(Context.BACKUP_SERVICE)); 10700 if (bm != null) { 10701 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10702 + " to BM for possible restore"); 10703 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10704 try { 10705 // TODO: http://b/22388012 10706 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10707 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10708 } else { 10709 doRestore = false; 10710 } 10711 } catch (RemoteException e) { 10712 // can't happen; the backup manager is local 10713 } catch (Exception e) { 10714 Slog.e(TAG, "Exception trying to enqueue restore", e); 10715 doRestore = false; 10716 } 10717 } else { 10718 Slog.e(TAG, "Backup Manager not found!"); 10719 doRestore = false; 10720 } 10721 } 10722 10723 if (!doRestore) { 10724 // No restore possible, or the Backup Manager was mysteriously not 10725 // available -- just fire the post-install work request directly. 10726 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10727 10728 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10729 10730 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10731 mHandler.sendMessage(msg); 10732 } 10733 } 10734 }); 10735 } 10736 10737 private abstract class HandlerParams { 10738 private static final int MAX_RETRIES = 4; 10739 10740 /** 10741 * Number of times startCopy() has been attempted and had a non-fatal 10742 * error. 10743 */ 10744 private int mRetries = 0; 10745 10746 /** User handle for the user requesting the information or installation. */ 10747 private final UserHandle mUser; 10748 String traceMethod; 10749 int traceCookie; 10750 10751 HandlerParams(UserHandle user) { 10752 mUser = user; 10753 } 10754 10755 UserHandle getUser() { 10756 return mUser; 10757 } 10758 10759 HandlerParams setTraceMethod(String traceMethod) { 10760 this.traceMethod = traceMethod; 10761 return this; 10762 } 10763 10764 HandlerParams setTraceCookie(int traceCookie) { 10765 this.traceCookie = traceCookie; 10766 return this; 10767 } 10768 10769 final boolean startCopy() { 10770 boolean res; 10771 try { 10772 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10773 10774 if (++mRetries > MAX_RETRIES) { 10775 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10776 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10777 handleServiceError(); 10778 return false; 10779 } else { 10780 handleStartCopy(); 10781 res = true; 10782 } 10783 } catch (RemoteException e) { 10784 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10785 mHandler.sendEmptyMessage(MCS_RECONNECT); 10786 res = false; 10787 } 10788 handleReturnCode(); 10789 return res; 10790 } 10791 10792 final void serviceError() { 10793 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10794 handleServiceError(); 10795 handleReturnCode(); 10796 } 10797 10798 abstract void handleStartCopy() throws RemoteException; 10799 abstract void handleServiceError(); 10800 abstract void handleReturnCode(); 10801 } 10802 10803 class MeasureParams extends HandlerParams { 10804 private final PackageStats mStats; 10805 private boolean mSuccess; 10806 10807 private final IPackageStatsObserver mObserver; 10808 10809 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10810 super(new UserHandle(stats.userHandle)); 10811 mObserver = observer; 10812 mStats = stats; 10813 } 10814 10815 @Override 10816 public String toString() { 10817 return "MeasureParams{" 10818 + Integer.toHexString(System.identityHashCode(this)) 10819 + " " + mStats.packageName + "}"; 10820 } 10821 10822 @Override 10823 void handleStartCopy() throws RemoteException { 10824 synchronized (mInstallLock) { 10825 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10826 } 10827 10828 if (mSuccess) { 10829 final boolean mounted; 10830 if (Environment.isExternalStorageEmulated()) { 10831 mounted = true; 10832 } else { 10833 final String status = Environment.getExternalStorageState(); 10834 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10835 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10836 } 10837 10838 if (mounted) { 10839 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10840 10841 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10842 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10843 10844 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10845 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10846 10847 // Always subtract cache size, since it's a subdirectory 10848 mStats.externalDataSize -= mStats.externalCacheSize; 10849 10850 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10851 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10852 10853 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10854 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10855 } 10856 } 10857 } 10858 10859 @Override 10860 void handleReturnCode() { 10861 if (mObserver != null) { 10862 try { 10863 mObserver.onGetStatsCompleted(mStats, mSuccess); 10864 } catch (RemoteException e) { 10865 Slog.i(TAG, "Observer no longer exists."); 10866 } 10867 } 10868 } 10869 10870 @Override 10871 void handleServiceError() { 10872 Slog.e(TAG, "Could not measure application " + mStats.packageName 10873 + " external storage"); 10874 } 10875 } 10876 10877 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10878 throws RemoteException { 10879 long result = 0; 10880 for (File path : paths) { 10881 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10882 } 10883 return result; 10884 } 10885 10886 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10887 for (File path : paths) { 10888 try { 10889 mcs.clearDirectory(path.getAbsolutePath()); 10890 } catch (RemoteException e) { 10891 } 10892 } 10893 } 10894 10895 static class OriginInfo { 10896 /** 10897 * Location where install is coming from, before it has been 10898 * copied/renamed into place. This could be a single monolithic APK 10899 * file, or a cluster directory. This location may be untrusted. 10900 */ 10901 final File file; 10902 final String cid; 10903 10904 /** 10905 * Flag indicating that {@link #file} or {@link #cid} has already been 10906 * staged, meaning downstream users don't need to defensively copy the 10907 * contents. 10908 */ 10909 final boolean staged; 10910 10911 /** 10912 * Flag indicating that {@link #file} or {@link #cid} is an already 10913 * installed app that is being moved. 10914 */ 10915 final boolean existing; 10916 10917 final String resolvedPath; 10918 final File resolvedFile; 10919 10920 static OriginInfo fromNothing() { 10921 return new OriginInfo(null, null, false, false); 10922 } 10923 10924 static OriginInfo fromUntrustedFile(File file) { 10925 return new OriginInfo(file, null, false, false); 10926 } 10927 10928 static OriginInfo fromExistingFile(File file) { 10929 return new OriginInfo(file, null, false, true); 10930 } 10931 10932 static OriginInfo fromStagedFile(File file) { 10933 return new OriginInfo(file, null, true, false); 10934 } 10935 10936 static OriginInfo fromStagedContainer(String cid) { 10937 return new OriginInfo(null, cid, true, false); 10938 } 10939 10940 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10941 this.file = file; 10942 this.cid = cid; 10943 this.staged = staged; 10944 this.existing = existing; 10945 10946 if (cid != null) { 10947 resolvedPath = PackageHelper.getSdDir(cid); 10948 resolvedFile = new File(resolvedPath); 10949 } else if (file != null) { 10950 resolvedPath = file.getAbsolutePath(); 10951 resolvedFile = file; 10952 } else { 10953 resolvedPath = null; 10954 resolvedFile = null; 10955 } 10956 } 10957 } 10958 10959 static class MoveInfo { 10960 final int moveId; 10961 final String fromUuid; 10962 final String toUuid; 10963 final String packageName; 10964 final String dataAppName; 10965 final int appId; 10966 final String seinfo; 10967 10968 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10969 String dataAppName, int appId, String seinfo) { 10970 this.moveId = moveId; 10971 this.fromUuid = fromUuid; 10972 this.toUuid = toUuid; 10973 this.packageName = packageName; 10974 this.dataAppName = dataAppName; 10975 this.appId = appId; 10976 this.seinfo = seinfo; 10977 } 10978 } 10979 10980 class InstallParams extends HandlerParams { 10981 final OriginInfo origin; 10982 final MoveInfo move; 10983 final IPackageInstallObserver2 observer; 10984 int installFlags; 10985 final String installerPackageName; 10986 final String volumeUuid; 10987 final VerificationParams verificationParams; 10988 private InstallArgs mArgs; 10989 private int mRet; 10990 final String packageAbiOverride; 10991 final String[] grantedRuntimePermissions; 10992 10993 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10994 int installFlags, String installerPackageName, String volumeUuid, 10995 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10996 String[] grantedPermissions) { 10997 super(user); 10998 this.origin = origin; 10999 this.move = move; 11000 this.observer = observer; 11001 this.installFlags = installFlags; 11002 this.installerPackageName = installerPackageName; 11003 this.volumeUuid = volumeUuid; 11004 this.verificationParams = verificationParams; 11005 this.packageAbiOverride = packageAbiOverride; 11006 this.grantedRuntimePermissions = grantedPermissions; 11007 } 11008 11009 @Override 11010 public String toString() { 11011 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11012 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11013 } 11014 11015 private int installLocationPolicy(PackageInfoLite pkgLite) { 11016 String packageName = pkgLite.packageName; 11017 int installLocation = pkgLite.installLocation; 11018 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11019 // reader 11020 synchronized (mPackages) { 11021 PackageParser.Package pkg = mPackages.get(packageName); 11022 if (pkg != null) { 11023 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11024 // Check for downgrading. 11025 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11026 try { 11027 checkDowngrade(pkg, pkgLite); 11028 } catch (PackageManagerException e) { 11029 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11030 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11031 } 11032 } 11033 // Check for updated system application. 11034 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11035 if (onSd) { 11036 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11037 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11038 } 11039 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11040 } else { 11041 if (onSd) { 11042 // Install flag overrides everything. 11043 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11044 } 11045 // If current upgrade specifies particular preference 11046 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11047 // Application explicitly specified internal. 11048 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11049 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11050 // App explictly prefers external. Let policy decide 11051 } else { 11052 // Prefer previous location 11053 if (isExternal(pkg)) { 11054 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11055 } 11056 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11057 } 11058 } 11059 } else { 11060 // Invalid install. Return error code 11061 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11062 } 11063 } 11064 } 11065 // All the special cases have been taken care of. 11066 // Return result based on recommended install location. 11067 if (onSd) { 11068 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11069 } 11070 return pkgLite.recommendedInstallLocation; 11071 } 11072 11073 /* 11074 * Invoke remote method to get package information and install 11075 * location values. Override install location based on default 11076 * policy if needed and then create install arguments based 11077 * on the install location. 11078 */ 11079 public void handleStartCopy() throws RemoteException { 11080 int ret = PackageManager.INSTALL_SUCCEEDED; 11081 11082 // If we're already staged, we've firmly committed to an install location 11083 if (origin.staged) { 11084 if (origin.file != null) { 11085 installFlags |= PackageManager.INSTALL_INTERNAL; 11086 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11087 } else if (origin.cid != null) { 11088 installFlags |= PackageManager.INSTALL_EXTERNAL; 11089 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11090 } else { 11091 throw new IllegalStateException("Invalid stage location"); 11092 } 11093 } 11094 11095 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11096 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11097 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11098 PackageInfoLite pkgLite = null; 11099 11100 if (onInt && onSd) { 11101 // Check if both bits are set. 11102 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11103 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11104 } else if (onSd && ephemeral) { 11105 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11106 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11107 } else { 11108 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11109 packageAbiOverride); 11110 11111 if (DEBUG_EPHEMERAL && ephemeral) { 11112 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11113 } 11114 11115 /* 11116 * If we have too little free space, try to free cache 11117 * before giving up. 11118 */ 11119 if (!origin.staged && pkgLite.recommendedInstallLocation 11120 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11121 // TODO: focus freeing disk space on the target device 11122 final StorageManager storage = StorageManager.from(mContext); 11123 final long lowThreshold = storage.getStorageLowBytes( 11124 Environment.getDataDirectory()); 11125 11126 final long sizeBytes = mContainerService.calculateInstalledSize( 11127 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11128 11129 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11130 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11131 installFlags, packageAbiOverride); 11132 } 11133 11134 /* 11135 * The cache free must have deleted the file we 11136 * downloaded to install. 11137 * 11138 * TODO: fix the "freeCache" call to not delete 11139 * the file we care about. 11140 */ 11141 if (pkgLite.recommendedInstallLocation 11142 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11143 pkgLite.recommendedInstallLocation 11144 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11145 } 11146 } 11147 } 11148 11149 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11150 int loc = pkgLite.recommendedInstallLocation; 11151 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11152 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11153 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11154 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11155 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11156 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11157 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11158 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11159 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11160 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11161 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11162 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11163 } else { 11164 // Override with defaults if needed. 11165 loc = installLocationPolicy(pkgLite); 11166 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11167 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11168 } else if (!onSd && !onInt) { 11169 // Override install location with flags 11170 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11171 // Set the flag to install on external media. 11172 installFlags |= PackageManager.INSTALL_EXTERNAL; 11173 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11174 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11175 if (DEBUG_EPHEMERAL) { 11176 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11177 } 11178 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11179 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11180 |PackageManager.INSTALL_INTERNAL); 11181 } else { 11182 // Make sure the flag for installing on external 11183 // media is unset 11184 installFlags |= PackageManager.INSTALL_INTERNAL; 11185 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11186 } 11187 } 11188 } 11189 } 11190 11191 final InstallArgs args = createInstallArgs(this); 11192 mArgs = args; 11193 11194 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11195 // TODO: http://b/22976637 11196 // Apps installed for "all" users use the device owner to verify the app 11197 UserHandle verifierUser = getUser(); 11198 if (verifierUser == UserHandle.ALL) { 11199 verifierUser = UserHandle.SYSTEM; 11200 } 11201 11202 /* 11203 * Determine if we have any installed package verifiers. If we 11204 * do, then we'll defer to them to verify the packages. 11205 */ 11206 final int requiredUid = mRequiredVerifierPackage == null ? -1 11207 : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier()); 11208 if (!origin.existing && requiredUid != -1 11209 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11210 final Intent verification = new Intent( 11211 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11212 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11213 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11214 PACKAGE_MIME_TYPE); 11215 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11216 11217 // Query all live verifiers based on current user state 11218 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11219 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11220 11221 if (DEBUG_VERIFY) { 11222 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11223 + verification.toString() + " with " + pkgLite.verifiers.length 11224 + " optional verifiers"); 11225 } 11226 11227 final int verificationId = mPendingVerificationToken++; 11228 11229 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11230 11231 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11232 installerPackageName); 11233 11234 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11235 installFlags); 11236 11237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11238 pkgLite.packageName); 11239 11240 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11241 pkgLite.versionCode); 11242 11243 if (verificationParams != null) { 11244 if (verificationParams.getVerificationURI() != null) { 11245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11246 verificationParams.getVerificationURI()); 11247 } 11248 if (verificationParams.getOriginatingURI() != null) { 11249 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11250 verificationParams.getOriginatingURI()); 11251 } 11252 if (verificationParams.getReferrer() != null) { 11253 verification.putExtra(Intent.EXTRA_REFERRER, 11254 verificationParams.getReferrer()); 11255 } 11256 if (verificationParams.getOriginatingUid() >= 0) { 11257 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11258 verificationParams.getOriginatingUid()); 11259 } 11260 if (verificationParams.getInstallerUid() >= 0) { 11261 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11262 verificationParams.getInstallerUid()); 11263 } 11264 } 11265 11266 final PackageVerificationState verificationState = new PackageVerificationState( 11267 requiredUid, args); 11268 11269 mPendingVerification.append(verificationId, verificationState); 11270 11271 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11272 receivers, verificationState); 11273 11274 /* 11275 * If any sufficient verifiers were listed in the package 11276 * manifest, attempt to ask them. 11277 */ 11278 if (sufficientVerifiers != null) { 11279 final int N = sufficientVerifiers.size(); 11280 if (N == 0) { 11281 Slog.i(TAG, "Additional verifiers required, but none installed."); 11282 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11283 } else { 11284 for (int i = 0; i < N; i++) { 11285 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11286 11287 final Intent sufficientIntent = new Intent(verification); 11288 sufficientIntent.setComponent(verifierComponent); 11289 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11290 } 11291 } 11292 } 11293 11294 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11295 mRequiredVerifierPackage, receivers); 11296 if (ret == PackageManager.INSTALL_SUCCEEDED 11297 && mRequiredVerifierPackage != null) { 11298 Trace.asyncTraceBegin( 11299 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11300 /* 11301 * Send the intent to the required verification agent, 11302 * but only start the verification timeout after the 11303 * target BroadcastReceivers have run. 11304 */ 11305 verification.setComponent(requiredVerifierComponent); 11306 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11307 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11308 new BroadcastReceiver() { 11309 @Override 11310 public void onReceive(Context context, Intent intent) { 11311 final Message msg = mHandler 11312 .obtainMessage(CHECK_PENDING_VERIFICATION); 11313 msg.arg1 = verificationId; 11314 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11315 } 11316 }, null, 0, null, null); 11317 11318 /* 11319 * We don't want the copy to proceed until verification 11320 * succeeds, so null out this field. 11321 */ 11322 mArgs = null; 11323 } 11324 } else { 11325 /* 11326 * No package verification is enabled, so immediately start 11327 * the remote call to initiate copy using temporary file. 11328 */ 11329 ret = args.copyApk(mContainerService, true); 11330 } 11331 } 11332 11333 mRet = ret; 11334 } 11335 11336 @Override 11337 void handleReturnCode() { 11338 // If mArgs is null, then MCS couldn't be reached. When it 11339 // reconnects, it will try again to install. At that point, this 11340 // will succeed. 11341 if (mArgs != null) { 11342 processPendingInstall(mArgs, mRet); 11343 } 11344 } 11345 11346 @Override 11347 void handleServiceError() { 11348 mArgs = createInstallArgs(this); 11349 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11350 } 11351 11352 public boolean isForwardLocked() { 11353 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11354 } 11355 } 11356 11357 /** 11358 * Used during creation of InstallArgs 11359 * 11360 * @param installFlags package installation flags 11361 * @return true if should be installed on external storage 11362 */ 11363 private static boolean installOnExternalAsec(int installFlags) { 11364 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11365 return false; 11366 } 11367 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11368 return true; 11369 } 11370 return false; 11371 } 11372 11373 /** 11374 * Used during creation of InstallArgs 11375 * 11376 * @param installFlags package installation flags 11377 * @return true if should be installed as forward locked 11378 */ 11379 private static boolean installForwardLocked(int installFlags) { 11380 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11381 } 11382 11383 private InstallArgs createInstallArgs(InstallParams params) { 11384 if (params.move != null) { 11385 return new MoveInstallArgs(params); 11386 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11387 return new AsecInstallArgs(params); 11388 } else { 11389 return new FileInstallArgs(params); 11390 } 11391 } 11392 11393 /** 11394 * Create args that describe an existing installed package. Typically used 11395 * when cleaning up old installs, or used as a move source. 11396 */ 11397 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11398 String resourcePath, String[] instructionSets) { 11399 final boolean isInAsec; 11400 if (installOnExternalAsec(installFlags)) { 11401 /* Apps on SD card are always in ASEC containers. */ 11402 isInAsec = true; 11403 } else if (installForwardLocked(installFlags) 11404 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11405 /* 11406 * Forward-locked apps are only in ASEC containers if they're the 11407 * new style 11408 */ 11409 isInAsec = true; 11410 } else { 11411 isInAsec = false; 11412 } 11413 11414 if (isInAsec) { 11415 return new AsecInstallArgs(codePath, instructionSets, 11416 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11417 } else { 11418 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11419 } 11420 } 11421 11422 static abstract class InstallArgs { 11423 /** @see InstallParams#origin */ 11424 final OriginInfo origin; 11425 /** @see InstallParams#move */ 11426 final MoveInfo move; 11427 11428 final IPackageInstallObserver2 observer; 11429 // Always refers to PackageManager flags only 11430 final int installFlags; 11431 final String installerPackageName; 11432 final String volumeUuid; 11433 final UserHandle user; 11434 final String abiOverride; 11435 final String[] installGrantPermissions; 11436 /** If non-null, drop an async trace when the install completes */ 11437 final String traceMethod; 11438 final int traceCookie; 11439 11440 // The list of instruction sets supported by this app. This is currently 11441 // only used during the rmdex() phase to clean up resources. We can get rid of this 11442 // if we move dex files under the common app path. 11443 /* nullable */ String[] instructionSets; 11444 11445 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11446 int installFlags, String installerPackageName, String volumeUuid, 11447 UserHandle user, String[] instructionSets, 11448 String abiOverride, String[] installGrantPermissions, 11449 String traceMethod, int traceCookie) { 11450 this.origin = origin; 11451 this.move = move; 11452 this.installFlags = installFlags; 11453 this.observer = observer; 11454 this.installerPackageName = installerPackageName; 11455 this.volumeUuid = volumeUuid; 11456 this.user = user; 11457 this.instructionSets = instructionSets; 11458 this.abiOverride = abiOverride; 11459 this.installGrantPermissions = installGrantPermissions; 11460 this.traceMethod = traceMethod; 11461 this.traceCookie = traceCookie; 11462 } 11463 11464 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11465 abstract int doPreInstall(int status); 11466 11467 /** 11468 * Rename package into final resting place. All paths on the given 11469 * scanned package should be updated to reflect the rename. 11470 */ 11471 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11472 abstract int doPostInstall(int status, int uid); 11473 11474 /** @see PackageSettingBase#codePathString */ 11475 abstract String getCodePath(); 11476 /** @see PackageSettingBase#resourcePathString */ 11477 abstract String getResourcePath(); 11478 11479 // Need installer lock especially for dex file removal. 11480 abstract void cleanUpResourcesLI(); 11481 abstract boolean doPostDeleteLI(boolean delete); 11482 11483 /** 11484 * Called before the source arguments are copied. This is used mostly 11485 * for MoveParams when it needs to read the source file to put it in the 11486 * destination. 11487 */ 11488 int doPreCopy() { 11489 return PackageManager.INSTALL_SUCCEEDED; 11490 } 11491 11492 /** 11493 * Called after the source arguments are copied. This is used mostly for 11494 * MoveParams when it needs to read the source file to put it in the 11495 * destination. 11496 * 11497 * @return 11498 */ 11499 int doPostCopy(int uid) { 11500 return PackageManager.INSTALL_SUCCEEDED; 11501 } 11502 11503 protected boolean isFwdLocked() { 11504 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11505 } 11506 11507 protected boolean isExternalAsec() { 11508 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11509 } 11510 11511 protected boolean isEphemeral() { 11512 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11513 } 11514 11515 UserHandle getUser() { 11516 return user; 11517 } 11518 } 11519 11520 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11521 if (!allCodePaths.isEmpty()) { 11522 if (instructionSets == null) { 11523 throw new IllegalStateException("instructionSet == null"); 11524 } 11525 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11526 for (String codePath : allCodePaths) { 11527 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11528 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11529 if (retCode < 0) { 11530 Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath 11531 + ", retcode=" + retCode); 11532 // we don't consider this to be a failure of the core package deletion 11533 } 11534 } 11535 } 11536 } 11537 } 11538 11539 /** 11540 * Logic to handle installation of non-ASEC applications, including copying 11541 * and renaming logic. 11542 */ 11543 class FileInstallArgs extends InstallArgs { 11544 private File codeFile; 11545 private File resourceFile; 11546 11547 // Example topology: 11548 // /data/app/com.example/base.apk 11549 // /data/app/com.example/split_foo.apk 11550 // /data/app/com.example/lib/arm/libfoo.so 11551 // /data/app/com.example/lib/arm64/libfoo.so 11552 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11553 11554 /** New install */ 11555 FileInstallArgs(InstallParams params) { 11556 super(params.origin, params.move, params.observer, params.installFlags, 11557 params.installerPackageName, params.volumeUuid, 11558 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11559 params.grantedRuntimePermissions, 11560 params.traceMethod, params.traceCookie); 11561 if (isFwdLocked()) { 11562 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11563 } 11564 } 11565 11566 /** Existing install */ 11567 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11568 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11569 null, null, null, 0); 11570 this.codeFile = (codePath != null) ? new File(codePath) : null; 11571 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11572 } 11573 11574 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11575 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11576 try { 11577 return doCopyApk(imcs, temp); 11578 } finally { 11579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11580 } 11581 } 11582 11583 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11584 if (origin.staged) { 11585 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11586 codeFile = origin.file; 11587 resourceFile = origin.file; 11588 return PackageManager.INSTALL_SUCCEEDED; 11589 } 11590 11591 try { 11592 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11593 final File tempDir = 11594 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11595 codeFile = tempDir; 11596 resourceFile = tempDir; 11597 } catch (IOException e) { 11598 Slog.w(TAG, "Failed to create copy file: " + e); 11599 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11600 } 11601 11602 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11603 @Override 11604 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11605 if (!FileUtils.isValidExtFilename(name)) { 11606 throw new IllegalArgumentException("Invalid filename: " + name); 11607 } 11608 try { 11609 final File file = new File(codeFile, name); 11610 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11611 O_RDWR | O_CREAT, 0644); 11612 Os.chmod(file.getAbsolutePath(), 0644); 11613 return new ParcelFileDescriptor(fd); 11614 } catch (ErrnoException e) { 11615 throw new RemoteException("Failed to open: " + e.getMessage()); 11616 } 11617 } 11618 }; 11619 11620 int ret = PackageManager.INSTALL_SUCCEEDED; 11621 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11622 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11623 Slog.e(TAG, "Failed to copy package"); 11624 return ret; 11625 } 11626 11627 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11628 NativeLibraryHelper.Handle handle = null; 11629 try { 11630 handle = NativeLibraryHelper.Handle.create(codeFile); 11631 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11632 abiOverride); 11633 } catch (IOException e) { 11634 Slog.e(TAG, "Copying native libraries failed", e); 11635 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11636 } finally { 11637 IoUtils.closeQuietly(handle); 11638 } 11639 11640 return ret; 11641 } 11642 11643 int doPreInstall(int status) { 11644 if (status != PackageManager.INSTALL_SUCCEEDED) { 11645 cleanUp(); 11646 } 11647 return status; 11648 } 11649 11650 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11651 if (status != PackageManager.INSTALL_SUCCEEDED) { 11652 cleanUp(); 11653 return false; 11654 } 11655 11656 final File targetDir = codeFile.getParentFile(); 11657 final File beforeCodeFile = codeFile; 11658 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11659 11660 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11661 try { 11662 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11663 } catch (ErrnoException e) { 11664 Slog.w(TAG, "Failed to rename", e); 11665 return false; 11666 } 11667 11668 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11669 Slog.w(TAG, "Failed to restorecon"); 11670 return false; 11671 } 11672 11673 // Reflect the rename internally 11674 codeFile = afterCodeFile; 11675 resourceFile = afterCodeFile; 11676 11677 // Reflect the rename in scanned details 11678 pkg.codePath = afterCodeFile.getAbsolutePath(); 11679 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11680 pkg.baseCodePath); 11681 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11682 pkg.splitCodePaths); 11683 11684 // Reflect the rename in app info 11685 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11686 pkg.applicationInfo.setCodePath(pkg.codePath); 11687 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11688 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11689 pkg.applicationInfo.setResourcePath(pkg.codePath); 11690 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11691 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11692 11693 return true; 11694 } 11695 11696 int doPostInstall(int status, int uid) { 11697 if (status != PackageManager.INSTALL_SUCCEEDED) { 11698 cleanUp(); 11699 } 11700 return status; 11701 } 11702 11703 @Override 11704 String getCodePath() { 11705 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11706 } 11707 11708 @Override 11709 String getResourcePath() { 11710 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11711 } 11712 11713 private boolean cleanUp() { 11714 if (codeFile == null || !codeFile.exists()) { 11715 return false; 11716 } 11717 11718 if (codeFile.isDirectory()) { 11719 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11720 } else { 11721 codeFile.delete(); 11722 } 11723 11724 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11725 resourceFile.delete(); 11726 } 11727 11728 return true; 11729 } 11730 11731 void cleanUpResourcesLI() { 11732 // Try enumerating all code paths before deleting 11733 List<String> allCodePaths = Collections.EMPTY_LIST; 11734 if (codeFile != null && codeFile.exists()) { 11735 try { 11736 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11737 allCodePaths = pkg.getAllCodePaths(); 11738 } catch (PackageParserException e) { 11739 // Ignored; we tried our best 11740 } 11741 } 11742 11743 cleanUp(); 11744 removeDexFiles(allCodePaths, instructionSets); 11745 } 11746 11747 boolean doPostDeleteLI(boolean delete) { 11748 // XXX err, shouldn't we respect the delete flag? 11749 cleanUpResourcesLI(); 11750 return true; 11751 } 11752 } 11753 11754 private boolean isAsecExternal(String cid) { 11755 final String asecPath = PackageHelper.getSdFilesystem(cid); 11756 return !asecPath.startsWith(mAsecInternalPath); 11757 } 11758 11759 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11760 PackageManagerException { 11761 if (copyRet < 0) { 11762 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11763 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11764 throw new PackageManagerException(copyRet, message); 11765 } 11766 } 11767 } 11768 11769 /** 11770 * Extract the MountService "container ID" from the full code path of an 11771 * .apk. 11772 */ 11773 static String cidFromCodePath(String fullCodePath) { 11774 int eidx = fullCodePath.lastIndexOf("/"); 11775 String subStr1 = fullCodePath.substring(0, eidx); 11776 int sidx = subStr1.lastIndexOf("/"); 11777 return subStr1.substring(sidx+1, eidx); 11778 } 11779 11780 /** 11781 * Logic to handle installation of ASEC applications, including copying and 11782 * renaming logic. 11783 */ 11784 class AsecInstallArgs extends InstallArgs { 11785 static final String RES_FILE_NAME = "pkg.apk"; 11786 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11787 11788 String cid; 11789 String packagePath; 11790 String resourcePath; 11791 11792 /** New install */ 11793 AsecInstallArgs(InstallParams params) { 11794 super(params.origin, params.move, params.observer, params.installFlags, 11795 params.installerPackageName, params.volumeUuid, 11796 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11797 params.grantedRuntimePermissions, 11798 params.traceMethod, params.traceCookie); 11799 } 11800 11801 /** Existing install */ 11802 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11803 boolean isExternal, boolean isForwardLocked) { 11804 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11805 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11806 instructionSets, null, null, null, 0); 11807 // Hackily pretend we're still looking at a full code path 11808 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11809 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11810 } 11811 11812 // Extract cid from fullCodePath 11813 int eidx = fullCodePath.lastIndexOf("/"); 11814 String subStr1 = fullCodePath.substring(0, eidx); 11815 int sidx = subStr1.lastIndexOf("/"); 11816 cid = subStr1.substring(sidx+1, eidx); 11817 setMountPath(subStr1); 11818 } 11819 11820 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11821 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11822 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11823 instructionSets, null, null, null, 0); 11824 this.cid = cid; 11825 setMountPath(PackageHelper.getSdDir(cid)); 11826 } 11827 11828 void createCopyFile() { 11829 cid = mInstallerService.allocateExternalStageCidLegacy(); 11830 } 11831 11832 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11833 if (origin.staged && origin.cid != null) { 11834 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11835 cid = origin.cid; 11836 setMountPath(PackageHelper.getSdDir(cid)); 11837 return PackageManager.INSTALL_SUCCEEDED; 11838 } 11839 11840 if (temp) { 11841 createCopyFile(); 11842 } else { 11843 /* 11844 * Pre-emptively destroy the container since it's destroyed if 11845 * copying fails due to it existing anyway. 11846 */ 11847 PackageHelper.destroySdDir(cid); 11848 } 11849 11850 final String newMountPath = imcs.copyPackageToContainer( 11851 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11852 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11853 11854 if (newMountPath != null) { 11855 setMountPath(newMountPath); 11856 return PackageManager.INSTALL_SUCCEEDED; 11857 } else { 11858 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11859 } 11860 } 11861 11862 @Override 11863 String getCodePath() { 11864 return packagePath; 11865 } 11866 11867 @Override 11868 String getResourcePath() { 11869 return resourcePath; 11870 } 11871 11872 int doPreInstall(int status) { 11873 if (status != PackageManager.INSTALL_SUCCEEDED) { 11874 // Destroy container 11875 PackageHelper.destroySdDir(cid); 11876 } else { 11877 boolean mounted = PackageHelper.isContainerMounted(cid); 11878 if (!mounted) { 11879 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11880 Process.SYSTEM_UID); 11881 if (newMountPath != null) { 11882 setMountPath(newMountPath); 11883 } else { 11884 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11885 } 11886 } 11887 } 11888 return status; 11889 } 11890 11891 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11892 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11893 String newMountPath = null; 11894 if (PackageHelper.isContainerMounted(cid)) { 11895 // Unmount the container 11896 if (!PackageHelper.unMountSdDir(cid)) { 11897 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11898 return false; 11899 } 11900 } 11901 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11902 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11903 " which might be stale. Will try to clean up."); 11904 // Clean up the stale container and proceed to recreate. 11905 if (!PackageHelper.destroySdDir(newCacheId)) { 11906 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11907 return false; 11908 } 11909 // Successfully cleaned up stale container. Try to rename again. 11910 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11911 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11912 + " inspite of cleaning it up."); 11913 return false; 11914 } 11915 } 11916 if (!PackageHelper.isContainerMounted(newCacheId)) { 11917 Slog.w(TAG, "Mounting container " + newCacheId); 11918 newMountPath = PackageHelper.mountSdDir(newCacheId, 11919 getEncryptKey(), Process.SYSTEM_UID); 11920 } else { 11921 newMountPath = PackageHelper.getSdDir(newCacheId); 11922 } 11923 if (newMountPath == null) { 11924 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11925 return false; 11926 } 11927 Log.i(TAG, "Succesfully renamed " + cid + 11928 " to " + newCacheId + 11929 " at new path: " + newMountPath); 11930 cid = newCacheId; 11931 11932 final File beforeCodeFile = new File(packagePath); 11933 setMountPath(newMountPath); 11934 final File afterCodeFile = new File(packagePath); 11935 11936 // Reflect the rename in scanned details 11937 pkg.codePath = afterCodeFile.getAbsolutePath(); 11938 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11939 pkg.baseCodePath); 11940 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11941 pkg.splitCodePaths); 11942 11943 // Reflect the rename in app info 11944 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11945 pkg.applicationInfo.setCodePath(pkg.codePath); 11946 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11947 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11948 pkg.applicationInfo.setResourcePath(pkg.codePath); 11949 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11950 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11951 11952 return true; 11953 } 11954 11955 private void setMountPath(String mountPath) { 11956 final File mountFile = new File(mountPath); 11957 11958 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11959 if (monolithicFile.exists()) { 11960 packagePath = monolithicFile.getAbsolutePath(); 11961 if (isFwdLocked()) { 11962 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11963 } else { 11964 resourcePath = packagePath; 11965 } 11966 } else { 11967 packagePath = mountFile.getAbsolutePath(); 11968 resourcePath = packagePath; 11969 } 11970 } 11971 11972 int doPostInstall(int status, int uid) { 11973 if (status != PackageManager.INSTALL_SUCCEEDED) { 11974 cleanUp(); 11975 } else { 11976 final int groupOwner; 11977 final String protectedFile; 11978 if (isFwdLocked()) { 11979 groupOwner = UserHandle.getSharedAppGid(uid); 11980 protectedFile = RES_FILE_NAME; 11981 } else { 11982 groupOwner = -1; 11983 protectedFile = null; 11984 } 11985 11986 if (uid < Process.FIRST_APPLICATION_UID 11987 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11988 Slog.e(TAG, "Failed to finalize " + cid); 11989 PackageHelper.destroySdDir(cid); 11990 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11991 } 11992 11993 boolean mounted = PackageHelper.isContainerMounted(cid); 11994 if (!mounted) { 11995 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11996 } 11997 } 11998 return status; 11999 } 12000 12001 private void cleanUp() { 12002 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12003 12004 // Destroy secure container 12005 PackageHelper.destroySdDir(cid); 12006 } 12007 12008 private List<String> getAllCodePaths() { 12009 final File codeFile = new File(getCodePath()); 12010 if (codeFile != null && codeFile.exists()) { 12011 try { 12012 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12013 return pkg.getAllCodePaths(); 12014 } catch (PackageParserException e) { 12015 // Ignored; we tried our best 12016 } 12017 } 12018 return Collections.EMPTY_LIST; 12019 } 12020 12021 void cleanUpResourcesLI() { 12022 // Enumerate all code paths before deleting 12023 cleanUpResourcesLI(getAllCodePaths()); 12024 } 12025 12026 private void cleanUpResourcesLI(List<String> allCodePaths) { 12027 cleanUp(); 12028 removeDexFiles(allCodePaths, instructionSets); 12029 } 12030 12031 String getPackageName() { 12032 return getAsecPackageName(cid); 12033 } 12034 12035 boolean doPostDeleteLI(boolean delete) { 12036 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12037 final List<String> allCodePaths = getAllCodePaths(); 12038 boolean mounted = PackageHelper.isContainerMounted(cid); 12039 if (mounted) { 12040 // Unmount first 12041 if (PackageHelper.unMountSdDir(cid)) { 12042 mounted = false; 12043 } 12044 } 12045 if (!mounted && delete) { 12046 cleanUpResourcesLI(allCodePaths); 12047 } 12048 return !mounted; 12049 } 12050 12051 @Override 12052 int doPreCopy() { 12053 if (isFwdLocked()) { 12054 if (!PackageHelper.fixSdPermissions(cid, 12055 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 12056 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12057 } 12058 } 12059 12060 return PackageManager.INSTALL_SUCCEEDED; 12061 } 12062 12063 @Override 12064 int doPostCopy(int uid) { 12065 if (isFwdLocked()) { 12066 if (uid < Process.FIRST_APPLICATION_UID 12067 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12068 RES_FILE_NAME)) { 12069 Slog.e(TAG, "Failed to finalize " + cid); 12070 PackageHelper.destroySdDir(cid); 12071 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12072 } 12073 } 12074 12075 return PackageManager.INSTALL_SUCCEEDED; 12076 } 12077 } 12078 12079 /** 12080 * Logic to handle movement of existing installed applications. 12081 */ 12082 class MoveInstallArgs extends InstallArgs { 12083 private File codeFile; 12084 private File resourceFile; 12085 12086 /** New install */ 12087 MoveInstallArgs(InstallParams params) { 12088 super(params.origin, params.move, params.observer, params.installFlags, 12089 params.installerPackageName, params.volumeUuid, 12090 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12091 params.grantedRuntimePermissions, 12092 params.traceMethod, params.traceCookie); 12093 } 12094 12095 int copyApk(IMediaContainerService imcs, boolean temp) { 12096 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12097 + move.fromUuid + " to " + move.toUuid); 12098 synchronized (mInstaller) { 12099 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12100 move.dataAppName, move.appId, move.seinfo) != 0) { 12101 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12102 } 12103 } 12104 12105 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12106 resourceFile = codeFile; 12107 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12108 12109 return PackageManager.INSTALL_SUCCEEDED; 12110 } 12111 12112 int doPreInstall(int status) { 12113 if (status != PackageManager.INSTALL_SUCCEEDED) { 12114 cleanUp(move.toUuid); 12115 } 12116 return status; 12117 } 12118 12119 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12120 if (status != PackageManager.INSTALL_SUCCEEDED) { 12121 cleanUp(move.toUuid); 12122 return false; 12123 } 12124 12125 // Reflect the move in app info 12126 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12127 pkg.applicationInfo.setCodePath(pkg.codePath); 12128 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12129 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12130 pkg.applicationInfo.setResourcePath(pkg.codePath); 12131 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12132 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12133 12134 return true; 12135 } 12136 12137 int doPostInstall(int status, int uid) { 12138 if (status == PackageManager.INSTALL_SUCCEEDED) { 12139 cleanUp(move.fromUuid); 12140 } else { 12141 cleanUp(move.toUuid); 12142 } 12143 return status; 12144 } 12145 12146 @Override 12147 String getCodePath() { 12148 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12149 } 12150 12151 @Override 12152 String getResourcePath() { 12153 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12154 } 12155 12156 private boolean cleanUp(String volumeUuid) { 12157 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12158 move.dataAppName); 12159 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12160 synchronized (mInstallLock) { 12161 // Clean up both app data and code 12162 removeDataDirsLI(volumeUuid, move.packageName); 12163 if (codeFile.isDirectory()) { 12164 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12165 } else { 12166 codeFile.delete(); 12167 } 12168 } 12169 return true; 12170 } 12171 12172 void cleanUpResourcesLI() { 12173 throw new UnsupportedOperationException(); 12174 } 12175 12176 boolean doPostDeleteLI(boolean delete) { 12177 throw new UnsupportedOperationException(); 12178 } 12179 } 12180 12181 static String getAsecPackageName(String packageCid) { 12182 int idx = packageCid.lastIndexOf("-"); 12183 if (idx == -1) { 12184 return packageCid; 12185 } 12186 return packageCid.substring(0, idx); 12187 } 12188 12189 // Utility method used to create code paths based on package name and available index. 12190 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12191 String idxStr = ""; 12192 int idx = 1; 12193 // Fall back to default value of idx=1 if prefix is not 12194 // part of oldCodePath 12195 if (oldCodePath != null) { 12196 String subStr = oldCodePath; 12197 // Drop the suffix right away 12198 if (suffix != null && subStr.endsWith(suffix)) { 12199 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12200 } 12201 // If oldCodePath already contains prefix find out the 12202 // ending index to either increment or decrement. 12203 int sidx = subStr.lastIndexOf(prefix); 12204 if (sidx != -1) { 12205 subStr = subStr.substring(sidx + prefix.length()); 12206 if (subStr != null) { 12207 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12208 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12209 } 12210 try { 12211 idx = Integer.parseInt(subStr); 12212 if (idx <= 1) { 12213 idx++; 12214 } else { 12215 idx--; 12216 } 12217 } catch(NumberFormatException e) { 12218 } 12219 } 12220 } 12221 } 12222 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12223 return prefix + idxStr; 12224 } 12225 12226 private File getNextCodePath(File targetDir, String packageName) { 12227 int suffix = 1; 12228 File result; 12229 do { 12230 result = new File(targetDir, packageName + "-" + suffix); 12231 suffix++; 12232 } while (result.exists()); 12233 return result; 12234 } 12235 12236 // Utility method that returns the relative package path with respect 12237 // to the installation directory. Like say for /data/data/com.test-1.apk 12238 // string com.test-1 is returned. 12239 static String deriveCodePathName(String codePath) { 12240 if (codePath == null) { 12241 return null; 12242 } 12243 final File codeFile = new File(codePath); 12244 final String name = codeFile.getName(); 12245 if (codeFile.isDirectory()) { 12246 return name; 12247 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12248 final int lastDot = name.lastIndexOf('.'); 12249 return name.substring(0, lastDot); 12250 } else { 12251 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12252 return null; 12253 } 12254 } 12255 12256 static class PackageInstalledInfo { 12257 String name; 12258 int uid; 12259 // The set of users that originally had this package installed. 12260 int[] origUsers; 12261 // The set of users that now have this package installed. 12262 int[] newUsers; 12263 PackageParser.Package pkg; 12264 int returnCode; 12265 String returnMsg; 12266 PackageRemovedInfo removedInfo; 12267 12268 public void setError(int code, String msg) { 12269 returnCode = code; 12270 returnMsg = msg; 12271 Slog.w(TAG, msg); 12272 } 12273 12274 public void setError(String msg, PackageParserException e) { 12275 returnCode = e.error; 12276 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12277 Slog.w(TAG, msg, e); 12278 } 12279 12280 public void setError(String msg, PackageManagerException e) { 12281 returnCode = e.error; 12282 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12283 Slog.w(TAG, msg, e); 12284 } 12285 12286 // In some error cases we want to convey more info back to the observer 12287 String origPackage; 12288 String origPermission; 12289 } 12290 12291 /* 12292 * Install a non-existing package. 12293 */ 12294 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12295 UserHandle user, String installerPackageName, String volumeUuid, 12296 PackageInstalledInfo res) { 12297 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12298 12299 // Remember this for later, in case we need to rollback this install 12300 String pkgName = pkg.packageName; 12301 12302 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12303 // TODO: b/23350563 12304 final boolean dataDirExists = Environment 12305 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12306 12307 synchronized(mPackages) { 12308 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12309 // A package with the same name is already installed, though 12310 // it has been renamed to an older name. The package we 12311 // are trying to install should be installed as an update to 12312 // the existing one, but that has not been requested, so bail. 12313 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12314 + " without first uninstalling package running as " 12315 + mSettings.mRenamedPackages.get(pkgName)); 12316 return; 12317 } 12318 if (mPackages.containsKey(pkgName)) { 12319 // Don't allow installation over an existing package with the same name. 12320 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12321 + " without first uninstalling."); 12322 return; 12323 } 12324 } 12325 12326 try { 12327 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12328 System.currentTimeMillis(), user); 12329 12330 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12331 // delete the partially installed application. the data directory will have to be 12332 // restored if it was already existing 12333 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12334 // remove package from internal structures. Note that we want deletePackageX to 12335 // delete the package data and cache directories that it created in 12336 // scanPackageLocked, unless those directories existed before we even tried to 12337 // install. 12338 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12339 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12340 res.removedInfo, true); 12341 } 12342 12343 } catch (PackageManagerException e) { 12344 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12345 } 12346 12347 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12348 } 12349 12350 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12351 // Can't rotate keys during boot or if sharedUser. 12352 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12353 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12354 return false; 12355 } 12356 // app is using upgradeKeySets; make sure all are valid 12357 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12358 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12359 for (int i = 0; i < upgradeKeySets.length; i++) { 12360 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12361 Slog.wtf(TAG, "Package " 12362 + (oldPs.name != null ? oldPs.name : "<null>") 12363 + " contains upgrade-key-set reference to unknown key-set: " 12364 + upgradeKeySets[i] 12365 + " reverting to signatures check."); 12366 return false; 12367 } 12368 } 12369 return true; 12370 } 12371 12372 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12373 // Upgrade keysets are being used. Determine if new package has a superset of the 12374 // required keys. 12375 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12376 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12377 for (int i = 0; i < upgradeKeySets.length; i++) { 12378 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12379 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12380 return true; 12381 } 12382 } 12383 return false; 12384 } 12385 12386 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12387 UserHandle user, String installerPackageName, String volumeUuid, 12388 PackageInstalledInfo res) { 12389 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12390 12391 final PackageParser.Package oldPackage; 12392 final String pkgName = pkg.packageName; 12393 final int[] allUsers; 12394 final boolean[] perUserInstalled; 12395 12396 // First find the old package info and check signatures 12397 synchronized(mPackages) { 12398 oldPackage = mPackages.get(pkgName); 12399 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12400 if (isEphemeral && !oldIsEphemeral) { 12401 // can't downgrade from full to ephemeral 12402 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12403 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12404 return; 12405 } 12406 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12407 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12408 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12409 if(!checkUpgradeKeySetLP(ps, pkg)) { 12410 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12411 "New package not signed by keys specified by upgrade-keysets: " 12412 + pkgName); 12413 return; 12414 } 12415 } else { 12416 // default to original signature matching 12417 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12418 != PackageManager.SIGNATURE_MATCH) { 12419 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12420 "New package has a different signature: " + pkgName); 12421 return; 12422 } 12423 } 12424 12425 // In case of rollback, remember per-user/profile install state 12426 allUsers = sUserManager.getUserIds(); 12427 perUserInstalled = new boolean[allUsers.length]; 12428 for (int i = 0; i < allUsers.length; i++) { 12429 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12430 } 12431 } 12432 12433 boolean sysPkg = (isSystemApp(oldPackage)); 12434 if (sysPkg) { 12435 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12436 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12437 } else { 12438 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12439 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12440 } 12441 } 12442 12443 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12444 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12445 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12446 String volumeUuid, PackageInstalledInfo res) { 12447 String pkgName = deletedPackage.packageName; 12448 boolean deletedPkg = true; 12449 boolean updatedSettings = false; 12450 12451 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12452 + deletedPackage); 12453 long origUpdateTime; 12454 if (pkg.mExtras != null) { 12455 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12456 } else { 12457 origUpdateTime = 0; 12458 } 12459 12460 // First delete the existing package while retaining the data directory 12461 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12462 res.removedInfo, true)) { 12463 // If the existing package wasn't successfully deleted 12464 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12465 deletedPkg = false; 12466 } else { 12467 // Successfully deleted the old package; proceed with replace. 12468 12469 // If deleted package lived in a container, give users a chance to 12470 // relinquish resources before killing. 12471 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12472 if (DEBUG_INSTALL) { 12473 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12474 } 12475 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12476 final ArrayList<String> pkgList = new ArrayList<String>(1); 12477 pkgList.add(deletedPackage.applicationInfo.packageName); 12478 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12479 } 12480 12481 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12482 try { 12483 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12484 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12485 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12486 perUserInstalled, res, user); 12487 updatedSettings = true; 12488 } catch (PackageManagerException e) { 12489 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12490 } 12491 } 12492 12493 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12494 // remove package from internal structures. Note that we want deletePackageX to 12495 // delete the package data and cache directories that it created in 12496 // scanPackageLocked, unless those directories existed before we even tried to 12497 // install. 12498 if(updatedSettings) { 12499 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12500 deletePackageLI( 12501 pkgName, null, true, allUsers, perUserInstalled, 12502 PackageManager.DELETE_KEEP_DATA, 12503 res.removedInfo, true); 12504 } 12505 // Since we failed to install the new package we need to restore the old 12506 // package that we deleted. 12507 if (deletedPkg) { 12508 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12509 File restoreFile = new File(deletedPackage.codePath); 12510 // Parse old package 12511 boolean oldExternal = isExternal(deletedPackage); 12512 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12513 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12514 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12515 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12516 try { 12517 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12518 null); 12519 } catch (PackageManagerException e) { 12520 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12521 + e.getMessage()); 12522 return; 12523 } 12524 // Restore of old package succeeded. Update permissions. 12525 // writer 12526 synchronized (mPackages) { 12527 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12528 UPDATE_PERMISSIONS_ALL); 12529 // can downgrade to reader 12530 mSettings.writeLPr(); 12531 } 12532 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12533 } 12534 } 12535 } 12536 12537 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12538 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12539 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12540 String volumeUuid, PackageInstalledInfo res) { 12541 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12542 + ", old=" + deletedPackage); 12543 boolean disabledSystem = false; 12544 boolean updatedSettings = false; 12545 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12546 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12547 != 0) { 12548 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12549 } 12550 String packageName = deletedPackage.packageName; 12551 if (packageName == null) { 12552 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12553 "Attempt to delete null packageName."); 12554 return; 12555 } 12556 PackageParser.Package oldPkg; 12557 PackageSetting oldPkgSetting; 12558 // reader 12559 synchronized (mPackages) { 12560 oldPkg = mPackages.get(packageName); 12561 oldPkgSetting = mSettings.mPackages.get(packageName); 12562 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12563 (oldPkgSetting == null)) { 12564 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12565 "Couldn't find package " + packageName + " information"); 12566 return; 12567 } 12568 } 12569 12570 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12571 12572 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12573 res.removedInfo.removedPackage = packageName; 12574 // Remove existing system package 12575 removePackageLI(oldPkgSetting, true); 12576 // writer 12577 synchronized (mPackages) { 12578 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12579 if (!disabledSystem && deletedPackage != null) { 12580 // We didn't need to disable the .apk as a current system package, 12581 // which means we are replacing another update that is already 12582 // installed. We need to make sure to delete the older one's .apk. 12583 res.removedInfo.args = createInstallArgsForExisting(0, 12584 deletedPackage.applicationInfo.getCodePath(), 12585 deletedPackage.applicationInfo.getResourcePath(), 12586 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12587 } else { 12588 res.removedInfo.args = null; 12589 } 12590 } 12591 12592 // Successfully disabled the old package. Now proceed with re-installation 12593 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12594 12595 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12596 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12597 12598 PackageParser.Package newPackage = null; 12599 try { 12600 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12601 if (newPackage.mExtras != null) { 12602 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12603 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12604 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12605 12606 // is the update attempting to change shared user? that isn't going to work... 12607 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12608 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12609 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12610 + " to " + newPkgSetting.sharedUser); 12611 updatedSettings = true; 12612 } 12613 } 12614 12615 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12616 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12617 perUserInstalled, res, user); 12618 updatedSettings = true; 12619 } 12620 12621 } catch (PackageManagerException e) { 12622 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12623 } 12624 12625 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12626 // Re installation failed. Restore old information 12627 // Remove new pkg information 12628 if (newPackage != null) { 12629 removeInstalledPackageLI(newPackage, true); 12630 } 12631 // Add back the old system package 12632 try { 12633 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12634 } catch (PackageManagerException e) { 12635 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12636 } 12637 // Restore the old system information in Settings 12638 synchronized (mPackages) { 12639 if (disabledSystem) { 12640 mSettings.enableSystemPackageLPw(packageName); 12641 } 12642 if (updatedSettings) { 12643 mSettings.setInstallerPackageName(packageName, 12644 oldPkgSetting.installerPackageName); 12645 } 12646 mSettings.writeLPr(); 12647 } 12648 } 12649 } 12650 12651 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12652 // Collect all used permissions in the UID 12653 ArraySet<String> usedPermissions = new ArraySet<>(); 12654 final int packageCount = su.packages.size(); 12655 for (int i = 0; i < packageCount; i++) { 12656 PackageSetting ps = su.packages.valueAt(i); 12657 if (ps.pkg == null) { 12658 continue; 12659 } 12660 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12661 for (int j = 0; j < requestedPermCount; j++) { 12662 String permission = ps.pkg.requestedPermissions.get(j); 12663 BasePermission bp = mSettings.mPermissions.get(permission); 12664 if (bp != null) { 12665 usedPermissions.add(permission); 12666 } 12667 } 12668 } 12669 12670 PermissionsState permissionsState = su.getPermissionsState(); 12671 // Prune install permissions 12672 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12673 final int installPermCount = installPermStates.size(); 12674 for (int i = installPermCount - 1; i >= 0; i--) { 12675 PermissionState permissionState = installPermStates.get(i); 12676 if (!usedPermissions.contains(permissionState.getName())) { 12677 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12678 if (bp != null) { 12679 permissionsState.revokeInstallPermission(bp); 12680 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12681 PackageManager.MASK_PERMISSION_FLAGS, 0); 12682 } 12683 } 12684 } 12685 12686 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12687 12688 // Prune runtime permissions 12689 for (int userId : allUserIds) { 12690 List<PermissionState> runtimePermStates = permissionsState 12691 .getRuntimePermissionStates(userId); 12692 final int runtimePermCount = runtimePermStates.size(); 12693 for (int i = runtimePermCount - 1; i >= 0; i--) { 12694 PermissionState permissionState = runtimePermStates.get(i); 12695 if (!usedPermissions.contains(permissionState.getName())) { 12696 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12697 if (bp != null) { 12698 permissionsState.revokeRuntimePermission(bp, userId); 12699 permissionsState.updatePermissionFlags(bp, userId, 12700 PackageManager.MASK_PERMISSION_FLAGS, 0); 12701 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12702 runtimePermissionChangedUserIds, userId); 12703 } 12704 } 12705 } 12706 } 12707 12708 return runtimePermissionChangedUserIds; 12709 } 12710 12711 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12712 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12713 UserHandle user) { 12714 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12715 12716 String pkgName = newPackage.packageName; 12717 synchronized (mPackages) { 12718 //write settings. the installStatus will be incomplete at this stage. 12719 //note that the new package setting would have already been 12720 //added to mPackages. It hasn't been persisted yet. 12721 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12723 mSettings.writeLPr(); 12724 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12725 } 12726 12727 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12728 synchronized (mPackages) { 12729 updatePermissionsLPw(newPackage.packageName, newPackage, 12730 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12731 ? UPDATE_PERMISSIONS_ALL : 0)); 12732 // For system-bundled packages, we assume that installing an upgraded version 12733 // of the package implies that the user actually wants to run that new code, 12734 // so we enable the package. 12735 PackageSetting ps = mSettings.mPackages.get(pkgName); 12736 if (ps != null) { 12737 if (isSystemApp(newPackage)) { 12738 // NB: implicit assumption that system package upgrades apply to all users 12739 if (DEBUG_INSTALL) { 12740 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12741 } 12742 if (res.origUsers != null) { 12743 for (int userHandle : res.origUsers) { 12744 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12745 userHandle, installerPackageName); 12746 } 12747 } 12748 // Also convey the prior install/uninstall state 12749 if (allUsers != null && perUserInstalled != null) { 12750 for (int i = 0; i < allUsers.length; i++) { 12751 if (DEBUG_INSTALL) { 12752 Slog.d(TAG, " user " + allUsers[i] 12753 + " => " + perUserInstalled[i]); 12754 } 12755 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12756 } 12757 // these install state changes will be persisted in the 12758 // upcoming call to mSettings.writeLPr(). 12759 } 12760 } 12761 // It's implied that when a user requests installation, they want the app to be 12762 // installed and enabled. 12763 int userId = user.getIdentifier(); 12764 if (userId != UserHandle.USER_ALL) { 12765 ps.setInstalled(true, userId); 12766 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12767 } 12768 } 12769 res.name = pkgName; 12770 res.uid = newPackage.applicationInfo.uid; 12771 res.pkg = newPackage; 12772 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12773 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12774 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12775 //to update install status 12776 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12777 mSettings.writeLPr(); 12778 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12779 } 12780 12781 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12782 } 12783 12784 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12785 try { 12786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12787 installPackageLI(args, res); 12788 } finally { 12789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12790 } 12791 } 12792 12793 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12794 final int installFlags = args.installFlags; 12795 final String installerPackageName = args.installerPackageName; 12796 final String volumeUuid = args.volumeUuid; 12797 final File tmpPackageFile = new File(args.getCodePath()); 12798 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12799 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12800 || (args.volumeUuid != null)); 12801 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12802 boolean replace = false; 12803 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12804 if (args.move != null) { 12805 // moving a complete application; perfom an initial scan on the new install location 12806 scanFlags |= SCAN_INITIAL; 12807 } 12808 // Result object to be returned 12809 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12810 12811 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12812 12813 // Sanity check 12814 if (ephemeral && (forwardLocked || onExternal)) { 12815 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12816 + " external=" + onExternal); 12817 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12818 return; 12819 } 12820 12821 // Retrieve PackageSettings and parse package 12822 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12823 | PackageParser.PARSE_ENFORCE_CODE 12824 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12825 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12826 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12827 PackageParser pp = new PackageParser(); 12828 pp.setSeparateProcesses(mSeparateProcesses); 12829 pp.setDisplayMetrics(mMetrics); 12830 12831 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12832 final PackageParser.Package pkg; 12833 try { 12834 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12835 } catch (PackageParserException e) { 12836 res.setError("Failed parse during installPackageLI", e); 12837 return; 12838 } finally { 12839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12840 } 12841 12842 // Mark that we have an install time CPU ABI override. 12843 pkg.cpuAbiOverride = args.abiOverride; 12844 12845 String pkgName = res.name = pkg.packageName; 12846 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12847 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12848 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12849 return; 12850 } 12851 } 12852 12853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12854 try { 12855 pp.collectCertificates(pkg, parseFlags); 12856 } catch (PackageParserException e) { 12857 res.setError("Failed collect during installPackageLI", e); 12858 return; 12859 } finally { 12860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12861 } 12862 12863 // Get rid of all references to package scan path via parser. 12864 pp = null; 12865 String oldCodePath = null; 12866 boolean systemApp = false; 12867 synchronized (mPackages) { 12868 // Check if installing already existing package 12869 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12870 String oldName = mSettings.mRenamedPackages.get(pkgName); 12871 if (pkg.mOriginalPackages != null 12872 && pkg.mOriginalPackages.contains(oldName) 12873 && mPackages.containsKey(oldName)) { 12874 // This package is derived from an original package, 12875 // and this device has been updating from that original 12876 // name. We must continue using the original name, so 12877 // rename the new package here. 12878 pkg.setPackageName(oldName); 12879 pkgName = pkg.packageName; 12880 replace = true; 12881 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12882 + oldName + " pkgName=" + pkgName); 12883 } else if (mPackages.containsKey(pkgName)) { 12884 // This package, under its official name, already exists 12885 // on the device; we should replace it. 12886 replace = true; 12887 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12888 } 12889 12890 // Prevent apps opting out from runtime permissions 12891 if (replace) { 12892 PackageParser.Package oldPackage = mPackages.get(pkgName); 12893 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12894 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12895 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12896 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12897 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12898 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12899 + " doesn't support runtime permissions but the old" 12900 + " target SDK " + oldTargetSdk + " does."); 12901 return; 12902 } 12903 } 12904 } 12905 12906 PackageSetting ps = mSettings.mPackages.get(pkgName); 12907 if (ps != null) { 12908 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12909 12910 // Quick sanity check that we're signed correctly if updating; 12911 // we'll check this again later when scanning, but we want to 12912 // bail early here before tripping over redefined permissions. 12913 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12914 if (!checkUpgradeKeySetLP(ps, pkg)) { 12915 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12916 + pkg.packageName + " upgrade keys do not match the " 12917 + "previously installed version"); 12918 return; 12919 } 12920 } else { 12921 try { 12922 verifySignaturesLP(ps, pkg); 12923 } catch (PackageManagerException e) { 12924 res.setError(e.error, e.getMessage()); 12925 return; 12926 } 12927 } 12928 12929 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12930 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12931 systemApp = (ps.pkg.applicationInfo.flags & 12932 ApplicationInfo.FLAG_SYSTEM) != 0; 12933 } 12934 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12935 } 12936 12937 // Check whether the newly-scanned package wants to define an already-defined perm 12938 int N = pkg.permissions.size(); 12939 for (int i = N-1; i >= 0; i--) { 12940 PackageParser.Permission perm = pkg.permissions.get(i); 12941 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12942 if (bp != null) { 12943 // If the defining package is signed with our cert, it's okay. This 12944 // also includes the "updating the same package" case, of course. 12945 // "updating same package" could also involve key-rotation. 12946 final boolean sigsOk; 12947 if (bp.sourcePackage.equals(pkg.packageName) 12948 && (bp.packageSetting instanceof PackageSetting) 12949 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12950 scanFlags))) { 12951 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12952 } else { 12953 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12954 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12955 } 12956 if (!sigsOk) { 12957 // If the owning package is the system itself, we log but allow 12958 // install to proceed; we fail the install on all other permission 12959 // redefinitions. 12960 if (!bp.sourcePackage.equals("android")) { 12961 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12962 + pkg.packageName + " attempting to redeclare permission " 12963 + perm.info.name + " already owned by " + bp.sourcePackage); 12964 res.origPermission = perm.info.name; 12965 res.origPackage = bp.sourcePackage; 12966 return; 12967 } else { 12968 Slog.w(TAG, "Package " + pkg.packageName 12969 + " attempting to redeclare system permission " 12970 + perm.info.name + "; ignoring new declaration"); 12971 pkg.permissions.remove(i); 12972 } 12973 } 12974 } 12975 } 12976 12977 } 12978 12979 if (systemApp) { 12980 if (onExternal) { 12981 // Abort update; system app can't be replaced with app on sdcard 12982 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12983 "Cannot install updates to system apps on sdcard"); 12984 return; 12985 } else if (ephemeral) { 12986 // Abort update; system app can't be replaced with an ephemeral app 12987 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12988 "Cannot update a system app with an ephemeral app"); 12989 return; 12990 } 12991 } 12992 12993 if (args.move != null) { 12994 // We did an in-place move, so dex is ready to roll 12995 scanFlags |= SCAN_NO_DEX; 12996 scanFlags |= SCAN_MOVE; 12997 12998 synchronized (mPackages) { 12999 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13000 if (ps == null) { 13001 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13002 "Missing settings for moved package " + pkgName); 13003 } 13004 13005 // We moved the entire application as-is, so bring over the 13006 // previously derived ABI information. 13007 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13008 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13009 } 13010 13011 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13012 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13013 scanFlags |= SCAN_NO_DEX; 13014 13015 try { 13016 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13017 true /* extract libs */); 13018 } catch (PackageManagerException pme) { 13019 Slog.e(TAG, "Error deriving application ABI", pme); 13020 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13021 return; 13022 } 13023 } 13024 13025 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13026 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13027 return; 13028 } 13029 13030 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13031 13032 if (replace) { 13033 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13034 installerPackageName, volumeUuid, res); 13035 } else { 13036 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13037 args.user, installerPackageName, volumeUuid, res); 13038 } 13039 synchronized (mPackages) { 13040 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13041 if (ps != null) { 13042 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13043 } 13044 } 13045 } 13046 13047 private void startIntentFilterVerifications(int userId, boolean replacing, 13048 PackageParser.Package pkg) { 13049 if (mIntentFilterVerifierComponent == null) { 13050 Slog.w(TAG, "No IntentFilter verification will not be done as " 13051 + "there is no IntentFilterVerifier available!"); 13052 return; 13053 } 13054 13055 final int verifierUid = getPackageUid( 13056 mIntentFilterVerifierComponent.getPackageName(), 13057 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13058 13059 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13060 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13061 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13062 mHandler.sendMessage(msg); 13063 } 13064 13065 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13066 PackageParser.Package pkg) { 13067 int size = pkg.activities.size(); 13068 if (size == 0) { 13069 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13070 "No activity, so no need to verify any IntentFilter!"); 13071 return; 13072 } 13073 13074 final boolean hasDomainURLs = hasDomainURLs(pkg); 13075 if (!hasDomainURLs) { 13076 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13077 "No domain URLs, so no need to verify any IntentFilter!"); 13078 return; 13079 } 13080 13081 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13082 + " if any IntentFilter from the " + size 13083 + " Activities needs verification ..."); 13084 13085 int count = 0; 13086 final String packageName = pkg.packageName; 13087 13088 synchronized (mPackages) { 13089 // If this is a new install and we see that we've already run verification for this 13090 // package, we have nothing to do: it means the state was restored from backup. 13091 if (!replacing) { 13092 IntentFilterVerificationInfo ivi = 13093 mSettings.getIntentFilterVerificationLPr(packageName); 13094 if (ivi != null) { 13095 if (DEBUG_DOMAIN_VERIFICATION) { 13096 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13097 + ivi.getStatusString()); 13098 } 13099 return; 13100 } 13101 } 13102 13103 // If any filters need to be verified, then all need to be. 13104 boolean needToVerify = false; 13105 for (PackageParser.Activity a : pkg.activities) { 13106 for (ActivityIntentInfo filter : a.intents) { 13107 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13108 if (DEBUG_DOMAIN_VERIFICATION) { 13109 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13110 } 13111 needToVerify = true; 13112 break; 13113 } 13114 } 13115 } 13116 13117 if (needToVerify) { 13118 final int verificationId = mIntentFilterVerificationToken++; 13119 for (PackageParser.Activity a : pkg.activities) { 13120 for (ActivityIntentInfo filter : a.intents) { 13121 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13122 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13123 "Verification needed for IntentFilter:" + filter.toString()); 13124 mIntentFilterVerifier.addOneIntentFilterVerification( 13125 verifierUid, userId, verificationId, filter, packageName); 13126 count++; 13127 } 13128 } 13129 } 13130 } 13131 } 13132 13133 if (count > 0) { 13134 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13135 + " IntentFilter verification" + (count > 1 ? "s" : "") 13136 + " for userId:" + userId); 13137 mIntentFilterVerifier.startVerifications(userId); 13138 } else { 13139 if (DEBUG_DOMAIN_VERIFICATION) { 13140 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13141 } 13142 } 13143 } 13144 13145 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13146 final ComponentName cn = filter.activity.getComponentName(); 13147 final String packageName = cn.getPackageName(); 13148 13149 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13150 packageName); 13151 if (ivi == null) { 13152 return true; 13153 } 13154 int status = ivi.getStatus(); 13155 switch (status) { 13156 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13157 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13158 return true; 13159 13160 default: 13161 // Nothing to do 13162 return false; 13163 } 13164 } 13165 13166 private static boolean isMultiArch(ApplicationInfo info) { 13167 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13168 } 13169 13170 private static boolean isExternal(PackageParser.Package pkg) { 13171 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13172 } 13173 13174 private static boolean isExternal(PackageSetting ps) { 13175 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13176 } 13177 13178 private static boolean isEphemeral(PackageParser.Package pkg) { 13179 return pkg.applicationInfo.isEphemeralApp(); 13180 } 13181 13182 private static boolean isEphemeral(PackageSetting ps) { 13183 return ps.pkg != null && isEphemeral(ps.pkg); 13184 } 13185 13186 private static boolean isSystemApp(PackageParser.Package pkg) { 13187 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13188 } 13189 13190 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13191 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13192 } 13193 13194 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13195 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13196 } 13197 13198 private static boolean isSystemApp(PackageSetting ps) { 13199 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13200 } 13201 13202 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13203 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13204 } 13205 13206 private int packageFlagsToInstallFlags(PackageSetting ps) { 13207 int installFlags = 0; 13208 if (isEphemeral(ps)) { 13209 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13210 } 13211 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13212 // This existing package was an external ASEC install when we have 13213 // the external flag without a UUID 13214 installFlags |= PackageManager.INSTALL_EXTERNAL; 13215 } 13216 if (ps.isForwardLocked()) { 13217 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13218 } 13219 return installFlags; 13220 } 13221 13222 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13223 if (isExternal(pkg)) { 13224 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13225 return StorageManager.UUID_PRIMARY_PHYSICAL; 13226 } else { 13227 return pkg.volumeUuid; 13228 } 13229 } else { 13230 return StorageManager.UUID_PRIVATE_INTERNAL; 13231 } 13232 } 13233 13234 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13235 if (isExternal(pkg)) { 13236 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13237 return mSettings.getExternalVersion(); 13238 } else { 13239 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13240 } 13241 } else { 13242 return mSettings.getInternalVersion(); 13243 } 13244 } 13245 13246 private void deleteTempPackageFiles() { 13247 final FilenameFilter filter = new FilenameFilter() { 13248 public boolean accept(File dir, String name) { 13249 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13250 } 13251 }; 13252 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13253 file.delete(); 13254 } 13255 } 13256 13257 @Override 13258 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13259 int flags) { 13260 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13261 flags); 13262 } 13263 13264 @Override 13265 public void deletePackage(final String packageName, 13266 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13267 mContext.enforceCallingOrSelfPermission( 13268 android.Manifest.permission.DELETE_PACKAGES, null); 13269 Preconditions.checkNotNull(packageName); 13270 Preconditions.checkNotNull(observer); 13271 final int uid = Binder.getCallingUid(); 13272 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13273 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13274 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13275 mContext.enforceCallingOrSelfPermission( 13276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13277 "deletePackage for user " + userId); 13278 } 13279 13280 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13281 try { 13282 observer.onPackageDeleted(packageName, 13283 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13284 } catch (RemoteException re) { 13285 } 13286 return; 13287 } 13288 13289 for (int currentUserId : users) { 13290 if (getBlockUninstallForUser(packageName, currentUserId)) { 13291 try { 13292 observer.onPackageDeleted(packageName, 13293 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13294 } catch (RemoteException re) { 13295 } 13296 return; 13297 } 13298 } 13299 13300 if (DEBUG_REMOVE) { 13301 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13302 } 13303 // Queue up an async operation since the package deletion may take a little while. 13304 mHandler.post(new Runnable() { 13305 public void run() { 13306 mHandler.removeCallbacks(this); 13307 final int returnCode = deletePackageX(packageName, userId, flags); 13308 try { 13309 observer.onPackageDeleted(packageName, returnCode, null); 13310 } catch (RemoteException e) { 13311 Log.i(TAG, "Observer no longer exists."); 13312 } //end catch 13313 } //end run 13314 }); 13315 } 13316 13317 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13318 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13319 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13320 try { 13321 if (dpm != null) { 13322 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13323 /* callingUserOnly =*/ false); 13324 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13325 : deviceOwnerComponentName.getPackageName(); 13326 // Does the package contains the device owner? 13327 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13328 // this check is probably not needed, since DO should be registered as a device 13329 // admin on some user too. (Original bug for this: b/17657954) 13330 if (packageName.equals(deviceOwnerPackageName)) { 13331 return true; 13332 } 13333 // Does it contain a device admin for any user? 13334 int[] users; 13335 if (userId == UserHandle.USER_ALL) { 13336 users = sUserManager.getUserIds(); 13337 } else { 13338 users = new int[]{userId}; 13339 } 13340 for (int i = 0; i < users.length; ++i) { 13341 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13342 return true; 13343 } 13344 } 13345 } 13346 } catch (RemoteException e) { 13347 } 13348 return false; 13349 } 13350 13351 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13352 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13353 } 13354 13355 /** 13356 * This method is an internal method that could be get invoked either 13357 * to delete an installed package or to clean up a failed installation. 13358 * After deleting an installed package, a broadcast is sent to notify any 13359 * listeners that the package has been installed. For cleaning up a failed 13360 * installation, the broadcast is not necessary since the package's 13361 * installation wouldn't have sent the initial broadcast either 13362 * The key steps in deleting a package are 13363 * deleting the package information in internal structures like mPackages, 13364 * deleting the packages base directories through installd 13365 * updating mSettings to reflect current status 13366 * persisting settings for later use 13367 * sending a broadcast if necessary 13368 */ 13369 private int deletePackageX(String packageName, int userId, int flags) { 13370 final PackageRemovedInfo info = new PackageRemovedInfo(); 13371 final boolean res; 13372 13373 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13374 ? UserHandle.ALL : new UserHandle(userId); 13375 13376 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13377 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13378 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13379 } 13380 13381 boolean removedForAllUsers = false; 13382 boolean systemUpdate = false; 13383 13384 PackageParser.Package uninstalledPkg; 13385 13386 // for the uninstall-updates case and restricted profiles, remember the per- 13387 // userhandle installed state 13388 int[] allUsers; 13389 boolean[] perUserInstalled; 13390 synchronized (mPackages) { 13391 uninstalledPkg = mPackages.get(packageName); 13392 PackageSetting ps = mSettings.mPackages.get(packageName); 13393 allUsers = sUserManager.getUserIds(); 13394 perUserInstalled = new boolean[allUsers.length]; 13395 for (int i = 0; i < allUsers.length; i++) { 13396 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13397 } 13398 } 13399 13400 synchronized (mInstallLock) { 13401 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13402 res = deletePackageLI(packageName, removeForUser, 13403 true, allUsers, perUserInstalled, 13404 flags | REMOVE_CHATTY, info, true); 13405 systemUpdate = info.isRemovedPackageSystemUpdate; 13406 synchronized (mPackages) { 13407 if (res) { 13408 if (!systemUpdate && mPackages.get(packageName) == null) { 13409 removedForAllUsers = true; 13410 } 13411 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13412 } 13413 } 13414 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13415 + " removedForAllUsers=" + removedForAllUsers); 13416 } 13417 13418 if (res) { 13419 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13420 13421 // If the removed package was a system update, the old system package 13422 // was re-enabled; we need to broadcast this information 13423 if (systemUpdate) { 13424 Bundle extras = new Bundle(1); 13425 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13426 ? info.removedAppId : info.uid); 13427 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13428 13429 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13430 extras, 0, null, null, null); 13431 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13432 extras, 0, null, null, null); 13433 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13434 null, 0, packageName, null, null); 13435 } 13436 } 13437 // Force a gc here. 13438 Runtime.getRuntime().gc(); 13439 // Delete the resources here after sending the broadcast to let 13440 // other processes clean up before deleting resources. 13441 if (info.args != null) { 13442 synchronized (mInstallLock) { 13443 info.args.doPostDeleteLI(true); 13444 } 13445 } 13446 13447 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13448 } 13449 13450 class PackageRemovedInfo { 13451 String removedPackage; 13452 int uid = -1; 13453 int removedAppId = -1; 13454 int[] removedUsers = null; 13455 boolean isRemovedPackageSystemUpdate = false; 13456 // Clean up resources deleted packages. 13457 InstallArgs args = null; 13458 13459 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13460 Bundle extras = new Bundle(1); 13461 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13462 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13463 if (replacing) { 13464 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13465 } 13466 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13467 if (removedPackage != null) { 13468 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13469 extras, 0, null, null, removedUsers); 13470 if (fullRemove && !replacing) { 13471 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13472 extras, 0, null, null, removedUsers); 13473 } 13474 } 13475 if (removedAppId >= 0) { 13476 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13477 removedUsers); 13478 } 13479 } 13480 } 13481 13482 /* 13483 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13484 * flag is not set, the data directory is removed as well. 13485 * make sure this flag is set for partially installed apps. If not its meaningless to 13486 * delete a partially installed application. 13487 */ 13488 private void removePackageDataLI(PackageSetting ps, 13489 int[] allUserHandles, boolean[] perUserInstalled, 13490 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13491 String packageName = ps.name; 13492 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13493 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13494 // Retrieve object to delete permissions for shared user later on 13495 final PackageSetting deletedPs; 13496 // reader 13497 synchronized (mPackages) { 13498 deletedPs = mSettings.mPackages.get(packageName); 13499 if (outInfo != null) { 13500 outInfo.removedPackage = packageName; 13501 outInfo.removedUsers = deletedPs != null 13502 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13503 : null; 13504 } 13505 } 13506 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13507 removeDataDirsLI(ps.volumeUuid, packageName); 13508 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13509 } 13510 // writer 13511 synchronized (mPackages) { 13512 if (deletedPs != null) { 13513 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13514 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13515 clearDefaultBrowserIfNeeded(packageName); 13516 if (outInfo != null) { 13517 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13518 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13519 } 13520 updatePermissionsLPw(deletedPs.name, null, 0); 13521 if (deletedPs.sharedUser != null) { 13522 // Remove permissions associated with package. Since runtime 13523 // permissions are per user we have to kill the removed package 13524 // or packages running under the shared user of the removed 13525 // package if revoking the permissions requested only by the removed 13526 // package is successful and this causes a change in gids. 13527 for (int userId : UserManagerService.getInstance().getUserIds()) { 13528 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13529 userId); 13530 if (userIdToKill == UserHandle.USER_ALL 13531 || userIdToKill >= UserHandle.USER_SYSTEM) { 13532 // If gids changed for this user, kill all affected packages. 13533 mHandler.post(new Runnable() { 13534 @Override 13535 public void run() { 13536 // This has to happen with no lock held. 13537 killApplication(deletedPs.name, deletedPs.appId, 13538 KILL_APP_REASON_GIDS_CHANGED); 13539 } 13540 }); 13541 break; 13542 } 13543 } 13544 } 13545 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13546 } 13547 // make sure to preserve per-user disabled state if this removal was just 13548 // a downgrade of a system app to the factory package 13549 if (allUserHandles != null && perUserInstalled != null) { 13550 if (DEBUG_REMOVE) { 13551 Slog.d(TAG, "Propagating install state across downgrade"); 13552 } 13553 for (int i = 0; i < allUserHandles.length; i++) { 13554 if (DEBUG_REMOVE) { 13555 Slog.d(TAG, " user " + allUserHandles[i] 13556 + " => " + perUserInstalled[i]); 13557 } 13558 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13559 } 13560 } 13561 } 13562 // can downgrade to reader 13563 if (writeSettings) { 13564 // Save settings now 13565 mSettings.writeLPr(); 13566 } 13567 } 13568 if (outInfo != null) { 13569 // A user ID was deleted here. Go through all users and remove it 13570 // from KeyStore. 13571 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13572 } 13573 } 13574 13575 static boolean locationIsPrivileged(File path) { 13576 try { 13577 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13578 .getCanonicalPath(); 13579 return path.getCanonicalPath().startsWith(privilegedAppDir); 13580 } catch (IOException e) { 13581 Slog.e(TAG, "Unable to access code path " + path); 13582 } 13583 return false; 13584 } 13585 13586 /* 13587 * Tries to delete system package. 13588 */ 13589 private boolean deleteSystemPackageLI(PackageSetting newPs, 13590 int[] allUserHandles, boolean[] perUserInstalled, 13591 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13592 final boolean applyUserRestrictions 13593 = (allUserHandles != null) && (perUserInstalled != null); 13594 PackageSetting disabledPs = null; 13595 // Confirm if the system package has been updated 13596 // An updated system app can be deleted. This will also have to restore 13597 // the system pkg from system partition 13598 // reader 13599 synchronized (mPackages) { 13600 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13601 } 13602 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13603 + " disabledPs=" + disabledPs); 13604 if (disabledPs == null) { 13605 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13606 return false; 13607 } else if (DEBUG_REMOVE) { 13608 Slog.d(TAG, "Deleting system pkg from data partition"); 13609 } 13610 if (DEBUG_REMOVE) { 13611 if (applyUserRestrictions) { 13612 Slog.d(TAG, "Remembering install states:"); 13613 for (int i = 0; i < allUserHandles.length; i++) { 13614 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13615 } 13616 } 13617 } 13618 // Delete the updated package 13619 outInfo.isRemovedPackageSystemUpdate = true; 13620 if (disabledPs.versionCode < newPs.versionCode) { 13621 // Delete data for downgrades 13622 flags &= ~PackageManager.DELETE_KEEP_DATA; 13623 } else { 13624 // Preserve data by setting flag 13625 flags |= PackageManager.DELETE_KEEP_DATA; 13626 } 13627 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13628 allUserHandles, perUserInstalled, outInfo, writeSettings); 13629 if (!ret) { 13630 return false; 13631 } 13632 // writer 13633 synchronized (mPackages) { 13634 // Reinstate the old system package 13635 mSettings.enableSystemPackageLPw(newPs.name); 13636 // Remove any native libraries from the upgraded package. 13637 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13638 } 13639 // Install the system package 13640 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13641 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13642 if (locationIsPrivileged(disabledPs.codePath)) { 13643 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13644 } 13645 13646 final PackageParser.Package newPkg; 13647 try { 13648 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13649 } catch (PackageManagerException e) { 13650 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13651 return false; 13652 } 13653 13654 // writer 13655 synchronized (mPackages) { 13656 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13657 13658 // Propagate the permissions state as we do not want to drop on the floor 13659 // runtime permissions. The update permissions method below will take 13660 // care of removing obsolete permissions and grant install permissions. 13661 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13662 updatePermissionsLPw(newPkg.packageName, newPkg, 13663 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13664 13665 if (applyUserRestrictions) { 13666 if (DEBUG_REMOVE) { 13667 Slog.d(TAG, "Propagating install state across reinstall"); 13668 } 13669 for (int i = 0; i < allUserHandles.length; i++) { 13670 if (DEBUG_REMOVE) { 13671 Slog.d(TAG, " user " + allUserHandles[i] 13672 + " => " + perUserInstalled[i]); 13673 } 13674 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13675 13676 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13677 } 13678 // Regardless of writeSettings we need to ensure that this restriction 13679 // state propagation is persisted 13680 mSettings.writeAllUsersPackageRestrictionsLPr(); 13681 } 13682 // can downgrade to reader here 13683 if (writeSettings) { 13684 mSettings.writeLPr(); 13685 } 13686 } 13687 return true; 13688 } 13689 13690 private boolean deleteInstalledPackageLI(PackageSetting ps, 13691 boolean deleteCodeAndResources, int flags, 13692 int[] allUserHandles, boolean[] perUserInstalled, 13693 PackageRemovedInfo outInfo, boolean writeSettings) { 13694 if (outInfo != null) { 13695 outInfo.uid = ps.appId; 13696 } 13697 13698 // Delete package data from internal structures and also remove data if flag is set 13699 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13700 13701 // Delete application code and resources 13702 if (deleteCodeAndResources && (outInfo != null)) { 13703 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13704 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13705 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13706 } 13707 return true; 13708 } 13709 13710 @Override 13711 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13712 int userId) { 13713 mContext.enforceCallingOrSelfPermission( 13714 android.Manifest.permission.DELETE_PACKAGES, null); 13715 synchronized (mPackages) { 13716 PackageSetting ps = mSettings.mPackages.get(packageName); 13717 if (ps == null) { 13718 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13719 return false; 13720 } 13721 if (!ps.getInstalled(userId)) { 13722 // Can't block uninstall for an app that is not installed or enabled. 13723 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13724 return false; 13725 } 13726 ps.setBlockUninstall(blockUninstall, userId); 13727 mSettings.writePackageRestrictionsLPr(userId); 13728 } 13729 return true; 13730 } 13731 13732 @Override 13733 public boolean getBlockUninstallForUser(String packageName, int userId) { 13734 synchronized (mPackages) { 13735 PackageSetting ps = mSettings.mPackages.get(packageName); 13736 if (ps == null) { 13737 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13738 return false; 13739 } 13740 return ps.getBlockUninstall(userId); 13741 } 13742 } 13743 13744 @Override 13745 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13746 int callingUid = Binder.getCallingUid(); 13747 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13748 throw new SecurityException( 13749 "setRequiredForSystemUser can only be run by the system or root"); 13750 } 13751 synchronized (mPackages) { 13752 PackageSetting ps = mSettings.mPackages.get(packageName); 13753 if (ps == null) { 13754 Log.w(TAG, "Package doesn't exist: " + packageName); 13755 return false; 13756 } 13757 if (systemUserApp) { 13758 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13759 } else { 13760 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13761 } 13762 mSettings.writeLPr(); 13763 } 13764 return true; 13765 } 13766 13767 /* 13768 * This method handles package deletion in general 13769 */ 13770 private boolean deletePackageLI(String packageName, UserHandle user, 13771 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13772 int flags, PackageRemovedInfo outInfo, 13773 boolean writeSettings) { 13774 if (packageName == null) { 13775 Slog.w(TAG, "Attempt to delete null packageName."); 13776 return false; 13777 } 13778 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13779 PackageSetting ps; 13780 boolean dataOnly = false; 13781 int removeUser = -1; 13782 int appId = -1; 13783 synchronized (mPackages) { 13784 ps = mSettings.mPackages.get(packageName); 13785 if (ps == null) { 13786 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13787 return false; 13788 } 13789 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13790 && user.getIdentifier() != UserHandle.USER_ALL) { 13791 // The caller is asking that the package only be deleted for a single 13792 // user. To do this, we just mark its uninstalled state and delete 13793 // its data. If this is a system app, we only allow this to happen if 13794 // they have set the special DELETE_SYSTEM_APP which requests different 13795 // semantics than normal for uninstalling system apps. 13796 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13797 final int userId = user.getIdentifier(); 13798 ps.setUserState(userId, 13799 COMPONENT_ENABLED_STATE_DEFAULT, 13800 false, //installed 13801 true, //stopped 13802 true, //notLaunched 13803 false, //hidden 13804 false, //suspended 13805 null, null, null, 13806 false, // blockUninstall 13807 ps.readUserState(userId).domainVerificationStatus, 0); 13808 if (!isSystemApp(ps)) { 13809 // Do not uninstall the APK if an app should be cached 13810 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13811 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13812 // Other user still have this package installed, so all 13813 // we need to do is clear this user's data and save that 13814 // it is uninstalled. 13815 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13816 removeUser = user.getIdentifier(); 13817 appId = ps.appId; 13818 scheduleWritePackageRestrictionsLocked(removeUser); 13819 } else { 13820 // We need to set it back to 'installed' so the uninstall 13821 // broadcasts will be sent correctly. 13822 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13823 ps.setInstalled(true, user.getIdentifier()); 13824 } 13825 } else { 13826 // This is a system app, so we assume that the 13827 // other users still have this package installed, so all 13828 // we need to do is clear this user's data and save that 13829 // it is uninstalled. 13830 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13831 removeUser = user.getIdentifier(); 13832 appId = ps.appId; 13833 scheduleWritePackageRestrictionsLocked(removeUser); 13834 } 13835 } 13836 } 13837 13838 if (removeUser >= 0) { 13839 // From above, we determined that we are deleting this only 13840 // for a single user. Continue the work here. 13841 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13842 if (outInfo != null) { 13843 outInfo.removedPackage = packageName; 13844 outInfo.removedAppId = appId; 13845 outInfo.removedUsers = new int[] {removeUser}; 13846 } 13847 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13848 removeKeystoreDataIfNeeded(removeUser, appId); 13849 schedulePackageCleaning(packageName, removeUser, false); 13850 synchronized (mPackages) { 13851 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13852 scheduleWritePackageRestrictionsLocked(removeUser); 13853 } 13854 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13855 } 13856 return true; 13857 } 13858 13859 if (dataOnly) { 13860 // Delete application data first 13861 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13862 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13863 return true; 13864 } 13865 13866 boolean ret = false; 13867 if (isSystemApp(ps)) { 13868 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13869 // When an updated system application is deleted we delete the existing resources as well and 13870 // fall back to existing code in system partition 13871 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13872 flags, outInfo, writeSettings); 13873 } else { 13874 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13875 // Kill application pre-emptively especially for apps on sd. 13876 killApplication(packageName, ps.appId, "uninstall pkg"); 13877 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13878 allUserHandles, perUserInstalled, 13879 outInfo, writeSettings); 13880 } 13881 13882 return ret; 13883 } 13884 13885 private final static class ClearStorageConnection implements ServiceConnection { 13886 IMediaContainerService mContainerService; 13887 13888 @Override 13889 public void onServiceConnected(ComponentName name, IBinder service) { 13890 synchronized (this) { 13891 mContainerService = IMediaContainerService.Stub.asInterface(service); 13892 notifyAll(); 13893 } 13894 } 13895 13896 @Override 13897 public void onServiceDisconnected(ComponentName name) { 13898 } 13899 } 13900 13901 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13902 final boolean mounted; 13903 if (Environment.isExternalStorageEmulated()) { 13904 mounted = true; 13905 } else { 13906 final String status = Environment.getExternalStorageState(); 13907 13908 mounted = status.equals(Environment.MEDIA_MOUNTED) 13909 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13910 } 13911 13912 if (!mounted) { 13913 return; 13914 } 13915 13916 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13917 int[] users; 13918 if (userId == UserHandle.USER_ALL) { 13919 users = sUserManager.getUserIds(); 13920 } else { 13921 users = new int[] { userId }; 13922 } 13923 final ClearStorageConnection conn = new ClearStorageConnection(); 13924 if (mContext.bindServiceAsUser( 13925 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13926 try { 13927 for (int curUser : users) { 13928 long timeout = SystemClock.uptimeMillis() + 5000; 13929 synchronized (conn) { 13930 long now = SystemClock.uptimeMillis(); 13931 while (conn.mContainerService == null && now < timeout) { 13932 try { 13933 conn.wait(timeout - now); 13934 } catch (InterruptedException e) { 13935 } 13936 } 13937 } 13938 if (conn.mContainerService == null) { 13939 return; 13940 } 13941 13942 final UserEnvironment userEnv = new UserEnvironment(curUser); 13943 clearDirectory(conn.mContainerService, 13944 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13945 if (allData) { 13946 clearDirectory(conn.mContainerService, 13947 userEnv.buildExternalStorageAppDataDirs(packageName)); 13948 clearDirectory(conn.mContainerService, 13949 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13950 } 13951 } 13952 } finally { 13953 mContext.unbindService(conn); 13954 } 13955 } 13956 } 13957 13958 @Override 13959 public void clearApplicationUserData(final String packageName, 13960 final IPackageDataObserver observer, final int userId) { 13961 mContext.enforceCallingOrSelfPermission( 13962 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13963 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13964 // Queue up an async operation since the package deletion may take a little while. 13965 mHandler.post(new Runnable() { 13966 public void run() { 13967 mHandler.removeCallbacks(this); 13968 final boolean succeeded; 13969 synchronized (mInstallLock) { 13970 succeeded = clearApplicationUserDataLI(packageName, userId); 13971 } 13972 clearExternalStorageDataSync(packageName, userId, true); 13973 if (succeeded) { 13974 // invoke DeviceStorageMonitor's update method to clear any notifications 13975 DeviceStorageMonitorInternal 13976 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13977 if (dsm != null) { 13978 dsm.checkMemory(); 13979 } 13980 } 13981 if(observer != null) { 13982 try { 13983 observer.onRemoveCompleted(packageName, succeeded); 13984 } catch (RemoteException e) { 13985 Log.i(TAG, "Observer no longer exists."); 13986 } 13987 } //end if observer 13988 } //end run 13989 }); 13990 } 13991 13992 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13993 if (packageName == null) { 13994 Slog.w(TAG, "Attempt to delete null packageName."); 13995 return false; 13996 } 13997 13998 // Try finding details about the requested package 13999 PackageParser.Package pkg; 14000 synchronized (mPackages) { 14001 pkg = mPackages.get(packageName); 14002 if (pkg == null) { 14003 final PackageSetting ps = mSettings.mPackages.get(packageName); 14004 if (ps != null) { 14005 pkg = ps.pkg; 14006 } 14007 } 14008 14009 if (pkg == null) { 14010 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14011 return false; 14012 } 14013 14014 PackageSetting ps = (PackageSetting) pkg.mExtras; 14015 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14016 } 14017 14018 // Always delete data directories for package, even if we found no other 14019 // record of app. This helps users recover from UID mismatches without 14020 // resorting to a full data wipe. 14021 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14022 if (retCode < 0) { 14023 Slog.w(TAG, "Couldn't remove cache files for package " + packageName); 14024 return false; 14025 } 14026 14027 final int appId = pkg.applicationInfo.uid; 14028 removeKeystoreDataIfNeeded(userId, appId); 14029 14030 // Create a native library symlink only if we have native libraries 14031 // and if the native libraries are 32 bit libraries. We do not provide 14032 // this symlink for 64 bit libraries. 14033 if (pkg.applicationInfo.primaryCpuAbi != null && 14034 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14035 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14036 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14037 nativeLibPath, userId) < 0) { 14038 Slog.w(TAG, "Failed linking native library dir"); 14039 return false; 14040 } 14041 } 14042 14043 return true; 14044 } 14045 14046 /** 14047 * Reverts user permission state changes (permissions and flags) in 14048 * all packages for a given user. 14049 * 14050 * @param userId The device user for which to do a reset. 14051 */ 14052 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14053 final int packageCount = mPackages.size(); 14054 for (int i = 0; i < packageCount; i++) { 14055 PackageParser.Package pkg = mPackages.valueAt(i); 14056 PackageSetting ps = (PackageSetting) pkg.mExtras; 14057 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14058 } 14059 } 14060 14061 /** 14062 * Reverts user permission state changes (permissions and flags). 14063 * 14064 * @param ps The package for which to reset. 14065 * @param userId The device user for which to do a reset. 14066 */ 14067 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14068 final PackageSetting ps, final int userId) { 14069 if (ps.pkg == null) { 14070 return; 14071 } 14072 14073 // These are flags that can change base on user actions. 14074 final int userSettableMask = FLAG_PERMISSION_USER_SET 14075 | FLAG_PERMISSION_USER_FIXED 14076 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14077 | FLAG_PERMISSION_REVIEW_REQUIRED; 14078 14079 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14080 | FLAG_PERMISSION_POLICY_FIXED; 14081 14082 boolean writeInstallPermissions = false; 14083 boolean writeRuntimePermissions = false; 14084 14085 final int permissionCount = ps.pkg.requestedPermissions.size(); 14086 for (int i = 0; i < permissionCount; i++) { 14087 String permission = ps.pkg.requestedPermissions.get(i); 14088 14089 BasePermission bp = mSettings.mPermissions.get(permission); 14090 if (bp == null) { 14091 continue; 14092 } 14093 14094 // If shared user we just reset the state to which only this app contributed. 14095 if (ps.sharedUser != null) { 14096 boolean used = false; 14097 final int packageCount = ps.sharedUser.packages.size(); 14098 for (int j = 0; j < packageCount; j++) { 14099 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14100 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14101 && pkg.pkg.requestedPermissions.contains(permission)) { 14102 used = true; 14103 break; 14104 } 14105 } 14106 if (used) { 14107 continue; 14108 } 14109 } 14110 14111 PermissionsState permissionsState = ps.getPermissionsState(); 14112 14113 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14114 14115 // Always clear the user settable flags. 14116 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14117 bp.name) != null; 14118 // If permission review is enabled and this is a legacy app, mark the 14119 // permission as requiring a review as this is the initial state. 14120 int flags = 0; 14121 if (Build.PERMISSIONS_REVIEW_REQUIRED 14122 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14123 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14124 } 14125 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14126 if (hasInstallState) { 14127 writeInstallPermissions = true; 14128 } else { 14129 writeRuntimePermissions = true; 14130 } 14131 } 14132 14133 // Below is only runtime permission handling. 14134 if (!bp.isRuntime()) { 14135 continue; 14136 } 14137 14138 // Never clobber system or policy. 14139 if ((oldFlags & policyOrSystemFlags) != 0) { 14140 continue; 14141 } 14142 14143 // If this permission was granted by default, make sure it is. 14144 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14145 if (permissionsState.grantRuntimePermission(bp, userId) 14146 != PERMISSION_OPERATION_FAILURE) { 14147 writeRuntimePermissions = true; 14148 } 14149 // If permission review is enabled the permissions for a legacy apps 14150 // are represented as constantly granted runtime ones, so don't revoke. 14151 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14152 // Otherwise, reset the permission. 14153 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14154 switch (revokeResult) { 14155 case PERMISSION_OPERATION_SUCCESS: { 14156 writeRuntimePermissions = true; 14157 } break; 14158 14159 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14160 writeRuntimePermissions = true; 14161 final int appId = ps.appId; 14162 mHandler.post(new Runnable() { 14163 @Override 14164 public void run() { 14165 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14166 } 14167 }); 14168 } break; 14169 } 14170 } 14171 } 14172 14173 // Synchronously write as we are taking permissions away. 14174 if (writeRuntimePermissions) { 14175 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14176 } 14177 14178 // Synchronously write as we are taking permissions away. 14179 if (writeInstallPermissions) { 14180 mSettings.writeLPr(); 14181 } 14182 } 14183 14184 /** 14185 * Remove entries from the keystore daemon. Will only remove it if the 14186 * {@code appId} is valid. 14187 */ 14188 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14189 if (appId < 0) { 14190 return; 14191 } 14192 14193 final KeyStore keyStore = KeyStore.getInstance(); 14194 if (keyStore != null) { 14195 if (userId == UserHandle.USER_ALL) { 14196 for (final int individual : sUserManager.getUserIds()) { 14197 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14198 } 14199 } else { 14200 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14201 } 14202 } else { 14203 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14204 } 14205 } 14206 14207 @Override 14208 public void deleteApplicationCacheFiles(final String packageName, 14209 final IPackageDataObserver observer) { 14210 mContext.enforceCallingOrSelfPermission( 14211 android.Manifest.permission.DELETE_CACHE_FILES, null); 14212 // Queue up an async operation since the package deletion may take a little while. 14213 final int userId = UserHandle.getCallingUserId(); 14214 mHandler.post(new Runnable() { 14215 public void run() { 14216 mHandler.removeCallbacks(this); 14217 final boolean succeded; 14218 synchronized (mInstallLock) { 14219 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14220 } 14221 clearExternalStorageDataSync(packageName, userId, false); 14222 if (observer != null) { 14223 try { 14224 observer.onRemoveCompleted(packageName, succeded); 14225 } catch (RemoteException e) { 14226 Log.i(TAG, "Observer no longer exists."); 14227 } 14228 } //end if observer 14229 } //end run 14230 }); 14231 } 14232 14233 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14234 if (packageName == null) { 14235 Slog.w(TAG, "Attempt to delete null packageName."); 14236 return false; 14237 } 14238 PackageParser.Package p; 14239 synchronized (mPackages) { 14240 p = mPackages.get(packageName); 14241 } 14242 if (p == null) { 14243 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14244 return false; 14245 } 14246 final ApplicationInfo applicationInfo = p.applicationInfo; 14247 if (applicationInfo == null) { 14248 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14249 return false; 14250 } 14251 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14252 if (retCode < 0) { 14253 Slog.w(TAG, "Couldn't remove cache files for package " 14254 + packageName + " u" + userId); 14255 return false; 14256 } 14257 return true; 14258 } 14259 14260 @Override 14261 public void getPackageSizeInfo(final String packageName, int userHandle, 14262 final IPackageStatsObserver observer) { 14263 mContext.enforceCallingOrSelfPermission( 14264 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14265 if (packageName == null) { 14266 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14267 } 14268 14269 PackageStats stats = new PackageStats(packageName, userHandle); 14270 14271 /* 14272 * Queue up an async operation since the package measurement may take a 14273 * little while. 14274 */ 14275 Message msg = mHandler.obtainMessage(INIT_COPY); 14276 msg.obj = new MeasureParams(stats, observer); 14277 mHandler.sendMessage(msg); 14278 } 14279 14280 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14281 PackageStats pStats) { 14282 if (packageName == null) { 14283 Slog.w(TAG, "Attempt to get size of null packageName."); 14284 return false; 14285 } 14286 PackageParser.Package p; 14287 boolean dataOnly = false; 14288 String libDirRoot = null; 14289 String asecPath = null; 14290 PackageSetting ps = null; 14291 synchronized (mPackages) { 14292 p = mPackages.get(packageName); 14293 ps = mSettings.mPackages.get(packageName); 14294 if(p == null) { 14295 dataOnly = true; 14296 if((ps == null) || (ps.pkg == null)) { 14297 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14298 return false; 14299 } 14300 p = ps.pkg; 14301 } 14302 if (ps != null) { 14303 libDirRoot = ps.legacyNativeLibraryPathString; 14304 } 14305 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14306 final long token = Binder.clearCallingIdentity(); 14307 try { 14308 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14309 if (secureContainerId != null) { 14310 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14311 } 14312 } finally { 14313 Binder.restoreCallingIdentity(token); 14314 } 14315 } 14316 } 14317 String publicSrcDir = null; 14318 if(!dataOnly) { 14319 final ApplicationInfo applicationInfo = p.applicationInfo; 14320 if (applicationInfo == null) { 14321 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14322 return false; 14323 } 14324 if (p.isForwardLocked()) { 14325 publicSrcDir = applicationInfo.getBaseResourcePath(); 14326 } 14327 } 14328 // TODO: extend to measure size of split APKs 14329 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14330 // not just the first level. 14331 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14332 // just the primary. 14333 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14334 14335 String apkPath; 14336 File packageDir = new File(p.codePath); 14337 14338 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14339 apkPath = packageDir.getAbsolutePath(); 14340 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14341 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14342 libDirRoot = null; 14343 } 14344 } else { 14345 apkPath = p.baseCodePath; 14346 } 14347 14348 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14349 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14350 if (res < 0) { 14351 return false; 14352 } 14353 14354 // Fix-up for forward-locked applications in ASEC containers. 14355 if (!isExternal(p)) { 14356 pStats.codeSize += pStats.externalCodeSize; 14357 pStats.externalCodeSize = 0L; 14358 } 14359 14360 return true; 14361 } 14362 14363 14364 @Override 14365 public void addPackageToPreferred(String packageName) { 14366 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14367 } 14368 14369 @Override 14370 public void removePackageFromPreferred(String packageName) { 14371 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14372 } 14373 14374 @Override 14375 public List<PackageInfo> getPreferredPackages(int flags) { 14376 return new ArrayList<PackageInfo>(); 14377 } 14378 14379 private int getUidTargetSdkVersionLockedLPr(int uid) { 14380 Object obj = mSettings.getUserIdLPr(uid); 14381 if (obj instanceof SharedUserSetting) { 14382 final SharedUserSetting sus = (SharedUserSetting) obj; 14383 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14384 final Iterator<PackageSetting> it = sus.packages.iterator(); 14385 while (it.hasNext()) { 14386 final PackageSetting ps = it.next(); 14387 if (ps.pkg != null) { 14388 int v = ps.pkg.applicationInfo.targetSdkVersion; 14389 if (v < vers) vers = v; 14390 } 14391 } 14392 return vers; 14393 } else if (obj instanceof PackageSetting) { 14394 final PackageSetting ps = (PackageSetting) obj; 14395 if (ps.pkg != null) { 14396 return ps.pkg.applicationInfo.targetSdkVersion; 14397 } 14398 } 14399 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14400 } 14401 14402 @Override 14403 public void addPreferredActivity(IntentFilter filter, int match, 14404 ComponentName[] set, ComponentName activity, int userId) { 14405 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14406 "Adding preferred"); 14407 } 14408 14409 private void addPreferredActivityInternal(IntentFilter filter, int match, 14410 ComponentName[] set, ComponentName activity, boolean always, int userId, 14411 String opname) { 14412 // writer 14413 int callingUid = Binder.getCallingUid(); 14414 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14415 if (filter.countActions() == 0) { 14416 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14417 return; 14418 } 14419 synchronized (mPackages) { 14420 if (mContext.checkCallingOrSelfPermission( 14421 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14422 != PackageManager.PERMISSION_GRANTED) { 14423 if (getUidTargetSdkVersionLockedLPr(callingUid) 14424 < Build.VERSION_CODES.FROYO) { 14425 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14426 + callingUid); 14427 return; 14428 } 14429 mContext.enforceCallingOrSelfPermission( 14430 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14431 } 14432 14433 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14434 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14435 + userId + ":"); 14436 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14437 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14438 scheduleWritePackageRestrictionsLocked(userId); 14439 } 14440 } 14441 14442 @Override 14443 public void replacePreferredActivity(IntentFilter filter, int match, 14444 ComponentName[] set, ComponentName activity, int userId) { 14445 if (filter.countActions() != 1) { 14446 throw new IllegalArgumentException( 14447 "replacePreferredActivity expects filter to have only 1 action."); 14448 } 14449 if (filter.countDataAuthorities() != 0 14450 || filter.countDataPaths() != 0 14451 || filter.countDataSchemes() > 1 14452 || filter.countDataTypes() != 0) { 14453 throw new IllegalArgumentException( 14454 "replacePreferredActivity expects filter to have no data authorities, " + 14455 "paths, or types; and at most one scheme."); 14456 } 14457 14458 final int callingUid = Binder.getCallingUid(); 14459 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14460 synchronized (mPackages) { 14461 if (mContext.checkCallingOrSelfPermission( 14462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14463 != PackageManager.PERMISSION_GRANTED) { 14464 if (getUidTargetSdkVersionLockedLPr(callingUid) 14465 < Build.VERSION_CODES.FROYO) { 14466 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14467 + Binder.getCallingUid()); 14468 return; 14469 } 14470 mContext.enforceCallingOrSelfPermission( 14471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14472 } 14473 14474 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14475 if (pir != null) { 14476 // Get all of the existing entries that exactly match this filter. 14477 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14478 if (existing != null && existing.size() == 1) { 14479 PreferredActivity cur = existing.get(0); 14480 if (DEBUG_PREFERRED) { 14481 Slog.i(TAG, "Checking replace of preferred:"); 14482 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14483 if (!cur.mPref.mAlways) { 14484 Slog.i(TAG, " -- CUR; not mAlways!"); 14485 } else { 14486 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14487 Slog.i(TAG, " -- CUR: mSet=" 14488 + Arrays.toString(cur.mPref.mSetComponents)); 14489 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14490 Slog.i(TAG, " -- NEW: mMatch=" 14491 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14492 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14493 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14494 } 14495 } 14496 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14497 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14498 && cur.mPref.sameSet(set)) { 14499 // Setting the preferred activity to what it happens to be already 14500 if (DEBUG_PREFERRED) { 14501 Slog.i(TAG, "Replacing with same preferred activity " 14502 + cur.mPref.mShortComponent + " for user " 14503 + userId + ":"); 14504 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14505 } 14506 return; 14507 } 14508 } 14509 14510 if (existing != null) { 14511 if (DEBUG_PREFERRED) { 14512 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14513 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14514 } 14515 for (int i = 0; i < existing.size(); i++) { 14516 PreferredActivity pa = existing.get(i); 14517 if (DEBUG_PREFERRED) { 14518 Slog.i(TAG, "Removing existing preferred activity " 14519 + pa.mPref.mComponent + ":"); 14520 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14521 } 14522 pir.removeFilter(pa); 14523 } 14524 } 14525 } 14526 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14527 "Replacing preferred"); 14528 } 14529 } 14530 14531 @Override 14532 public void clearPackagePreferredActivities(String packageName) { 14533 final int uid = Binder.getCallingUid(); 14534 // writer 14535 synchronized (mPackages) { 14536 PackageParser.Package pkg = mPackages.get(packageName); 14537 if (pkg == null || pkg.applicationInfo.uid != uid) { 14538 if (mContext.checkCallingOrSelfPermission( 14539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14540 != PackageManager.PERMISSION_GRANTED) { 14541 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14542 < Build.VERSION_CODES.FROYO) { 14543 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14544 + Binder.getCallingUid()); 14545 return; 14546 } 14547 mContext.enforceCallingOrSelfPermission( 14548 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14549 } 14550 } 14551 14552 int user = UserHandle.getCallingUserId(); 14553 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14554 scheduleWritePackageRestrictionsLocked(user); 14555 } 14556 } 14557 } 14558 14559 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14560 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14561 ArrayList<PreferredActivity> removed = null; 14562 boolean changed = false; 14563 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14564 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14565 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14566 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14567 continue; 14568 } 14569 Iterator<PreferredActivity> it = pir.filterIterator(); 14570 while (it.hasNext()) { 14571 PreferredActivity pa = it.next(); 14572 // Mark entry for removal only if it matches the package name 14573 // and the entry is of type "always". 14574 if (packageName == null || 14575 (pa.mPref.mComponent.getPackageName().equals(packageName) 14576 && pa.mPref.mAlways)) { 14577 if (removed == null) { 14578 removed = new ArrayList<PreferredActivity>(); 14579 } 14580 removed.add(pa); 14581 } 14582 } 14583 if (removed != null) { 14584 for (int j=0; j<removed.size(); j++) { 14585 PreferredActivity pa = removed.get(j); 14586 pir.removeFilter(pa); 14587 } 14588 changed = true; 14589 } 14590 } 14591 return changed; 14592 } 14593 14594 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14595 private void clearIntentFilterVerificationsLPw(int userId) { 14596 final int packageCount = mPackages.size(); 14597 for (int i = 0; i < packageCount; i++) { 14598 PackageParser.Package pkg = mPackages.valueAt(i); 14599 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14600 } 14601 } 14602 14603 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14604 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14605 if (userId == UserHandle.USER_ALL) { 14606 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14607 sUserManager.getUserIds())) { 14608 for (int oneUserId : sUserManager.getUserIds()) { 14609 scheduleWritePackageRestrictionsLocked(oneUserId); 14610 } 14611 } 14612 } else { 14613 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14614 scheduleWritePackageRestrictionsLocked(userId); 14615 } 14616 } 14617 } 14618 14619 void clearDefaultBrowserIfNeeded(String packageName) { 14620 for (int oneUserId : sUserManager.getUserIds()) { 14621 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14622 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14623 if (packageName.equals(defaultBrowserPackageName)) { 14624 setDefaultBrowserPackageName(null, oneUserId); 14625 } 14626 } 14627 } 14628 14629 @Override 14630 public void resetApplicationPreferences(int userId) { 14631 mContext.enforceCallingOrSelfPermission( 14632 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14633 // writer 14634 synchronized (mPackages) { 14635 final long identity = Binder.clearCallingIdentity(); 14636 try { 14637 clearPackagePreferredActivitiesLPw(null, userId); 14638 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14639 // TODO: We have to reset the default SMS and Phone. This requires 14640 // significant refactoring to keep all default apps in the package 14641 // manager (cleaner but more work) or have the services provide 14642 // callbacks to the package manager to request a default app reset. 14643 applyFactoryDefaultBrowserLPw(userId); 14644 clearIntentFilterVerificationsLPw(userId); 14645 primeDomainVerificationsLPw(userId); 14646 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14647 scheduleWritePackageRestrictionsLocked(userId); 14648 } finally { 14649 Binder.restoreCallingIdentity(identity); 14650 } 14651 } 14652 } 14653 14654 @Override 14655 public int getPreferredActivities(List<IntentFilter> outFilters, 14656 List<ComponentName> outActivities, String packageName) { 14657 14658 int num = 0; 14659 final int userId = UserHandle.getCallingUserId(); 14660 // reader 14661 synchronized (mPackages) { 14662 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14663 if (pir != null) { 14664 final Iterator<PreferredActivity> it = pir.filterIterator(); 14665 while (it.hasNext()) { 14666 final PreferredActivity pa = it.next(); 14667 if (packageName == null 14668 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14669 && pa.mPref.mAlways)) { 14670 if (outFilters != null) { 14671 outFilters.add(new IntentFilter(pa)); 14672 } 14673 if (outActivities != null) { 14674 outActivities.add(pa.mPref.mComponent); 14675 } 14676 } 14677 } 14678 } 14679 } 14680 14681 return num; 14682 } 14683 14684 @Override 14685 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14686 int userId) { 14687 int callingUid = Binder.getCallingUid(); 14688 if (callingUid != Process.SYSTEM_UID) { 14689 throw new SecurityException( 14690 "addPersistentPreferredActivity can only be run by the system"); 14691 } 14692 if (filter.countActions() == 0) { 14693 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14694 return; 14695 } 14696 synchronized (mPackages) { 14697 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14698 ":"); 14699 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14700 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14701 new PersistentPreferredActivity(filter, activity)); 14702 scheduleWritePackageRestrictionsLocked(userId); 14703 } 14704 } 14705 14706 @Override 14707 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14708 int callingUid = Binder.getCallingUid(); 14709 if (callingUid != Process.SYSTEM_UID) { 14710 throw new SecurityException( 14711 "clearPackagePersistentPreferredActivities can only be run by the system"); 14712 } 14713 ArrayList<PersistentPreferredActivity> removed = null; 14714 boolean changed = false; 14715 synchronized (mPackages) { 14716 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14717 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14718 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14719 .valueAt(i); 14720 if (userId != thisUserId) { 14721 continue; 14722 } 14723 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14724 while (it.hasNext()) { 14725 PersistentPreferredActivity ppa = it.next(); 14726 // Mark entry for removal only if it matches the package name. 14727 if (ppa.mComponent.getPackageName().equals(packageName)) { 14728 if (removed == null) { 14729 removed = new ArrayList<PersistentPreferredActivity>(); 14730 } 14731 removed.add(ppa); 14732 } 14733 } 14734 if (removed != null) { 14735 for (int j=0; j<removed.size(); j++) { 14736 PersistentPreferredActivity ppa = removed.get(j); 14737 ppir.removeFilter(ppa); 14738 } 14739 changed = true; 14740 } 14741 } 14742 14743 if (changed) { 14744 scheduleWritePackageRestrictionsLocked(userId); 14745 } 14746 } 14747 } 14748 14749 /** 14750 * Common machinery for picking apart a restored XML blob and passing 14751 * it to a caller-supplied functor to be applied to the running system. 14752 */ 14753 private void restoreFromXml(XmlPullParser parser, int userId, 14754 String expectedStartTag, BlobXmlRestorer functor) 14755 throws IOException, XmlPullParserException { 14756 int type; 14757 while ((type = parser.next()) != XmlPullParser.START_TAG 14758 && type != XmlPullParser.END_DOCUMENT) { 14759 } 14760 if (type != XmlPullParser.START_TAG) { 14761 // oops didn't find a start tag?! 14762 if (DEBUG_BACKUP) { 14763 Slog.e(TAG, "Didn't find start tag during restore"); 14764 } 14765 return; 14766 } 14767 14768 // this is supposed to be TAG_PREFERRED_BACKUP 14769 if (!expectedStartTag.equals(parser.getName())) { 14770 if (DEBUG_BACKUP) { 14771 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14772 } 14773 return; 14774 } 14775 14776 // skip interfering stuff, then we're aligned with the backing implementation 14777 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14778 functor.apply(parser, userId); 14779 } 14780 14781 private interface BlobXmlRestorer { 14782 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14783 } 14784 14785 /** 14786 * Non-Binder method, support for the backup/restore mechanism: write the 14787 * full set of preferred activities in its canonical XML format. Returns the 14788 * XML output as a byte array, or null if there is none. 14789 */ 14790 @Override 14791 public byte[] getPreferredActivityBackup(int userId) { 14792 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14793 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14794 } 14795 14796 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14797 try { 14798 final XmlSerializer serializer = new FastXmlSerializer(); 14799 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14800 serializer.startDocument(null, true); 14801 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14802 14803 synchronized (mPackages) { 14804 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14805 } 14806 14807 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14808 serializer.endDocument(); 14809 serializer.flush(); 14810 } catch (Exception e) { 14811 if (DEBUG_BACKUP) { 14812 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14813 } 14814 return null; 14815 } 14816 14817 return dataStream.toByteArray(); 14818 } 14819 14820 @Override 14821 public void restorePreferredActivities(byte[] backup, int userId) { 14822 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14823 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14824 } 14825 14826 try { 14827 final XmlPullParser parser = Xml.newPullParser(); 14828 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14829 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14830 new BlobXmlRestorer() { 14831 @Override 14832 public void apply(XmlPullParser parser, int userId) 14833 throws XmlPullParserException, IOException { 14834 synchronized (mPackages) { 14835 mSettings.readPreferredActivitiesLPw(parser, userId); 14836 } 14837 } 14838 } ); 14839 } catch (Exception e) { 14840 if (DEBUG_BACKUP) { 14841 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14842 } 14843 } 14844 } 14845 14846 /** 14847 * Non-Binder method, support for the backup/restore mechanism: write the 14848 * default browser (etc) settings in its canonical XML format. Returns the default 14849 * browser XML representation as a byte array, or null if there is none. 14850 */ 14851 @Override 14852 public byte[] getDefaultAppsBackup(int userId) { 14853 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14854 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14855 } 14856 14857 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14858 try { 14859 final XmlSerializer serializer = new FastXmlSerializer(); 14860 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14861 serializer.startDocument(null, true); 14862 serializer.startTag(null, TAG_DEFAULT_APPS); 14863 14864 synchronized (mPackages) { 14865 mSettings.writeDefaultAppsLPr(serializer, userId); 14866 } 14867 14868 serializer.endTag(null, TAG_DEFAULT_APPS); 14869 serializer.endDocument(); 14870 serializer.flush(); 14871 } catch (Exception e) { 14872 if (DEBUG_BACKUP) { 14873 Slog.e(TAG, "Unable to write default apps for backup", e); 14874 } 14875 return null; 14876 } 14877 14878 return dataStream.toByteArray(); 14879 } 14880 14881 @Override 14882 public void restoreDefaultApps(byte[] backup, int userId) { 14883 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14884 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14885 } 14886 14887 try { 14888 final XmlPullParser parser = Xml.newPullParser(); 14889 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14890 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14891 new BlobXmlRestorer() { 14892 @Override 14893 public void apply(XmlPullParser parser, int userId) 14894 throws XmlPullParserException, IOException { 14895 synchronized (mPackages) { 14896 mSettings.readDefaultAppsLPw(parser, userId); 14897 } 14898 } 14899 } ); 14900 } catch (Exception e) { 14901 if (DEBUG_BACKUP) { 14902 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14903 } 14904 } 14905 } 14906 14907 @Override 14908 public byte[] getIntentFilterVerificationBackup(int userId) { 14909 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14910 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14911 } 14912 14913 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14914 try { 14915 final XmlSerializer serializer = new FastXmlSerializer(); 14916 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14917 serializer.startDocument(null, true); 14918 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14919 14920 synchronized (mPackages) { 14921 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14922 } 14923 14924 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14925 serializer.endDocument(); 14926 serializer.flush(); 14927 } catch (Exception e) { 14928 if (DEBUG_BACKUP) { 14929 Slog.e(TAG, "Unable to write default apps for backup", e); 14930 } 14931 return null; 14932 } 14933 14934 return dataStream.toByteArray(); 14935 } 14936 14937 @Override 14938 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14939 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14940 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14941 } 14942 14943 try { 14944 final XmlPullParser parser = Xml.newPullParser(); 14945 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14946 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14947 new BlobXmlRestorer() { 14948 @Override 14949 public void apply(XmlPullParser parser, int userId) 14950 throws XmlPullParserException, IOException { 14951 synchronized (mPackages) { 14952 mSettings.readAllDomainVerificationsLPr(parser, userId); 14953 mSettings.writeLPr(); 14954 } 14955 } 14956 } ); 14957 } catch (Exception e) { 14958 if (DEBUG_BACKUP) { 14959 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14960 } 14961 } 14962 } 14963 14964 @Override 14965 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14966 int sourceUserId, int targetUserId, int flags) { 14967 mContext.enforceCallingOrSelfPermission( 14968 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14969 int callingUid = Binder.getCallingUid(); 14970 enforceOwnerRights(ownerPackage, callingUid); 14971 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14972 if (intentFilter.countActions() == 0) { 14973 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14974 return; 14975 } 14976 synchronized (mPackages) { 14977 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14978 ownerPackage, targetUserId, flags); 14979 CrossProfileIntentResolver resolver = 14980 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14981 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14982 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14983 if (existing != null) { 14984 int size = existing.size(); 14985 for (int i = 0; i < size; i++) { 14986 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14987 return; 14988 } 14989 } 14990 } 14991 resolver.addFilter(newFilter); 14992 scheduleWritePackageRestrictionsLocked(sourceUserId); 14993 } 14994 } 14995 14996 @Override 14997 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14998 mContext.enforceCallingOrSelfPermission( 14999 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15000 int callingUid = Binder.getCallingUid(); 15001 enforceOwnerRights(ownerPackage, callingUid); 15002 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15003 synchronized (mPackages) { 15004 CrossProfileIntentResolver resolver = 15005 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15006 ArraySet<CrossProfileIntentFilter> set = 15007 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15008 for (CrossProfileIntentFilter filter : set) { 15009 if (filter.getOwnerPackage().equals(ownerPackage)) { 15010 resolver.removeFilter(filter); 15011 } 15012 } 15013 scheduleWritePackageRestrictionsLocked(sourceUserId); 15014 } 15015 } 15016 15017 // Enforcing that callingUid is owning pkg on userId 15018 private void enforceOwnerRights(String pkg, int callingUid) { 15019 // The system owns everything. 15020 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15021 return; 15022 } 15023 int callingUserId = UserHandle.getUserId(callingUid); 15024 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15025 if (pi == null) { 15026 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15027 + callingUserId); 15028 } 15029 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15030 throw new SecurityException("Calling uid " + callingUid 15031 + " does not own package " + pkg); 15032 } 15033 } 15034 15035 @Override 15036 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15037 Intent intent = new Intent(Intent.ACTION_MAIN); 15038 intent.addCategory(Intent.CATEGORY_HOME); 15039 15040 final int callingUserId = UserHandle.getCallingUserId(); 15041 List<ResolveInfo> list = queryIntentActivities(intent, null, 15042 PackageManager.GET_META_DATA, callingUserId); 15043 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15044 true, false, false, callingUserId); 15045 15046 allHomeCandidates.clear(); 15047 if (list != null) { 15048 for (ResolveInfo ri : list) { 15049 allHomeCandidates.add(ri); 15050 } 15051 } 15052 return (preferred == null || preferred.activityInfo == null) 15053 ? null 15054 : new ComponentName(preferred.activityInfo.packageName, 15055 preferred.activityInfo.name); 15056 } 15057 15058 @Override 15059 public void setApplicationEnabledSetting(String appPackageName, 15060 int newState, int flags, int userId, String callingPackage) { 15061 if (!sUserManager.exists(userId)) return; 15062 if (callingPackage == null) { 15063 callingPackage = Integer.toString(Binder.getCallingUid()); 15064 } 15065 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15066 } 15067 15068 @Override 15069 public void setComponentEnabledSetting(ComponentName componentName, 15070 int newState, int flags, int userId) { 15071 if (!sUserManager.exists(userId)) return; 15072 setEnabledSetting(componentName.getPackageName(), 15073 componentName.getClassName(), newState, flags, userId, null); 15074 } 15075 15076 private void setEnabledSetting(final String packageName, String className, int newState, 15077 final int flags, int userId, String callingPackage) { 15078 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15079 || newState == COMPONENT_ENABLED_STATE_ENABLED 15080 || newState == COMPONENT_ENABLED_STATE_DISABLED 15081 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15082 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15083 throw new IllegalArgumentException("Invalid new component state: " 15084 + newState); 15085 } 15086 PackageSetting pkgSetting; 15087 final int uid = Binder.getCallingUid(); 15088 final int permission = mContext.checkCallingOrSelfPermission( 15089 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15090 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15091 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15092 boolean sendNow = false; 15093 boolean isApp = (className == null); 15094 String componentName = isApp ? packageName : className; 15095 int packageUid = -1; 15096 ArrayList<String> components; 15097 15098 // writer 15099 synchronized (mPackages) { 15100 pkgSetting = mSettings.mPackages.get(packageName); 15101 if (pkgSetting == null) { 15102 if (className == null) { 15103 throw new IllegalArgumentException("Unknown package: " + packageName); 15104 } 15105 throw new IllegalArgumentException( 15106 "Unknown component: " + packageName + "/" + className); 15107 } 15108 // Allow root and verify that userId is not being specified by a different user 15109 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15110 throw new SecurityException( 15111 "Permission Denial: attempt to change component state from pid=" 15112 + Binder.getCallingPid() 15113 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15114 } 15115 if (className == null) { 15116 // We're dealing with an application/package level state change 15117 if (pkgSetting.getEnabled(userId) == newState) { 15118 // Nothing to do 15119 return; 15120 } 15121 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15122 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15123 // Don't care about who enables an app. 15124 callingPackage = null; 15125 } 15126 pkgSetting.setEnabled(newState, userId, callingPackage); 15127 // pkgSetting.pkg.mSetEnabled = newState; 15128 } else { 15129 // We're dealing with a component level state change 15130 // First, verify that this is a valid class name. 15131 PackageParser.Package pkg = pkgSetting.pkg; 15132 if (pkg == null || !pkg.hasComponentClassName(className)) { 15133 if (pkg != null && 15134 pkg.applicationInfo.targetSdkVersion >= 15135 Build.VERSION_CODES.JELLY_BEAN) { 15136 throw new IllegalArgumentException("Component class " + className 15137 + " does not exist in " + packageName); 15138 } else { 15139 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15140 + className + " does not exist in " + packageName); 15141 } 15142 } 15143 switch (newState) { 15144 case COMPONENT_ENABLED_STATE_ENABLED: 15145 if (!pkgSetting.enableComponentLPw(className, userId)) { 15146 return; 15147 } 15148 break; 15149 case COMPONENT_ENABLED_STATE_DISABLED: 15150 if (!pkgSetting.disableComponentLPw(className, userId)) { 15151 return; 15152 } 15153 break; 15154 case COMPONENT_ENABLED_STATE_DEFAULT: 15155 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15156 return; 15157 } 15158 break; 15159 default: 15160 Slog.e(TAG, "Invalid new component state: " + newState); 15161 return; 15162 } 15163 } 15164 scheduleWritePackageRestrictionsLocked(userId); 15165 components = mPendingBroadcasts.get(userId, packageName); 15166 final boolean newPackage = components == null; 15167 if (newPackage) { 15168 components = new ArrayList<String>(); 15169 } 15170 if (!components.contains(componentName)) { 15171 components.add(componentName); 15172 } 15173 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15174 sendNow = true; 15175 // Purge entry from pending broadcast list if another one exists already 15176 // since we are sending one right away. 15177 mPendingBroadcasts.remove(userId, packageName); 15178 } else { 15179 if (newPackage) { 15180 mPendingBroadcasts.put(userId, packageName, components); 15181 } 15182 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15183 // Schedule a message 15184 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15185 } 15186 } 15187 } 15188 15189 long callingId = Binder.clearCallingIdentity(); 15190 try { 15191 if (sendNow) { 15192 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15193 sendPackageChangedBroadcast(packageName, 15194 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15195 } 15196 } finally { 15197 Binder.restoreCallingIdentity(callingId); 15198 } 15199 } 15200 15201 private void sendPackageChangedBroadcast(String packageName, 15202 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15203 if (DEBUG_INSTALL) 15204 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15205 + componentNames); 15206 Bundle extras = new Bundle(4); 15207 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15208 String nameList[] = new String[componentNames.size()]; 15209 componentNames.toArray(nameList); 15210 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15211 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15212 extras.putInt(Intent.EXTRA_UID, packageUid); 15213 // If this is not reporting a change of the overall package, then only send it 15214 // to registered receivers. We don't want to launch a swath of apps for every 15215 // little component state change. 15216 final int flags = !componentNames.contains(packageName) 15217 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15218 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15219 new int[] {UserHandle.getUserId(packageUid)}); 15220 } 15221 15222 @Override 15223 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15224 if (!sUserManager.exists(userId)) return; 15225 final int uid = Binder.getCallingUid(); 15226 final int permission = mContext.checkCallingOrSelfPermission( 15227 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15228 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15229 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15230 // writer 15231 synchronized (mPackages) { 15232 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15233 allowedByPermission, uid, userId)) { 15234 scheduleWritePackageRestrictionsLocked(userId); 15235 } 15236 } 15237 } 15238 15239 @Override 15240 public String getInstallerPackageName(String packageName) { 15241 // reader 15242 synchronized (mPackages) { 15243 return mSettings.getInstallerPackageNameLPr(packageName); 15244 } 15245 } 15246 15247 @Override 15248 public int getApplicationEnabledSetting(String packageName, int userId) { 15249 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15250 int uid = Binder.getCallingUid(); 15251 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15252 // reader 15253 synchronized (mPackages) { 15254 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15255 } 15256 } 15257 15258 @Override 15259 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15260 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15261 int uid = Binder.getCallingUid(); 15262 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15263 // reader 15264 synchronized (mPackages) { 15265 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15266 } 15267 } 15268 15269 @Override 15270 public void enterSafeMode() { 15271 enforceSystemOrRoot("Only the system can request entering safe mode"); 15272 15273 if (!mSystemReady) { 15274 mSafeMode = true; 15275 } 15276 } 15277 15278 @Override 15279 public void systemReady() { 15280 mSystemReady = true; 15281 15282 // Read the compatibilty setting when the system is ready. 15283 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15284 mContext.getContentResolver(), 15285 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15286 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15287 if (DEBUG_SETTINGS) { 15288 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15289 } 15290 15291 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15292 15293 synchronized (mPackages) { 15294 // Verify that all of the preferred activity components actually 15295 // exist. It is possible for applications to be updated and at 15296 // that point remove a previously declared activity component that 15297 // had been set as a preferred activity. We try to clean this up 15298 // the next time we encounter that preferred activity, but it is 15299 // possible for the user flow to never be able to return to that 15300 // situation so here we do a sanity check to make sure we haven't 15301 // left any junk around. 15302 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15303 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15304 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15305 removed.clear(); 15306 for (PreferredActivity pa : pir.filterSet()) { 15307 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15308 removed.add(pa); 15309 } 15310 } 15311 if (removed.size() > 0) { 15312 for (int r=0; r<removed.size(); r++) { 15313 PreferredActivity pa = removed.get(r); 15314 Slog.w(TAG, "Removing dangling preferred activity: " 15315 + pa.mPref.mComponent); 15316 pir.removeFilter(pa); 15317 } 15318 mSettings.writePackageRestrictionsLPr( 15319 mSettings.mPreferredActivities.keyAt(i)); 15320 } 15321 } 15322 15323 for (int userId : UserManagerService.getInstance().getUserIds()) { 15324 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15325 grantPermissionsUserIds = ArrayUtils.appendInt( 15326 grantPermissionsUserIds, userId); 15327 } 15328 } 15329 } 15330 sUserManager.systemReady(); 15331 15332 // If we upgraded grant all default permissions before kicking off. 15333 for (int userId : grantPermissionsUserIds) { 15334 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15335 } 15336 15337 // Kick off any messages waiting for system ready 15338 if (mPostSystemReadyMessages != null) { 15339 for (Message msg : mPostSystemReadyMessages) { 15340 msg.sendToTarget(); 15341 } 15342 mPostSystemReadyMessages = null; 15343 } 15344 15345 // Watch for external volumes that come and go over time 15346 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15347 storage.registerListener(mStorageListener); 15348 15349 mInstallerService.systemReady(); 15350 mPackageDexOptimizer.systemReady(); 15351 15352 MountServiceInternal mountServiceInternal = LocalServices.getService( 15353 MountServiceInternal.class); 15354 mountServiceInternal.addExternalStoragePolicy( 15355 new MountServiceInternal.ExternalStorageMountPolicy() { 15356 @Override 15357 public int getMountMode(int uid, String packageName) { 15358 if (Process.isIsolated(uid)) { 15359 return Zygote.MOUNT_EXTERNAL_NONE; 15360 } 15361 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15362 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15363 } 15364 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15365 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15366 } 15367 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15368 return Zygote.MOUNT_EXTERNAL_READ; 15369 } 15370 return Zygote.MOUNT_EXTERNAL_WRITE; 15371 } 15372 15373 @Override 15374 public boolean hasExternalStorage(int uid, String packageName) { 15375 return true; 15376 } 15377 }); 15378 } 15379 15380 @Override 15381 public boolean isSafeMode() { 15382 return mSafeMode; 15383 } 15384 15385 @Override 15386 public boolean hasSystemUidErrors() { 15387 return mHasSystemUidErrors; 15388 } 15389 15390 static String arrayToString(int[] array) { 15391 StringBuffer buf = new StringBuffer(128); 15392 buf.append('['); 15393 if (array != null) { 15394 for (int i=0; i<array.length; i++) { 15395 if (i > 0) buf.append(", "); 15396 buf.append(array[i]); 15397 } 15398 } 15399 buf.append(']'); 15400 return buf.toString(); 15401 } 15402 15403 static class DumpState { 15404 public static final int DUMP_LIBS = 1 << 0; 15405 public static final int DUMP_FEATURES = 1 << 1; 15406 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15407 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15408 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15409 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15410 public static final int DUMP_PERMISSIONS = 1 << 6; 15411 public static final int DUMP_PACKAGES = 1 << 7; 15412 public static final int DUMP_SHARED_USERS = 1 << 8; 15413 public static final int DUMP_MESSAGES = 1 << 9; 15414 public static final int DUMP_PROVIDERS = 1 << 10; 15415 public static final int DUMP_VERIFIERS = 1 << 11; 15416 public static final int DUMP_PREFERRED = 1 << 12; 15417 public static final int DUMP_PREFERRED_XML = 1 << 13; 15418 public static final int DUMP_KEYSETS = 1 << 14; 15419 public static final int DUMP_VERSION = 1 << 15; 15420 public static final int DUMP_INSTALLS = 1 << 16; 15421 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15422 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15423 15424 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15425 15426 private int mTypes; 15427 15428 private int mOptions; 15429 15430 private boolean mTitlePrinted; 15431 15432 private SharedUserSetting mSharedUser; 15433 15434 public boolean isDumping(int type) { 15435 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15436 return true; 15437 } 15438 15439 return (mTypes & type) != 0; 15440 } 15441 15442 public void setDump(int type) { 15443 mTypes |= type; 15444 } 15445 15446 public boolean isOptionEnabled(int option) { 15447 return (mOptions & option) != 0; 15448 } 15449 15450 public void setOptionEnabled(int option) { 15451 mOptions |= option; 15452 } 15453 15454 public boolean onTitlePrinted() { 15455 final boolean printed = mTitlePrinted; 15456 mTitlePrinted = true; 15457 return printed; 15458 } 15459 15460 public boolean getTitlePrinted() { 15461 return mTitlePrinted; 15462 } 15463 15464 public void setTitlePrinted(boolean enabled) { 15465 mTitlePrinted = enabled; 15466 } 15467 15468 public SharedUserSetting getSharedUser() { 15469 return mSharedUser; 15470 } 15471 15472 public void setSharedUser(SharedUserSetting user) { 15473 mSharedUser = user; 15474 } 15475 } 15476 15477 @Override 15478 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15479 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15480 (new PackageManagerShellCommand(this)).exec( 15481 this, in, out, err, args, resultReceiver); 15482 } 15483 15484 @Override 15485 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15486 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15487 != PackageManager.PERMISSION_GRANTED) { 15488 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15489 + Binder.getCallingPid() 15490 + ", uid=" + Binder.getCallingUid() 15491 + " without permission " 15492 + android.Manifest.permission.DUMP); 15493 return; 15494 } 15495 15496 DumpState dumpState = new DumpState(); 15497 boolean fullPreferred = false; 15498 boolean checkin = false; 15499 15500 String packageName = null; 15501 ArraySet<String> permissionNames = null; 15502 15503 int opti = 0; 15504 while (opti < args.length) { 15505 String opt = args[opti]; 15506 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15507 break; 15508 } 15509 opti++; 15510 15511 if ("-a".equals(opt)) { 15512 // Right now we only know how to print all. 15513 } else if ("-h".equals(opt)) { 15514 pw.println("Package manager dump options:"); 15515 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15516 pw.println(" --checkin: dump for a checkin"); 15517 pw.println(" -f: print details of intent filters"); 15518 pw.println(" -h: print this help"); 15519 pw.println(" cmd may be one of:"); 15520 pw.println(" l[ibraries]: list known shared libraries"); 15521 pw.println(" f[eatures]: list device features"); 15522 pw.println(" k[eysets]: print known keysets"); 15523 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15524 pw.println(" perm[issions]: dump permissions"); 15525 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15526 pw.println(" pref[erred]: print preferred package settings"); 15527 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15528 pw.println(" prov[iders]: dump content providers"); 15529 pw.println(" p[ackages]: dump installed packages"); 15530 pw.println(" s[hared-users]: dump shared user IDs"); 15531 pw.println(" m[essages]: print collected runtime messages"); 15532 pw.println(" v[erifiers]: print package verifier info"); 15533 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15534 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15535 pw.println(" version: print database version info"); 15536 pw.println(" write: write current settings now"); 15537 pw.println(" installs: details about install sessions"); 15538 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15539 pw.println(" <package.name>: info about given package"); 15540 return; 15541 } else if ("--checkin".equals(opt)) { 15542 checkin = true; 15543 } else if ("-f".equals(opt)) { 15544 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15545 } else { 15546 pw.println("Unknown argument: " + opt + "; use -h for help"); 15547 } 15548 } 15549 15550 // Is the caller requesting to dump a particular piece of data? 15551 if (opti < args.length) { 15552 String cmd = args[opti]; 15553 opti++; 15554 // Is this a package name? 15555 if ("android".equals(cmd) || cmd.contains(".")) { 15556 packageName = cmd; 15557 // When dumping a single package, we always dump all of its 15558 // filter information since the amount of data will be reasonable. 15559 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15560 } else if ("check-permission".equals(cmd)) { 15561 if (opti >= args.length) { 15562 pw.println("Error: check-permission missing permission argument"); 15563 return; 15564 } 15565 String perm = args[opti]; 15566 opti++; 15567 if (opti >= args.length) { 15568 pw.println("Error: check-permission missing package argument"); 15569 return; 15570 } 15571 String pkg = args[opti]; 15572 opti++; 15573 int user = UserHandle.getUserId(Binder.getCallingUid()); 15574 if (opti < args.length) { 15575 try { 15576 user = Integer.parseInt(args[opti]); 15577 } catch (NumberFormatException e) { 15578 pw.println("Error: check-permission user argument is not a number: " 15579 + args[opti]); 15580 return; 15581 } 15582 } 15583 pw.println(checkPermission(perm, pkg, user)); 15584 return; 15585 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15586 dumpState.setDump(DumpState.DUMP_LIBS); 15587 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15588 dumpState.setDump(DumpState.DUMP_FEATURES); 15589 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15590 if (opti >= args.length) { 15591 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15592 | DumpState.DUMP_SERVICE_RESOLVERS 15593 | DumpState.DUMP_RECEIVER_RESOLVERS 15594 | DumpState.DUMP_CONTENT_RESOLVERS); 15595 } else { 15596 while (opti < args.length) { 15597 String name = args[opti]; 15598 if ("a".equals(name) || "activity".equals(name)) { 15599 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15600 } else if ("s".equals(name) || "service".equals(name)) { 15601 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15602 } else if ("r".equals(name) || "receiver".equals(name)) { 15603 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15604 } else if ("c".equals(name) || "content".equals(name)) { 15605 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15606 } else { 15607 pw.println("Error: unknown resolver table type: " + name); 15608 return; 15609 } 15610 opti++; 15611 } 15612 } 15613 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15614 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15615 } else if ("permission".equals(cmd)) { 15616 if (opti >= args.length) { 15617 pw.println("Error: permission requires permission name"); 15618 return; 15619 } 15620 permissionNames = new ArraySet<>(); 15621 while (opti < args.length) { 15622 permissionNames.add(args[opti]); 15623 opti++; 15624 } 15625 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15626 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15627 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15628 dumpState.setDump(DumpState.DUMP_PREFERRED); 15629 } else if ("preferred-xml".equals(cmd)) { 15630 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15631 if (opti < args.length && "--full".equals(args[opti])) { 15632 fullPreferred = true; 15633 opti++; 15634 } 15635 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15636 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15637 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15638 dumpState.setDump(DumpState.DUMP_PACKAGES); 15639 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15640 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15641 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15642 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15643 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15644 dumpState.setDump(DumpState.DUMP_MESSAGES); 15645 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15646 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15647 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15648 || "intent-filter-verifiers".equals(cmd)) { 15649 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15650 } else if ("version".equals(cmd)) { 15651 dumpState.setDump(DumpState.DUMP_VERSION); 15652 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15653 dumpState.setDump(DumpState.DUMP_KEYSETS); 15654 } else if ("installs".equals(cmd)) { 15655 dumpState.setDump(DumpState.DUMP_INSTALLS); 15656 } else if ("write".equals(cmd)) { 15657 synchronized (mPackages) { 15658 mSettings.writeLPr(); 15659 pw.println("Settings written."); 15660 return; 15661 } 15662 } 15663 } 15664 15665 if (checkin) { 15666 pw.println("vers,1"); 15667 } 15668 15669 // reader 15670 synchronized (mPackages) { 15671 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15672 if (!checkin) { 15673 if (dumpState.onTitlePrinted()) 15674 pw.println(); 15675 pw.println("Database versions:"); 15676 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15677 } 15678 } 15679 15680 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15681 if (!checkin) { 15682 if (dumpState.onTitlePrinted()) 15683 pw.println(); 15684 pw.println("Verifiers:"); 15685 pw.print(" Required: "); 15686 pw.print(mRequiredVerifierPackage); 15687 pw.print(" (uid="); 15688 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 15689 pw.println(")"); 15690 } else if (mRequiredVerifierPackage != null) { 15691 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15692 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 15693 } 15694 } 15695 15696 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15697 packageName == null) { 15698 if (mIntentFilterVerifierComponent != null) { 15699 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15700 if (!checkin) { 15701 if (dumpState.onTitlePrinted()) 15702 pw.println(); 15703 pw.println("Intent Filter Verifier:"); 15704 pw.print(" Using: "); 15705 pw.print(verifierPackageName); 15706 pw.print(" (uid="); 15707 pw.print(getPackageUid(verifierPackageName, 0)); 15708 pw.println(")"); 15709 } else if (verifierPackageName != null) { 15710 pw.print("ifv,"); pw.print(verifierPackageName); 15711 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 15712 } 15713 } else { 15714 pw.println(); 15715 pw.println("No Intent Filter Verifier available!"); 15716 } 15717 } 15718 15719 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15720 boolean printedHeader = false; 15721 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15722 while (it.hasNext()) { 15723 String name = it.next(); 15724 SharedLibraryEntry ent = mSharedLibraries.get(name); 15725 if (!checkin) { 15726 if (!printedHeader) { 15727 if (dumpState.onTitlePrinted()) 15728 pw.println(); 15729 pw.println("Libraries:"); 15730 printedHeader = true; 15731 } 15732 pw.print(" "); 15733 } else { 15734 pw.print("lib,"); 15735 } 15736 pw.print(name); 15737 if (!checkin) { 15738 pw.print(" -> "); 15739 } 15740 if (ent.path != null) { 15741 if (!checkin) { 15742 pw.print("(jar) "); 15743 pw.print(ent.path); 15744 } else { 15745 pw.print(",jar,"); 15746 pw.print(ent.path); 15747 } 15748 } else { 15749 if (!checkin) { 15750 pw.print("(apk) "); 15751 pw.print(ent.apk); 15752 } else { 15753 pw.print(",apk,"); 15754 pw.print(ent.apk); 15755 } 15756 } 15757 pw.println(); 15758 } 15759 } 15760 15761 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15762 if (dumpState.onTitlePrinted()) 15763 pw.println(); 15764 if (!checkin) { 15765 pw.println("Features:"); 15766 } 15767 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15768 while (it.hasNext()) { 15769 String name = it.next(); 15770 if (!checkin) { 15771 pw.print(" "); 15772 } else { 15773 pw.print("feat,"); 15774 } 15775 pw.println(name); 15776 } 15777 } 15778 15779 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15780 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15781 : "Activity Resolver Table:", " ", packageName, 15782 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15783 dumpState.setTitlePrinted(true); 15784 } 15785 } 15786 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15787 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15788 : "Receiver Resolver Table:", " ", packageName, 15789 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15790 dumpState.setTitlePrinted(true); 15791 } 15792 } 15793 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15794 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15795 : "Service Resolver Table:", " ", packageName, 15796 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15797 dumpState.setTitlePrinted(true); 15798 } 15799 } 15800 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15801 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15802 : "Provider Resolver Table:", " ", packageName, 15803 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15804 dumpState.setTitlePrinted(true); 15805 } 15806 } 15807 15808 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15809 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15810 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15811 int user = mSettings.mPreferredActivities.keyAt(i); 15812 if (pir.dump(pw, 15813 dumpState.getTitlePrinted() 15814 ? "\nPreferred Activities User " + user + ":" 15815 : "Preferred Activities User " + user + ":", " ", 15816 packageName, true, false)) { 15817 dumpState.setTitlePrinted(true); 15818 } 15819 } 15820 } 15821 15822 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15823 pw.flush(); 15824 FileOutputStream fout = new FileOutputStream(fd); 15825 BufferedOutputStream str = new BufferedOutputStream(fout); 15826 XmlSerializer serializer = new FastXmlSerializer(); 15827 try { 15828 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15829 serializer.startDocument(null, true); 15830 serializer.setFeature( 15831 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15832 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15833 serializer.endDocument(); 15834 serializer.flush(); 15835 } catch (IllegalArgumentException e) { 15836 pw.println("Failed writing: " + e); 15837 } catch (IllegalStateException e) { 15838 pw.println("Failed writing: " + e); 15839 } catch (IOException e) { 15840 pw.println("Failed writing: " + e); 15841 } 15842 } 15843 15844 if (!checkin 15845 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15846 && packageName == null) { 15847 pw.println(); 15848 int count = mSettings.mPackages.size(); 15849 if (count == 0) { 15850 pw.println("No applications!"); 15851 pw.println(); 15852 } else { 15853 final String prefix = " "; 15854 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15855 if (allPackageSettings.size() == 0) { 15856 pw.println("No domain preferred apps!"); 15857 pw.println(); 15858 } else { 15859 pw.println("App verification status:"); 15860 pw.println(); 15861 count = 0; 15862 for (PackageSetting ps : allPackageSettings) { 15863 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15864 if (ivi == null || ivi.getPackageName() == null) continue; 15865 pw.println(prefix + "Package: " + ivi.getPackageName()); 15866 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15867 pw.println(prefix + "Status: " + ivi.getStatusString()); 15868 pw.println(); 15869 count++; 15870 } 15871 if (count == 0) { 15872 pw.println(prefix + "No app verification established."); 15873 pw.println(); 15874 } 15875 for (int userId : sUserManager.getUserIds()) { 15876 pw.println("App linkages for user " + userId + ":"); 15877 pw.println(); 15878 count = 0; 15879 for (PackageSetting ps : allPackageSettings) { 15880 final long status = ps.getDomainVerificationStatusForUser(userId); 15881 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15882 continue; 15883 } 15884 pw.println(prefix + "Package: " + ps.name); 15885 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15886 String statusStr = IntentFilterVerificationInfo. 15887 getStatusStringFromValue(status); 15888 pw.println(prefix + "Status: " + statusStr); 15889 pw.println(); 15890 count++; 15891 } 15892 if (count == 0) { 15893 pw.println(prefix + "No configured app linkages."); 15894 pw.println(); 15895 } 15896 } 15897 } 15898 } 15899 } 15900 15901 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15902 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15903 if (packageName == null && permissionNames == null) { 15904 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15905 if (iperm == 0) { 15906 if (dumpState.onTitlePrinted()) 15907 pw.println(); 15908 pw.println("AppOp Permissions:"); 15909 } 15910 pw.print(" AppOp Permission "); 15911 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15912 pw.println(":"); 15913 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15914 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15915 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15916 } 15917 } 15918 } 15919 } 15920 15921 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15922 boolean printedSomething = false; 15923 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15924 if (packageName != null && !packageName.equals(p.info.packageName)) { 15925 continue; 15926 } 15927 if (!printedSomething) { 15928 if (dumpState.onTitlePrinted()) 15929 pw.println(); 15930 pw.println("Registered ContentProviders:"); 15931 printedSomething = true; 15932 } 15933 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15934 pw.print(" "); pw.println(p.toString()); 15935 } 15936 printedSomething = false; 15937 for (Map.Entry<String, PackageParser.Provider> entry : 15938 mProvidersByAuthority.entrySet()) { 15939 PackageParser.Provider p = entry.getValue(); 15940 if (packageName != null && !packageName.equals(p.info.packageName)) { 15941 continue; 15942 } 15943 if (!printedSomething) { 15944 if (dumpState.onTitlePrinted()) 15945 pw.println(); 15946 pw.println("ContentProvider Authorities:"); 15947 printedSomething = true; 15948 } 15949 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15950 pw.print(" "); pw.println(p.toString()); 15951 if (p.info != null && p.info.applicationInfo != null) { 15952 final String appInfo = p.info.applicationInfo.toString(); 15953 pw.print(" applicationInfo="); pw.println(appInfo); 15954 } 15955 } 15956 } 15957 15958 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15959 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15960 } 15961 15962 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15963 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15964 } 15965 15966 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15967 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15968 } 15969 15970 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15971 // XXX should handle packageName != null by dumping only install data that 15972 // the given package is involved with. 15973 if (dumpState.onTitlePrinted()) pw.println(); 15974 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15975 } 15976 15977 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15978 if (dumpState.onTitlePrinted()) pw.println(); 15979 mSettings.dumpReadMessagesLPr(pw, dumpState); 15980 15981 pw.println(); 15982 pw.println("Package warning messages:"); 15983 BufferedReader in = null; 15984 String line = null; 15985 try { 15986 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15987 while ((line = in.readLine()) != null) { 15988 if (line.contains("ignored: updated version")) continue; 15989 pw.println(line); 15990 } 15991 } catch (IOException ignored) { 15992 } finally { 15993 IoUtils.closeQuietly(in); 15994 } 15995 } 15996 15997 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15998 BufferedReader in = null; 15999 String line = null; 16000 try { 16001 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16002 while ((line = in.readLine()) != null) { 16003 if (line.contains("ignored: updated version")) continue; 16004 pw.print("msg,"); 16005 pw.println(line); 16006 } 16007 } catch (IOException ignored) { 16008 } finally { 16009 IoUtils.closeQuietly(in); 16010 } 16011 } 16012 } 16013 } 16014 16015 private String dumpDomainString(String packageName) { 16016 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16017 List<IntentFilter> filters = getAllIntentFilters(packageName); 16018 16019 ArraySet<String> result = new ArraySet<>(); 16020 if (iviList.size() > 0) { 16021 for (IntentFilterVerificationInfo ivi : iviList) { 16022 for (String host : ivi.getDomains()) { 16023 result.add(host); 16024 } 16025 } 16026 } 16027 if (filters != null && filters.size() > 0) { 16028 for (IntentFilter filter : filters) { 16029 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16030 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16031 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16032 result.addAll(filter.getHostsList()); 16033 } 16034 } 16035 } 16036 16037 StringBuilder sb = new StringBuilder(result.size() * 16); 16038 for (String domain : result) { 16039 if (sb.length() > 0) sb.append(" "); 16040 sb.append(domain); 16041 } 16042 return sb.toString(); 16043 } 16044 16045 // ------- apps on sdcard specific code ------- 16046 static final boolean DEBUG_SD_INSTALL = false; 16047 16048 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16049 16050 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16051 16052 private boolean mMediaMounted = false; 16053 16054 static String getEncryptKey() { 16055 try { 16056 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16057 SD_ENCRYPTION_KEYSTORE_NAME); 16058 if (sdEncKey == null) { 16059 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16060 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16061 if (sdEncKey == null) { 16062 Slog.e(TAG, "Failed to create encryption keys"); 16063 return null; 16064 } 16065 } 16066 return sdEncKey; 16067 } catch (NoSuchAlgorithmException nsae) { 16068 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16069 return null; 16070 } catch (IOException ioe) { 16071 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16072 return null; 16073 } 16074 } 16075 16076 /* 16077 * Update media status on PackageManager. 16078 */ 16079 @Override 16080 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16081 int callingUid = Binder.getCallingUid(); 16082 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16083 throw new SecurityException("Media status can only be updated by the system"); 16084 } 16085 // reader; this apparently protects mMediaMounted, but should probably 16086 // be a different lock in that case. 16087 synchronized (mPackages) { 16088 Log.i(TAG, "Updating external media status from " 16089 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16090 + (mediaStatus ? "mounted" : "unmounted")); 16091 if (DEBUG_SD_INSTALL) 16092 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16093 + ", mMediaMounted=" + mMediaMounted); 16094 if (mediaStatus == mMediaMounted) { 16095 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16096 : 0, -1); 16097 mHandler.sendMessage(msg); 16098 return; 16099 } 16100 mMediaMounted = mediaStatus; 16101 } 16102 // Queue up an async operation since the package installation may take a 16103 // little while. 16104 mHandler.post(new Runnable() { 16105 public void run() { 16106 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16107 } 16108 }); 16109 } 16110 16111 /** 16112 * Called by MountService when the initial ASECs to scan are available. 16113 * Should block until all the ASEC containers are finished being scanned. 16114 */ 16115 public void scanAvailableAsecs() { 16116 updateExternalMediaStatusInner(true, false, false); 16117 if (mShouldRestoreconData) { 16118 SELinuxMMAC.setRestoreconDone(); 16119 mShouldRestoreconData = false; 16120 } 16121 } 16122 16123 /* 16124 * Collect information of applications on external media, map them against 16125 * existing containers and update information based on current mount status. 16126 * Please note that we always have to report status if reportStatus has been 16127 * set to true especially when unloading packages. 16128 */ 16129 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16130 boolean externalStorage) { 16131 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16132 int[] uidArr = EmptyArray.INT; 16133 16134 final String[] list = PackageHelper.getSecureContainerList(); 16135 if (ArrayUtils.isEmpty(list)) { 16136 Log.i(TAG, "No secure containers found"); 16137 } else { 16138 // Process list of secure containers and categorize them 16139 // as active or stale based on their package internal state. 16140 16141 // reader 16142 synchronized (mPackages) { 16143 for (String cid : list) { 16144 // Leave stages untouched for now; installer service owns them 16145 if (PackageInstallerService.isStageName(cid)) continue; 16146 16147 if (DEBUG_SD_INSTALL) 16148 Log.i(TAG, "Processing container " + cid); 16149 String pkgName = getAsecPackageName(cid); 16150 if (pkgName == null) { 16151 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16152 continue; 16153 } 16154 if (DEBUG_SD_INSTALL) 16155 Log.i(TAG, "Looking for pkg : " + pkgName); 16156 16157 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16158 if (ps == null) { 16159 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16160 continue; 16161 } 16162 16163 /* 16164 * Skip packages that are not external if we're unmounting 16165 * external storage. 16166 */ 16167 if (externalStorage && !isMounted && !isExternal(ps)) { 16168 continue; 16169 } 16170 16171 final AsecInstallArgs args = new AsecInstallArgs(cid, 16172 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16173 // The package status is changed only if the code path 16174 // matches between settings and the container id. 16175 if (ps.codePathString != null 16176 && ps.codePathString.startsWith(args.getCodePath())) { 16177 if (DEBUG_SD_INSTALL) { 16178 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16179 + " at code path: " + ps.codePathString); 16180 } 16181 16182 // We do have a valid package installed on sdcard 16183 processCids.put(args, ps.codePathString); 16184 final int uid = ps.appId; 16185 if (uid != -1) { 16186 uidArr = ArrayUtils.appendInt(uidArr, uid); 16187 } 16188 } else { 16189 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16190 + ps.codePathString); 16191 } 16192 } 16193 } 16194 16195 Arrays.sort(uidArr); 16196 } 16197 16198 // Process packages with valid entries. 16199 if (isMounted) { 16200 if (DEBUG_SD_INSTALL) 16201 Log.i(TAG, "Loading packages"); 16202 loadMediaPackages(processCids, uidArr, externalStorage); 16203 startCleaningPackages(); 16204 mInstallerService.onSecureContainersAvailable(); 16205 } else { 16206 if (DEBUG_SD_INSTALL) 16207 Log.i(TAG, "Unloading packages"); 16208 unloadMediaPackages(processCids, uidArr, reportStatus); 16209 } 16210 } 16211 16212 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16213 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16214 final int size = infos.size(); 16215 final String[] packageNames = new String[size]; 16216 final int[] packageUids = new int[size]; 16217 for (int i = 0; i < size; i++) { 16218 final ApplicationInfo info = infos.get(i); 16219 packageNames[i] = info.packageName; 16220 packageUids[i] = info.uid; 16221 } 16222 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16223 finishedReceiver); 16224 } 16225 16226 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16227 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16228 sendResourcesChangedBroadcast(mediaStatus, replacing, 16229 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16230 } 16231 16232 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16233 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16234 int size = pkgList.length; 16235 if (size > 0) { 16236 // Send broadcasts here 16237 Bundle extras = new Bundle(); 16238 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16239 if (uidArr != null) { 16240 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16241 } 16242 if (replacing) { 16243 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16244 } 16245 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16246 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16247 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16248 } 16249 } 16250 16251 /* 16252 * Look at potentially valid container ids from processCids If package 16253 * information doesn't match the one on record or package scanning fails, 16254 * the cid is added to list of removeCids. We currently don't delete stale 16255 * containers. 16256 */ 16257 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16258 boolean externalStorage) { 16259 ArrayList<String> pkgList = new ArrayList<String>(); 16260 Set<AsecInstallArgs> keys = processCids.keySet(); 16261 16262 for (AsecInstallArgs args : keys) { 16263 String codePath = processCids.get(args); 16264 if (DEBUG_SD_INSTALL) 16265 Log.i(TAG, "Loading container : " + args.cid); 16266 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16267 try { 16268 // Make sure there are no container errors first. 16269 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16270 Slog.e(TAG, "Failed to mount cid : " + args.cid 16271 + " when installing from sdcard"); 16272 continue; 16273 } 16274 // Check code path here. 16275 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16276 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16277 + " does not match one in settings " + codePath); 16278 continue; 16279 } 16280 // Parse package 16281 int parseFlags = mDefParseFlags; 16282 if (args.isExternalAsec()) { 16283 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16284 } 16285 if (args.isFwdLocked()) { 16286 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16287 } 16288 16289 synchronized (mInstallLock) { 16290 PackageParser.Package pkg = null; 16291 try { 16292 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16293 } catch (PackageManagerException e) { 16294 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16295 } 16296 // Scan the package 16297 if (pkg != null) { 16298 /* 16299 * TODO why is the lock being held? doPostInstall is 16300 * called in other places without the lock. This needs 16301 * to be straightened out. 16302 */ 16303 // writer 16304 synchronized (mPackages) { 16305 retCode = PackageManager.INSTALL_SUCCEEDED; 16306 pkgList.add(pkg.packageName); 16307 // Post process args 16308 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16309 pkg.applicationInfo.uid); 16310 } 16311 } else { 16312 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16313 } 16314 } 16315 16316 } finally { 16317 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16318 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16319 } 16320 } 16321 } 16322 // writer 16323 synchronized (mPackages) { 16324 // If the platform SDK has changed since the last time we booted, 16325 // we need to re-grant app permission to catch any new ones that 16326 // appear. This is really a hack, and means that apps can in some 16327 // cases get permissions that the user didn't initially explicitly 16328 // allow... it would be nice to have some better way to handle 16329 // this situation. 16330 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16331 : mSettings.getInternalVersion(); 16332 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16333 : StorageManager.UUID_PRIVATE_INTERNAL; 16334 16335 int updateFlags = UPDATE_PERMISSIONS_ALL; 16336 if (ver.sdkVersion != mSdkVersion) { 16337 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16338 + mSdkVersion + "; regranting permissions for external"); 16339 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16340 } 16341 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16342 16343 // Yay, everything is now upgraded 16344 ver.forceCurrent(); 16345 16346 // can downgrade to reader 16347 // Persist settings 16348 mSettings.writeLPr(); 16349 } 16350 // Send a broadcast to let everyone know we are done processing 16351 if (pkgList.size() > 0) { 16352 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16353 } 16354 } 16355 16356 /* 16357 * Utility method to unload a list of specified containers 16358 */ 16359 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16360 // Just unmount all valid containers. 16361 for (AsecInstallArgs arg : cidArgs) { 16362 synchronized (mInstallLock) { 16363 arg.doPostDeleteLI(false); 16364 } 16365 } 16366 } 16367 16368 /* 16369 * Unload packages mounted on external media. This involves deleting package 16370 * data from internal structures, sending broadcasts about diabled packages, 16371 * gc'ing to free up references, unmounting all secure containers 16372 * corresponding to packages on external media, and posting a 16373 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16374 * that we always have to post this message if status has been requested no 16375 * matter what. 16376 */ 16377 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16378 final boolean reportStatus) { 16379 if (DEBUG_SD_INSTALL) 16380 Log.i(TAG, "unloading media packages"); 16381 ArrayList<String> pkgList = new ArrayList<String>(); 16382 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16383 final Set<AsecInstallArgs> keys = processCids.keySet(); 16384 for (AsecInstallArgs args : keys) { 16385 String pkgName = args.getPackageName(); 16386 if (DEBUG_SD_INSTALL) 16387 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16388 // Delete package internally 16389 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16390 synchronized (mInstallLock) { 16391 boolean res = deletePackageLI(pkgName, null, false, null, null, 16392 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16393 if (res) { 16394 pkgList.add(pkgName); 16395 } else { 16396 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16397 failedList.add(args); 16398 } 16399 } 16400 } 16401 16402 // reader 16403 synchronized (mPackages) { 16404 // We didn't update the settings after removing each package; 16405 // write them now for all packages. 16406 mSettings.writeLPr(); 16407 } 16408 16409 // We have to absolutely send UPDATED_MEDIA_STATUS only 16410 // after confirming that all the receivers processed the ordered 16411 // broadcast when packages get disabled, force a gc to clean things up. 16412 // and unload all the containers. 16413 if (pkgList.size() > 0) { 16414 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16415 new IIntentReceiver.Stub() { 16416 public void performReceive(Intent intent, int resultCode, String data, 16417 Bundle extras, boolean ordered, boolean sticky, 16418 int sendingUser) throws RemoteException { 16419 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16420 reportStatus ? 1 : 0, 1, keys); 16421 mHandler.sendMessage(msg); 16422 } 16423 }); 16424 } else { 16425 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16426 keys); 16427 mHandler.sendMessage(msg); 16428 } 16429 } 16430 16431 private void loadPrivatePackages(final VolumeInfo vol) { 16432 mHandler.post(new Runnable() { 16433 @Override 16434 public void run() { 16435 loadPrivatePackagesInner(vol); 16436 } 16437 }); 16438 } 16439 16440 private void loadPrivatePackagesInner(VolumeInfo vol) { 16441 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16442 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16443 16444 final VersionInfo ver; 16445 final List<PackageSetting> packages; 16446 synchronized (mPackages) { 16447 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16448 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16449 } 16450 16451 for (PackageSetting ps : packages) { 16452 synchronized (mInstallLock) { 16453 final PackageParser.Package pkg; 16454 try { 16455 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16456 loaded.add(pkg.applicationInfo); 16457 } catch (PackageManagerException e) { 16458 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16459 } 16460 16461 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16462 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16463 } 16464 } 16465 } 16466 16467 synchronized (mPackages) { 16468 int updateFlags = UPDATE_PERMISSIONS_ALL; 16469 if (ver.sdkVersion != mSdkVersion) { 16470 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16471 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16472 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16473 } 16474 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16475 16476 // Yay, everything is now upgraded 16477 ver.forceCurrent(); 16478 16479 mSettings.writeLPr(); 16480 } 16481 16482 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16483 sendResourcesChangedBroadcast(true, false, loaded, null); 16484 } 16485 16486 private void unloadPrivatePackages(final VolumeInfo vol) { 16487 mHandler.post(new Runnable() { 16488 @Override 16489 public void run() { 16490 unloadPrivatePackagesInner(vol); 16491 } 16492 }); 16493 } 16494 16495 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16496 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16497 synchronized (mInstallLock) { 16498 synchronized (mPackages) { 16499 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16500 for (PackageSetting ps : packages) { 16501 if (ps.pkg == null) continue; 16502 16503 final ApplicationInfo info = ps.pkg.applicationInfo; 16504 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16505 if (deletePackageLI(ps.name, null, false, null, null, 16506 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16507 unloaded.add(info); 16508 } else { 16509 Slog.w(TAG, "Failed to unload " + ps.codePath); 16510 } 16511 } 16512 16513 mSettings.writeLPr(); 16514 } 16515 } 16516 16517 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16518 sendResourcesChangedBroadcast(false, false, unloaded, null); 16519 } 16520 16521 /** 16522 * Examine all users present on given mounted volume, and destroy data 16523 * belonging to users that are no longer valid, or whose user ID has been 16524 * recycled. 16525 */ 16526 private void reconcileUsers(String volumeUuid) { 16527 final File[] files = FileUtils 16528 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16529 for (File file : files) { 16530 if (!file.isDirectory()) continue; 16531 16532 final int userId; 16533 final UserInfo info; 16534 try { 16535 userId = Integer.parseInt(file.getName()); 16536 info = sUserManager.getUserInfo(userId); 16537 } catch (NumberFormatException e) { 16538 Slog.w(TAG, "Invalid user directory " + file); 16539 continue; 16540 } 16541 16542 boolean destroyUser = false; 16543 if (info == null) { 16544 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16545 + " because no matching user was found"); 16546 destroyUser = true; 16547 } else { 16548 try { 16549 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16550 } catch (IOException e) { 16551 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16552 + " because we failed to enforce serial number: " + e); 16553 destroyUser = true; 16554 } 16555 } 16556 16557 if (destroyUser) { 16558 synchronized (mInstallLock) { 16559 mInstaller.removeUserDataDirs(volumeUuid, userId); 16560 } 16561 } 16562 } 16563 16564 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16565 final UserManager um = mContext.getSystemService(UserManager.class); 16566 for (UserInfo user : um.getUsers()) { 16567 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16568 if (userDir.exists()) continue; 16569 16570 try { 16571 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16572 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16573 } catch (IOException e) { 16574 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16575 } 16576 } 16577 } 16578 16579 /** 16580 * Examine all apps present on given mounted volume, and destroy apps that 16581 * aren't expected, either due to uninstallation or reinstallation on 16582 * another volume. 16583 */ 16584 private void reconcileApps(String volumeUuid) { 16585 final File[] files = FileUtils 16586 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16587 for (File file : files) { 16588 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16589 && !PackageInstallerService.isStageName(file.getName()); 16590 if (!isPackage) { 16591 // Ignore entries which are not packages 16592 continue; 16593 } 16594 16595 boolean destroyApp = false; 16596 String packageName = null; 16597 try { 16598 final PackageLite pkg = PackageParser.parsePackageLite(file, 16599 PackageParser.PARSE_MUST_BE_APK); 16600 packageName = pkg.packageName; 16601 16602 synchronized (mPackages) { 16603 final PackageSetting ps = mSettings.mPackages.get(packageName); 16604 if (ps == null) { 16605 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16606 + volumeUuid + " because we found no install record"); 16607 destroyApp = true; 16608 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16609 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16610 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16611 destroyApp = true; 16612 } 16613 } 16614 16615 } catch (PackageParserException e) { 16616 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16617 destroyApp = true; 16618 } 16619 16620 if (destroyApp) { 16621 synchronized (mInstallLock) { 16622 if (packageName != null) { 16623 removeDataDirsLI(volumeUuid, packageName); 16624 } 16625 if (file.isDirectory()) { 16626 mInstaller.rmPackageDir(file.getAbsolutePath()); 16627 } else { 16628 file.delete(); 16629 } 16630 } 16631 } 16632 } 16633 } 16634 16635 private void unfreezePackage(String packageName) { 16636 synchronized (mPackages) { 16637 final PackageSetting ps = mSettings.mPackages.get(packageName); 16638 if (ps != null) { 16639 ps.frozen = false; 16640 } 16641 } 16642 } 16643 16644 @Override 16645 public int movePackage(final String packageName, final String volumeUuid) { 16646 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16647 16648 final int moveId = mNextMoveId.getAndIncrement(); 16649 mHandler.post(new Runnable() { 16650 @Override 16651 public void run() { 16652 try { 16653 movePackageInternal(packageName, volumeUuid, moveId); 16654 } catch (PackageManagerException e) { 16655 Slog.w(TAG, "Failed to move " + packageName, e); 16656 mMoveCallbacks.notifyStatusChanged(moveId, 16657 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16658 } 16659 } 16660 }); 16661 return moveId; 16662 } 16663 16664 private void movePackageInternal(final String packageName, final String volumeUuid, 16665 final int moveId) throws PackageManagerException { 16666 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16667 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16668 final PackageManager pm = mContext.getPackageManager(); 16669 16670 final boolean currentAsec; 16671 final String currentVolumeUuid; 16672 final File codeFile; 16673 final String installerPackageName; 16674 final String packageAbiOverride; 16675 final int appId; 16676 final String seinfo; 16677 final String label; 16678 16679 // reader 16680 synchronized (mPackages) { 16681 final PackageParser.Package pkg = mPackages.get(packageName); 16682 final PackageSetting ps = mSettings.mPackages.get(packageName); 16683 if (pkg == null || ps == null) { 16684 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16685 } 16686 16687 if (pkg.applicationInfo.isSystemApp()) { 16688 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16689 "Cannot move system application"); 16690 } 16691 16692 if (pkg.applicationInfo.isExternalAsec()) { 16693 currentAsec = true; 16694 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16695 } else if (pkg.applicationInfo.isForwardLocked()) { 16696 currentAsec = true; 16697 currentVolumeUuid = "forward_locked"; 16698 } else { 16699 currentAsec = false; 16700 currentVolumeUuid = ps.volumeUuid; 16701 16702 final File probe = new File(pkg.codePath); 16703 final File probeOat = new File(probe, "oat"); 16704 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16705 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16706 "Move only supported for modern cluster style installs"); 16707 } 16708 } 16709 16710 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16711 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16712 "Package already moved to " + volumeUuid); 16713 } 16714 16715 if (ps.frozen) { 16716 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16717 "Failed to move already frozen package"); 16718 } 16719 ps.frozen = true; 16720 16721 codeFile = new File(pkg.codePath); 16722 installerPackageName = ps.installerPackageName; 16723 packageAbiOverride = ps.cpuAbiOverrideString; 16724 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16725 seinfo = pkg.applicationInfo.seinfo; 16726 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16727 } 16728 16729 // Now that we're guarded by frozen state, kill app during move 16730 final long token = Binder.clearCallingIdentity(); 16731 try { 16732 killApplication(packageName, appId, "move pkg"); 16733 } finally { 16734 Binder.restoreCallingIdentity(token); 16735 } 16736 16737 final Bundle extras = new Bundle(); 16738 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16739 extras.putString(Intent.EXTRA_TITLE, label); 16740 mMoveCallbacks.notifyCreated(moveId, extras); 16741 16742 int installFlags; 16743 final boolean moveCompleteApp; 16744 final File measurePath; 16745 16746 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16747 installFlags = INSTALL_INTERNAL; 16748 moveCompleteApp = !currentAsec; 16749 measurePath = Environment.getDataAppDirectory(volumeUuid); 16750 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16751 installFlags = INSTALL_EXTERNAL; 16752 moveCompleteApp = false; 16753 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16754 } else { 16755 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16756 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16757 || !volume.isMountedWritable()) { 16758 unfreezePackage(packageName); 16759 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16760 "Move location not mounted private volume"); 16761 } 16762 16763 Preconditions.checkState(!currentAsec); 16764 16765 installFlags = INSTALL_INTERNAL; 16766 moveCompleteApp = true; 16767 measurePath = Environment.getDataAppDirectory(volumeUuid); 16768 } 16769 16770 final PackageStats stats = new PackageStats(null, -1); 16771 synchronized (mInstaller) { 16772 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16773 unfreezePackage(packageName); 16774 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16775 "Failed to measure package size"); 16776 } 16777 } 16778 16779 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16780 + stats.dataSize); 16781 16782 final long startFreeBytes = measurePath.getFreeSpace(); 16783 final long sizeBytes; 16784 if (moveCompleteApp) { 16785 sizeBytes = stats.codeSize + stats.dataSize; 16786 } else { 16787 sizeBytes = stats.codeSize; 16788 } 16789 16790 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16791 unfreezePackage(packageName); 16792 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16793 "Not enough free space to move"); 16794 } 16795 16796 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16797 16798 final CountDownLatch installedLatch = new CountDownLatch(1); 16799 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16800 @Override 16801 public void onUserActionRequired(Intent intent) throws RemoteException { 16802 throw new IllegalStateException(); 16803 } 16804 16805 @Override 16806 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16807 Bundle extras) throws RemoteException { 16808 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16809 + PackageManager.installStatusToString(returnCode, msg)); 16810 16811 installedLatch.countDown(); 16812 16813 // Regardless of success or failure of the move operation, 16814 // always unfreeze the package 16815 unfreezePackage(packageName); 16816 16817 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16818 switch (status) { 16819 case PackageInstaller.STATUS_SUCCESS: 16820 mMoveCallbacks.notifyStatusChanged(moveId, 16821 PackageManager.MOVE_SUCCEEDED); 16822 break; 16823 case PackageInstaller.STATUS_FAILURE_STORAGE: 16824 mMoveCallbacks.notifyStatusChanged(moveId, 16825 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16826 break; 16827 default: 16828 mMoveCallbacks.notifyStatusChanged(moveId, 16829 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16830 break; 16831 } 16832 } 16833 }; 16834 16835 final MoveInfo move; 16836 if (moveCompleteApp) { 16837 // Kick off a thread to report progress estimates 16838 new Thread() { 16839 @Override 16840 public void run() { 16841 while (true) { 16842 try { 16843 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16844 break; 16845 } 16846 } catch (InterruptedException ignored) { 16847 } 16848 16849 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16850 final int progress = 10 + (int) MathUtils.constrain( 16851 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16852 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16853 } 16854 } 16855 }.start(); 16856 16857 final String dataAppName = codeFile.getName(); 16858 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16859 dataAppName, appId, seinfo); 16860 } else { 16861 move = null; 16862 } 16863 16864 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16865 16866 final Message msg = mHandler.obtainMessage(INIT_COPY); 16867 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16868 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16869 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16870 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16871 msg.obj = params; 16872 16873 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16874 System.identityHashCode(msg.obj)); 16875 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16876 System.identityHashCode(msg.obj)); 16877 16878 mHandler.sendMessage(msg); 16879 } 16880 16881 @Override 16882 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16883 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16884 16885 final int realMoveId = mNextMoveId.getAndIncrement(); 16886 final Bundle extras = new Bundle(); 16887 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16888 mMoveCallbacks.notifyCreated(realMoveId, extras); 16889 16890 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16891 @Override 16892 public void onCreated(int moveId, Bundle extras) { 16893 // Ignored 16894 } 16895 16896 @Override 16897 public void onStatusChanged(int moveId, int status, long estMillis) { 16898 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16899 } 16900 }; 16901 16902 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16903 storage.setPrimaryStorageUuid(volumeUuid, callback); 16904 return realMoveId; 16905 } 16906 16907 @Override 16908 public int getMoveStatus(int moveId) { 16909 mContext.enforceCallingOrSelfPermission( 16910 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16911 return mMoveCallbacks.mLastStatus.get(moveId); 16912 } 16913 16914 @Override 16915 public void registerMoveCallback(IPackageMoveObserver callback) { 16916 mContext.enforceCallingOrSelfPermission( 16917 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16918 mMoveCallbacks.register(callback); 16919 } 16920 16921 @Override 16922 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16923 mContext.enforceCallingOrSelfPermission( 16924 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16925 mMoveCallbacks.unregister(callback); 16926 } 16927 16928 @Override 16929 public boolean setInstallLocation(int loc) { 16930 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16931 null); 16932 if (getInstallLocation() == loc) { 16933 return true; 16934 } 16935 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16936 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16937 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16938 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16939 return true; 16940 } 16941 return false; 16942 } 16943 16944 @Override 16945 public int getInstallLocation() { 16946 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16947 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16948 PackageHelper.APP_INSTALL_AUTO); 16949 } 16950 16951 /** Called by UserManagerService */ 16952 void cleanUpUser(UserManagerService userManager, int userHandle) { 16953 synchronized (mPackages) { 16954 mDirtyUsers.remove(userHandle); 16955 mUserNeedsBadging.delete(userHandle); 16956 mSettings.removeUserLPw(userHandle); 16957 mPendingBroadcasts.remove(userHandle); 16958 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 16959 } 16960 synchronized (mInstallLock) { 16961 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16962 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16963 final String volumeUuid = vol.getFsUuid(); 16964 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16965 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16966 } 16967 synchronized (mPackages) { 16968 removeUnusedPackagesLILPw(userManager, userHandle); 16969 } 16970 } 16971 } 16972 16973 /** 16974 * We're removing userHandle and would like to remove any downloaded packages 16975 * that are no longer in use by any other user. 16976 * @param userHandle the user being removed 16977 */ 16978 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16979 final boolean DEBUG_CLEAN_APKS = false; 16980 int [] users = userManager.getUserIds(); 16981 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16982 while (psit.hasNext()) { 16983 PackageSetting ps = psit.next(); 16984 if (ps.pkg == null) { 16985 continue; 16986 } 16987 final String packageName = ps.pkg.packageName; 16988 // Skip over if system app 16989 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16990 continue; 16991 } 16992 if (DEBUG_CLEAN_APKS) { 16993 Slog.i(TAG, "Checking package " + packageName); 16994 } 16995 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16996 if (keep) { 16997 if (DEBUG_CLEAN_APKS) { 16998 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16999 } 17000 } else { 17001 for (int i = 0; i < users.length; i++) { 17002 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17003 keep = true; 17004 if (DEBUG_CLEAN_APKS) { 17005 Slog.i(TAG, " Keeping package " + packageName + " for user " 17006 + users[i]); 17007 } 17008 break; 17009 } 17010 } 17011 } 17012 if (!keep) { 17013 if (DEBUG_CLEAN_APKS) { 17014 Slog.i(TAG, " Removing package " + packageName); 17015 } 17016 mHandler.post(new Runnable() { 17017 public void run() { 17018 deletePackageX(packageName, userHandle, 0); 17019 } //end run 17020 }); 17021 } 17022 } 17023 } 17024 17025 /** Called by UserManagerService */ 17026 void createNewUser(int userHandle) { 17027 synchronized (mInstallLock) { 17028 mInstaller.createUserConfig(userHandle); 17029 mSettings.createNewUserLI(this, mInstaller, userHandle); 17030 } 17031 synchronized (mPackages) { 17032 applyFactoryDefaultBrowserLPw(userHandle); 17033 primeDomainVerificationsLPw(userHandle); 17034 } 17035 } 17036 17037 void newUserCreated(final int userHandle) { 17038 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17039 // If permission review for legacy apps is required, we represent 17040 // dagerous permissions for such apps as always granted runtime 17041 // permissions to keep per user flag state whether review is needed. 17042 // Hence, if a new user is added we have to propagate dangerous 17043 // permission grants for these legacy apps. 17044 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17045 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17046 | UPDATE_PERMISSIONS_REPLACE_ALL); 17047 } 17048 } 17049 17050 @Override 17051 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17052 mContext.enforceCallingOrSelfPermission( 17053 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17054 "Only package verification agents can read the verifier device identity"); 17055 17056 synchronized (mPackages) { 17057 return mSettings.getVerifierDeviceIdentityLPw(); 17058 } 17059 } 17060 17061 @Override 17062 public void setPermissionEnforced(String permission, boolean enforced) { 17063 // TODO: Now that we no longer change GID for storage, this should to away. 17064 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17065 "setPermissionEnforced"); 17066 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17067 synchronized (mPackages) { 17068 if (mSettings.mReadExternalStorageEnforced == null 17069 || mSettings.mReadExternalStorageEnforced != enforced) { 17070 mSettings.mReadExternalStorageEnforced = enforced; 17071 mSettings.writeLPr(); 17072 } 17073 } 17074 // kill any non-foreground processes so we restart them and 17075 // grant/revoke the GID. 17076 final IActivityManager am = ActivityManagerNative.getDefault(); 17077 if (am != null) { 17078 final long token = Binder.clearCallingIdentity(); 17079 try { 17080 am.killProcessesBelowForeground("setPermissionEnforcement"); 17081 } catch (RemoteException e) { 17082 } finally { 17083 Binder.restoreCallingIdentity(token); 17084 } 17085 } 17086 } else { 17087 throw new IllegalArgumentException("No selective enforcement for " + permission); 17088 } 17089 } 17090 17091 @Override 17092 @Deprecated 17093 public boolean isPermissionEnforced(String permission) { 17094 return true; 17095 } 17096 17097 @Override 17098 public boolean isStorageLow() { 17099 final long token = Binder.clearCallingIdentity(); 17100 try { 17101 final DeviceStorageMonitorInternal 17102 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17103 if (dsm != null) { 17104 return dsm.isMemoryLow(); 17105 } else { 17106 return false; 17107 } 17108 } finally { 17109 Binder.restoreCallingIdentity(token); 17110 } 17111 } 17112 17113 @Override 17114 public IPackageInstaller getPackageInstaller() { 17115 return mInstallerService; 17116 } 17117 17118 private boolean userNeedsBadging(int userId) { 17119 int index = mUserNeedsBadging.indexOfKey(userId); 17120 if (index < 0) { 17121 final UserInfo userInfo; 17122 final long token = Binder.clearCallingIdentity(); 17123 try { 17124 userInfo = sUserManager.getUserInfo(userId); 17125 } finally { 17126 Binder.restoreCallingIdentity(token); 17127 } 17128 final boolean b; 17129 if (userInfo != null && userInfo.isManagedProfile()) { 17130 b = true; 17131 } else { 17132 b = false; 17133 } 17134 mUserNeedsBadging.put(userId, b); 17135 return b; 17136 } 17137 return mUserNeedsBadging.valueAt(index); 17138 } 17139 17140 @Override 17141 public KeySet getKeySetByAlias(String packageName, String alias) { 17142 if (packageName == null || alias == null) { 17143 return null; 17144 } 17145 synchronized(mPackages) { 17146 final PackageParser.Package pkg = mPackages.get(packageName); 17147 if (pkg == null) { 17148 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17149 throw new IllegalArgumentException("Unknown package: " + packageName); 17150 } 17151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17152 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17153 } 17154 } 17155 17156 @Override 17157 public KeySet getSigningKeySet(String packageName) { 17158 if (packageName == null) { 17159 return null; 17160 } 17161 synchronized(mPackages) { 17162 final PackageParser.Package pkg = mPackages.get(packageName); 17163 if (pkg == null) { 17164 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17165 throw new IllegalArgumentException("Unknown package: " + packageName); 17166 } 17167 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17168 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17169 throw new SecurityException("May not access signing KeySet of other apps."); 17170 } 17171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17172 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17173 } 17174 } 17175 17176 @Override 17177 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17178 if (packageName == null || ks == null) { 17179 return false; 17180 } 17181 synchronized(mPackages) { 17182 final PackageParser.Package pkg = mPackages.get(packageName); 17183 if (pkg == null) { 17184 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17185 throw new IllegalArgumentException("Unknown package: " + packageName); 17186 } 17187 IBinder ksh = ks.getToken(); 17188 if (ksh instanceof KeySetHandle) { 17189 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17190 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17191 } 17192 return false; 17193 } 17194 } 17195 17196 @Override 17197 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17198 if (packageName == null || ks == null) { 17199 return false; 17200 } 17201 synchronized(mPackages) { 17202 final PackageParser.Package pkg = mPackages.get(packageName); 17203 if (pkg == null) { 17204 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17205 throw new IllegalArgumentException("Unknown package: " + packageName); 17206 } 17207 IBinder ksh = ks.getToken(); 17208 if (ksh instanceof KeySetHandle) { 17209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17210 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17211 } 17212 return false; 17213 } 17214 } 17215 17216 private void deletePackageIfUnusedLPr(final String packageName) { 17217 PackageSetting ps = mSettings.mPackages.get(packageName); 17218 if (ps == null) { 17219 return; 17220 } 17221 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17222 // TODO Implement atomic delete if package is unused 17223 // It is currently possible that the package will be deleted even if it is installed 17224 // after this method returns. 17225 mHandler.post(new Runnable() { 17226 public void run() { 17227 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17228 } 17229 }); 17230 } 17231 } 17232 17233 /** 17234 * Check and throw if the given before/after packages would be considered a 17235 * downgrade. 17236 */ 17237 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17238 throws PackageManagerException { 17239 if (after.versionCode < before.mVersionCode) { 17240 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17241 "Update version code " + after.versionCode + " is older than current " 17242 + before.mVersionCode); 17243 } else if (after.versionCode == before.mVersionCode) { 17244 if (after.baseRevisionCode < before.baseRevisionCode) { 17245 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17246 "Update base revision code " + after.baseRevisionCode 17247 + " is older than current " + before.baseRevisionCode); 17248 } 17249 17250 if (!ArrayUtils.isEmpty(after.splitNames)) { 17251 for (int i = 0; i < after.splitNames.length; i++) { 17252 final String splitName = after.splitNames[i]; 17253 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17254 if (j != -1) { 17255 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17256 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17257 "Update split " + splitName + " revision code " 17258 + after.splitRevisionCodes[i] + " is older than current " 17259 + before.splitRevisionCodes[j]); 17260 } 17261 } 17262 } 17263 } 17264 } 17265 } 17266 17267 private static class MoveCallbacks extends Handler { 17268 private static final int MSG_CREATED = 1; 17269 private static final int MSG_STATUS_CHANGED = 2; 17270 17271 private final RemoteCallbackList<IPackageMoveObserver> 17272 mCallbacks = new RemoteCallbackList<>(); 17273 17274 private final SparseIntArray mLastStatus = new SparseIntArray(); 17275 17276 public MoveCallbacks(Looper looper) { 17277 super(looper); 17278 } 17279 17280 public void register(IPackageMoveObserver callback) { 17281 mCallbacks.register(callback); 17282 } 17283 17284 public void unregister(IPackageMoveObserver callback) { 17285 mCallbacks.unregister(callback); 17286 } 17287 17288 @Override 17289 public void handleMessage(Message msg) { 17290 final SomeArgs args = (SomeArgs) msg.obj; 17291 final int n = mCallbacks.beginBroadcast(); 17292 for (int i = 0; i < n; i++) { 17293 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17294 try { 17295 invokeCallback(callback, msg.what, args); 17296 } catch (RemoteException ignored) { 17297 } 17298 } 17299 mCallbacks.finishBroadcast(); 17300 args.recycle(); 17301 } 17302 17303 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17304 throws RemoteException { 17305 switch (what) { 17306 case MSG_CREATED: { 17307 callback.onCreated(args.argi1, (Bundle) args.arg2); 17308 break; 17309 } 17310 case MSG_STATUS_CHANGED: { 17311 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17312 break; 17313 } 17314 } 17315 } 17316 17317 private void notifyCreated(int moveId, Bundle extras) { 17318 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17319 17320 final SomeArgs args = SomeArgs.obtain(); 17321 args.argi1 = moveId; 17322 args.arg2 = extras; 17323 obtainMessage(MSG_CREATED, args).sendToTarget(); 17324 } 17325 17326 private void notifyStatusChanged(int moveId, int status) { 17327 notifyStatusChanged(moveId, status, -1); 17328 } 17329 17330 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17331 Slog.v(TAG, "Move " + moveId + " status " + status); 17332 17333 final SomeArgs args = SomeArgs.obtain(); 17334 args.argi1 = moveId; 17335 args.argi2 = status; 17336 args.arg3 = estMillis; 17337 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17338 17339 synchronized (mLastStatus) { 17340 mLastStatus.put(moveId, status); 17341 } 17342 } 17343 } 17344 17345 private final static class OnPermissionChangeListeners extends Handler { 17346 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17347 17348 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17349 new RemoteCallbackList<>(); 17350 17351 public OnPermissionChangeListeners(Looper looper) { 17352 super(looper); 17353 } 17354 17355 @Override 17356 public void handleMessage(Message msg) { 17357 switch (msg.what) { 17358 case MSG_ON_PERMISSIONS_CHANGED: { 17359 final int uid = msg.arg1; 17360 handleOnPermissionsChanged(uid); 17361 } break; 17362 } 17363 } 17364 17365 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17366 mPermissionListeners.register(listener); 17367 17368 } 17369 17370 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17371 mPermissionListeners.unregister(listener); 17372 } 17373 17374 public void onPermissionsChanged(int uid) { 17375 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17376 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17377 } 17378 } 17379 17380 private void handleOnPermissionsChanged(int uid) { 17381 final int count = mPermissionListeners.beginBroadcast(); 17382 try { 17383 for (int i = 0; i < count; i++) { 17384 IOnPermissionsChangeListener callback = mPermissionListeners 17385 .getBroadcastItem(i); 17386 try { 17387 callback.onPermissionsChanged(uid); 17388 } catch (RemoteException e) { 17389 Log.e(TAG, "Permission listener is dead", e); 17390 } 17391 } 17392 } finally { 17393 mPermissionListeners.finishBroadcast(); 17394 } 17395 } 17396 } 17397 17398 private class PackageManagerInternalImpl extends PackageManagerInternal { 17399 @Override 17400 public void setLocationPackagesProvider(PackagesProvider provider) { 17401 synchronized (mPackages) { 17402 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17403 } 17404 } 17405 17406 @Override 17407 public void setImePackagesProvider(PackagesProvider provider) { 17408 synchronized (mPackages) { 17409 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17410 } 17411 } 17412 17413 @Override 17414 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17415 synchronized (mPackages) { 17416 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17417 } 17418 } 17419 17420 @Override 17421 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17422 synchronized (mPackages) { 17423 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17424 } 17425 } 17426 17427 @Override 17428 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17429 synchronized (mPackages) { 17430 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17431 } 17432 } 17433 17434 @Override 17435 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17436 synchronized (mPackages) { 17437 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17438 } 17439 } 17440 17441 @Override 17442 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17443 synchronized (mPackages) { 17444 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17445 } 17446 } 17447 17448 @Override 17449 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17450 synchronized (mPackages) { 17451 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17452 packageName, userId); 17453 } 17454 } 17455 17456 @Override 17457 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17458 synchronized (mPackages) { 17459 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17460 packageName, userId); 17461 } 17462 } 17463 17464 @Override 17465 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17466 synchronized (mPackages) { 17467 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17468 packageName, userId); 17469 } 17470 } 17471 17472 @Override 17473 public void setKeepUninstalledPackages(final List<String> packageList) { 17474 Preconditions.checkNotNull(packageList); 17475 List<String> removedFromList = null; 17476 synchronized (mPackages) { 17477 if (mKeepUninstalledPackages != null) { 17478 final int packagesCount = mKeepUninstalledPackages.size(); 17479 for (int i = 0; i < packagesCount; i++) { 17480 String oldPackage = mKeepUninstalledPackages.get(i); 17481 if (packageList != null && packageList.contains(oldPackage)) { 17482 continue; 17483 } 17484 if (removedFromList == null) { 17485 removedFromList = new ArrayList<>(); 17486 } 17487 removedFromList.add(oldPackage); 17488 } 17489 } 17490 mKeepUninstalledPackages = new ArrayList<>(packageList); 17491 if (removedFromList != null) { 17492 final int removedCount = removedFromList.size(); 17493 for (int i = 0; i < removedCount; i++) { 17494 deletePackageIfUnusedLPr(removedFromList.get(i)); 17495 } 17496 } 17497 } 17498 } 17499 17500 @Override 17501 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17502 synchronized (mPackages) { 17503 // If we do not support permission review, done. 17504 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17505 return false; 17506 } 17507 17508 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17509 if (packageSetting == null) { 17510 return false; 17511 } 17512 17513 // Permission review applies only to apps not supporting the new permission model. 17514 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17515 return false; 17516 } 17517 17518 // Legacy apps have the permission and get user consent on launch. 17519 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17520 return permissionsState.isPermissionReviewRequired(userId); 17521 } 17522 } 17523 } 17524 17525 @Override 17526 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17527 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17528 synchronized (mPackages) { 17529 final long identity = Binder.clearCallingIdentity(); 17530 try { 17531 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17532 packageNames, userId); 17533 } finally { 17534 Binder.restoreCallingIdentity(identity); 17535 } 17536 } 17537 } 17538 17539 private static void enforceSystemOrPhoneCaller(String tag) { 17540 int callingUid = Binder.getCallingUid(); 17541 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17542 throw new SecurityException( 17543 "Cannot call " + tag + " from UID " + callingUid); 17544 } 17545 } 17546} 17547