PackageManagerService.java revision cd65448ccd13c4c2d0fe9e9623fec3a898ab9372
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_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.PackageLite; 143import android.content.pm.PackageParser.PackageParserException; 144import android.content.pm.PackageStats; 145import android.content.pm.PackageUserState; 146import android.content.pm.ParceledListSlice; 147import android.content.pm.PermissionGroupInfo; 148import android.content.pm.PermissionInfo; 149import android.content.pm.ProviderInfo; 150import android.content.pm.ResolveInfo; 151import android.content.pm.ServiceInfo; 152import android.content.pm.Signature; 153import android.content.pm.UserInfo; 154import android.content.pm.VerificationParams; 155import android.content.pm.VerifierDeviceIdentity; 156import android.content.pm.VerifierInfo; 157import android.content.res.Resources; 158import android.graphics.Bitmap; 159import android.hardware.display.DisplayManager; 160import android.net.Uri; 161import android.os.Binder; 162import android.os.Build; 163import android.os.Bundle; 164import android.os.Debug; 165import android.os.Environment; 166import android.os.Environment.UserEnvironment; 167import android.os.FileUtils; 168import android.os.Handler; 169import android.os.IBinder; 170import android.os.Looper; 171import android.os.Message; 172import android.os.Parcel; 173import android.os.ParcelFileDescriptor; 174import android.os.Process; 175import android.os.RemoteCallbackList; 176import android.os.RemoteException; 177import android.os.ResultReceiver; 178import android.os.SELinux; 179import android.os.ServiceManager; 180import android.os.SystemClock; 181import android.os.SystemProperties; 182import android.os.Trace; 183import android.os.UserHandle; 184import android.os.UserManager; 185import android.os.storage.IMountService; 186import android.os.storage.MountServiceInternal; 187import android.os.storage.StorageEventListener; 188import android.os.storage.StorageManager; 189import android.os.storage.VolumeInfo; 190import android.os.storage.VolumeRecord; 191import android.security.KeyStore; 192import android.security.SystemKeyStore; 193import android.system.ErrnoException; 194import android.system.Os; 195import android.system.StructStat; 196import android.text.TextUtils; 197import android.text.format.DateUtils; 198import android.util.ArrayMap; 199import android.util.ArraySet; 200import android.util.AtomicFile; 201import android.util.DisplayMetrics; 202import android.util.EventLog; 203import android.util.ExceptionUtils; 204import android.util.Log; 205import android.util.LogPrinter; 206import android.util.MathUtils; 207import android.util.PrintStreamPrinter; 208import android.util.Slog; 209import android.util.SparseArray; 210import android.util.SparseBooleanArray; 211import android.util.SparseIntArray; 212import android.util.Xml; 213import android.view.Display; 214 215import com.android.internal.R; 216import com.android.internal.annotations.GuardedBy; 217import com.android.internal.app.IMediaContainerService; 218import com.android.internal.app.ResolverActivity; 219import com.android.internal.content.NativeLibraryHelper; 220import com.android.internal.content.PackageHelper; 221import com.android.internal.os.IParcelFileDescriptorFactory; 222import com.android.internal.os.SomeArgs; 223import com.android.internal.os.Zygote; 224import com.android.internal.util.ArrayUtils; 225import com.android.internal.util.FastPrintWriter; 226import com.android.internal.util.FastXmlSerializer; 227import com.android.internal.util.IndentingPrintWriter; 228import com.android.internal.util.Preconditions; 229import com.android.server.EventLogTags; 230import com.android.server.FgThread; 231import com.android.server.IntentResolver; 232import com.android.server.LocalServices; 233import com.android.server.ServiceThread; 234import com.android.server.SystemConfig; 235import com.android.server.Watchdog; 236import com.android.server.pm.PermissionsState.PermissionState; 237import com.android.server.pm.Settings.DatabaseVersion; 238import com.android.server.pm.Settings.VersionInfo; 239import com.android.server.storage.DeviceStorageMonitorInternal; 240 241import dalvik.system.DexFile; 242import dalvik.system.VMRuntime; 243 244import libcore.io.IoUtils; 245import libcore.util.EmptyArray; 246 247import org.xmlpull.v1.XmlPullParser; 248import org.xmlpull.v1.XmlPullParserException; 249import org.xmlpull.v1.XmlSerializer; 250 251import java.io.BufferedInputStream; 252import java.io.BufferedOutputStream; 253import java.io.BufferedReader; 254import java.io.ByteArrayInputStream; 255import java.io.ByteArrayOutputStream; 256import java.io.File; 257import java.io.FileDescriptor; 258import java.io.FileNotFoundException; 259import java.io.FileOutputStream; 260import java.io.FileReader; 261import java.io.FilenameFilter; 262import java.io.IOException; 263import java.io.InputStream; 264import java.io.PrintWriter; 265import java.nio.charset.StandardCharsets; 266import java.security.MessageDigest; 267import java.security.NoSuchAlgorithmException; 268import java.security.PublicKey; 269import java.security.cert.CertificateEncodingException; 270import java.security.cert.CertificateException; 271import java.text.SimpleDateFormat; 272import java.util.ArrayList; 273import java.util.Arrays; 274import java.util.Collection; 275import java.util.Collections; 276import java.util.Comparator; 277import java.util.Date; 278import java.util.Iterator; 279import java.util.List; 280import java.util.Map; 281import java.util.Objects; 282import java.util.Set; 283import java.util.concurrent.CountDownLatch; 284import java.util.concurrent.TimeUnit; 285import java.util.concurrent.atomic.AtomicBoolean; 286import java.util.concurrent.atomic.AtomicInteger; 287import java.util.concurrent.atomic.AtomicLong; 288 289/** 290 * Keep track of all those .apks everywhere. 291 * 292 * This is very central to the platform's security; please run the unit 293 * tests whenever making modifications here: 294 * 295runtest -c android.content.pm.PackageManagerTests frameworks-core 296 * 297 * {@hide} 298 */ 299public class PackageManagerService extends IPackageManager.Stub { 300 static final String TAG = "PackageManager"; 301 static final boolean DEBUG_SETTINGS = false; 302 static final boolean DEBUG_PREFERRED = false; 303 static final boolean DEBUG_UPGRADE = false; 304 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 305 private static final boolean DEBUG_BACKUP = false; 306 private static final boolean DEBUG_INSTALL = false; 307 private static final boolean DEBUG_REMOVE = false; 308 private static final boolean DEBUG_BROADCASTS = false; 309 private static final boolean DEBUG_SHOW_INFO = false; 310 private static final boolean DEBUG_PACKAGE_INFO = false; 311 private static final boolean DEBUG_INTENT_MATCHING = false; 312 private static final boolean DEBUG_PACKAGE_SCANNING = false; 313 private static final boolean DEBUG_VERIFY = false; 314 private static final boolean DEBUG_DEXOPT = false; 315 private static final boolean DEBUG_ABI_SELECTION = false; 316 private static final boolean DEBUG_EPHEMERAL = false; 317 private static final boolean DEBUG_TRIAGED_MISSING = false; 318 319 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 320 321 private static final int RADIO_UID = Process.PHONE_UID; 322 private static final int LOG_UID = Process.LOG_UID; 323 private static final int NFC_UID = Process.NFC_UID; 324 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 325 private static final int SHELL_UID = Process.SHELL_UID; 326 327 // Cap the size of permission trees that 3rd party apps can define 328 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 329 330 // Suffix used during package installation when copying/moving 331 // package apks to install directory. 332 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 333 334 static final int SCAN_NO_DEX = 1<<1; 335 static final int SCAN_FORCE_DEX = 1<<2; 336 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 337 static final int SCAN_NEW_INSTALL = 1<<4; 338 static final int SCAN_NO_PATHS = 1<<5; 339 static final int SCAN_UPDATE_TIME = 1<<6; 340 static final int SCAN_DEFER_DEX = 1<<7; 341 static final int SCAN_BOOTING = 1<<8; 342 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 343 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 344 static final int SCAN_REPLACING = 1<<11; 345 static final int SCAN_REQUIRE_KNOWN = 1<<12; 346 static final int SCAN_MOVE = 1<<13; 347 static final int SCAN_INITIAL = 1<<14; 348 349 static final int REMOVE_CHATTY = 1<<16; 350 351 private static final int[] EMPTY_INT_ARRAY = new int[0]; 352 353 /** 354 * Timeout (in milliseconds) after which the watchdog should declare that 355 * our handler thread is wedged. The usual default for such things is one 356 * minute but we sometimes do very lengthy I/O operations on this thread, 357 * such as installing multi-gigabyte applications, so ours needs to be longer. 358 */ 359 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 360 361 /** 362 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 363 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 364 * settings entry if available, otherwise we use the hardcoded default. If it's been 365 * more than this long since the last fstrim, we force one during the boot sequence. 366 * 367 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 368 * one gets run at the next available charging+idle time. This final mandatory 369 * no-fstrim check kicks in only of the other scheduling criteria is never met. 370 */ 371 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 372 373 /** 374 * Whether verification is enabled by default. 375 */ 376 private static final boolean DEFAULT_VERIFY_ENABLE = true; 377 378 /** 379 * The default maximum time to wait for the verification agent to return in 380 * milliseconds. 381 */ 382 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 383 384 /** 385 * The default response for package verification timeout. 386 * 387 * This can be either PackageManager.VERIFICATION_ALLOW or 388 * PackageManager.VERIFICATION_REJECT. 389 */ 390 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 391 392 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 393 394 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 395 DEFAULT_CONTAINER_PACKAGE, 396 "com.android.defcontainer.DefaultContainerService"); 397 398 private static final String KILL_APP_REASON_GIDS_CHANGED = 399 "permission grant or revoke changed gids"; 400 401 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 402 "permissions revoked"; 403 404 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 405 406 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 407 408 /** Permission grant: not grant the permission. */ 409 private static final int GRANT_DENIED = 1; 410 411 /** Permission grant: grant the permission as an install permission. */ 412 private static final int GRANT_INSTALL = 2; 413 414 /** Permission grant: grant the permission as a runtime one. */ 415 private static final int GRANT_RUNTIME = 3; 416 417 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 418 private static final int GRANT_UPGRADE = 4; 419 420 /** Canonical intent used to identify what counts as a "web browser" app */ 421 private static final Intent sBrowserIntent; 422 static { 423 sBrowserIntent = new Intent(); 424 sBrowserIntent.setAction(Intent.ACTION_VIEW); 425 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 426 sBrowserIntent.setData(Uri.parse("http:")); 427 } 428 429 final ServiceThread mHandlerThread; 430 431 final PackageHandler mHandler; 432 433 /** 434 * Messages for {@link #mHandler} that need to wait for system ready before 435 * being dispatched. 436 */ 437 private ArrayList<Message> mPostSystemReadyMessages; 438 439 final int mSdkVersion = Build.VERSION.SDK_INT; 440 441 final Context mContext; 442 final boolean mFactoryTest; 443 final boolean mOnlyCore; 444 final DisplayMetrics mMetrics; 445 final int mDefParseFlags; 446 final String[] mSeparateProcesses; 447 final boolean mIsUpgrade; 448 449 /** The location for ASEC container files on internal storage. */ 450 final String mAsecInternalPath; 451 452 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 453 // LOCK HELD. Can be called with mInstallLock held. 454 @GuardedBy("mInstallLock") 455 final Installer mInstaller; 456 457 /** Directory where installed third-party apps stored */ 458 final File mAppInstallDir; 459 final File mEphemeralInstallDir; 460 461 /** 462 * Directory to which applications installed internally have their 463 * 32 bit native libraries copied. 464 */ 465 private File mAppLib32InstallDir; 466 467 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 468 // apps. 469 final File mDrmAppPrivateInstallDir; 470 471 // ---------------------------------------------------------------- 472 473 // Lock for state used when installing and doing other long running 474 // operations. Methods that must be called with this lock held have 475 // the suffix "LI". 476 final Object mInstallLock = new Object(); 477 478 // ---------------------------------------------------------------- 479 480 // Keys are String (package name), values are Package. This also serves 481 // as the lock for the global state. Methods that must be called with 482 // this lock held have the prefix "LP". 483 @GuardedBy("mPackages") 484 final ArrayMap<String, PackageParser.Package> mPackages = 485 new ArrayMap<String, PackageParser.Package>(); 486 487 // Tracks available target package names -> overlay package paths. 488 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 489 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 490 491 /** 492 * Tracks new system packages [received in an OTA] that we expect to 493 * find updated user-installed versions. Keys are package name, values 494 * are package location. 495 */ 496 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 497 498 /** 499 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 500 */ 501 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 502 /** 503 * Whether or not system app permissions should be promoted from install to runtime. 504 */ 505 boolean mPromoteSystemApps; 506 507 final Settings mSettings; 508 boolean mRestoredSettings; 509 510 // System configuration read by SystemConfig. 511 final int[] mGlobalGids; 512 final SparseArray<ArraySet<String>> mSystemPermissions; 513 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 514 515 // If mac_permissions.xml was found for seinfo labeling. 516 boolean mFoundPolicyFile; 517 518 // If a recursive restorecon of /data/data/<pkg> is needed. 519 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 520 521 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 522 523 public static final class SharedLibraryEntry { 524 public final String path; 525 public final String apk; 526 527 SharedLibraryEntry(String _path, String _apk) { 528 path = _path; 529 apk = _apk; 530 } 531 } 532 533 // Currently known shared libraries. 534 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 535 new ArrayMap<String, SharedLibraryEntry>(); 536 537 // All available activities, for your resolving pleasure. 538 final ActivityIntentResolver mActivities = 539 new ActivityIntentResolver(); 540 541 // All available receivers, for your resolving pleasure. 542 final ActivityIntentResolver mReceivers = 543 new ActivityIntentResolver(); 544 545 // All available services, for your resolving pleasure. 546 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 547 548 // All available providers, for your resolving pleasure. 549 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 550 551 // Mapping from provider base names (first directory in content URI codePath) 552 // to the provider information. 553 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 554 new ArrayMap<String, PackageParser.Provider>(); 555 556 // Mapping from instrumentation class names to info about them. 557 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 558 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 559 560 // Mapping from permission names to info about them. 561 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 562 new ArrayMap<String, PackageParser.PermissionGroup>(); 563 564 // Packages whose data we have transfered into another package, thus 565 // should no longer exist. 566 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 567 568 // Broadcast actions that are only available to the system. 569 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 570 571 /** List of packages waiting for verification. */ 572 final SparseArray<PackageVerificationState> mPendingVerification 573 = new SparseArray<PackageVerificationState>(); 574 575 /** Set of packages associated with each app op permission. */ 576 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 577 578 final PackageInstallerService mInstallerService; 579 580 private final PackageDexOptimizer mPackageDexOptimizer; 581 582 private AtomicInteger mNextMoveId = new AtomicInteger(); 583 private final MoveCallbacks mMoveCallbacks; 584 585 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 586 587 // Cache of users who need badging. 588 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 589 590 /** Token for keys in mPendingVerification. */ 591 private int mPendingVerificationToken = 0; 592 593 volatile boolean mSystemReady; 594 volatile boolean mSafeMode; 595 volatile boolean mHasSystemUidErrors; 596 597 ApplicationInfo mAndroidApplication; 598 final ActivityInfo mResolveActivity = new ActivityInfo(); 599 final ResolveInfo mResolveInfo = new ResolveInfo(); 600 ComponentName mResolveComponentName; 601 PackageParser.Package mPlatformPackage; 602 ComponentName mCustomResolverComponentName; 603 604 boolean mResolverReplaced = false; 605 606 private final @Nullable ComponentName mIntentFilterVerifierComponent; 607 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 608 609 private int mIntentFilterVerificationToken = 0; 610 611 /** Component that knows whether or not an ephemeral application exists */ 612 final ComponentName mEphemeralResolverComponent; 613 /** The service connection to the ephemeral resolver */ 614 final EphemeralResolverConnection mEphemeralResolverConnection; 615 616 /** Component used to install ephemeral applications */ 617 final ComponentName mEphemeralInstallerComponent; 618 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 619 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 620 621 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 622 = new SparseArray<IntentFilterVerificationState>(); 623 624 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 625 new DefaultPermissionGrantPolicy(this); 626 627 // List of packages names to keep cached, even if they are uninstalled for all users 628 private List<String> mKeepUninstalledPackages; 629 630 private static class IFVerificationParams { 631 PackageParser.Package pkg; 632 boolean replacing; 633 int userId; 634 int verifierUid; 635 636 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 637 int _userId, int _verifierUid) { 638 pkg = _pkg; 639 replacing = _replacing; 640 userId = _userId; 641 replacing = _replacing; 642 verifierUid = _verifierUid; 643 } 644 } 645 646 private interface IntentFilterVerifier<T extends IntentFilter> { 647 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 648 T filter, String packageName); 649 void startVerifications(int userId); 650 void receiveVerificationResponse(int verificationId); 651 } 652 653 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 654 private Context mContext; 655 private ComponentName mIntentFilterVerifierComponent; 656 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 657 658 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 659 mContext = context; 660 mIntentFilterVerifierComponent = verifierComponent; 661 } 662 663 private String getDefaultScheme() { 664 return IntentFilter.SCHEME_HTTPS; 665 } 666 667 @Override 668 public void startVerifications(int userId) { 669 // Launch verifications requests 670 int count = mCurrentIntentFilterVerifications.size(); 671 for (int n=0; n<count; n++) { 672 int verificationId = mCurrentIntentFilterVerifications.get(n); 673 final IntentFilterVerificationState ivs = 674 mIntentFilterVerificationStates.get(verificationId); 675 676 String packageName = ivs.getPackageName(); 677 678 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 679 final int filterCount = filters.size(); 680 ArraySet<String> domainsSet = new ArraySet<>(); 681 for (int m=0; m<filterCount; m++) { 682 PackageParser.ActivityIntentInfo filter = filters.get(m); 683 domainsSet.addAll(filter.getHostsList()); 684 } 685 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 686 synchronized (mPackages) { 687 if (mSettings.createIntentFilterVerificationIfNeededLPw( 688 packageName, domainsList) != null) { 689 scheduleWriteSettingsLocked(); 690 } 691 } 692 sendVerificationRequest(userId, verificationId, ivs); 693 } 694 mCurrentIntentFilterVerifications.clear(); 695 } 696 697 private void sendVerificationRequest(int userId, int verificationId, 698 IntentFilterVerificationState ivs) { 699 700 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 701 verificationIntent.putExtra( 702 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 703 verificationId); 704 verificationIntent.putExtra( 705 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 706 getDefaultScheme()); 707 verificationIntent.putExtra( 708 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 709 ivs.getHostsString()); 710 verificationIntent.putExtra( 711 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 712 ivs.getPackageName()); 713 verificationIntent.setComponent(mIntentFilterVerifierComponent); 714 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 715 716 UserHandle user = new UserHandle(userId); 717 mContext.sendBroadcastAsUser(verificationIntent, user); 718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 719 "Sending IntentFilter verification broadcast"); 720 } 721 722 public void receiveVerificationResponse(int verificationId) { 723 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 724 725 final boolean verified = ivs.isVerified(); 726 727 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 728 final int count = filters.size(); 729 if (DEBUG_DOMAIN_VERIFICATION) { 730 Slog.i(TAG, "Received verification response " + verificationId 731 + " for " + count + " filters, verified=" + verified); 732 } 733 for (int n=0; n<count; n++) { 734 PackageParser.ActivityIntentInfo filter = filters.get(n); 735 filter.setVerified(verified); 736 737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 738 + " verified with result:" + verified + " and hosts:" 739 + ivs.getHostsString()); 740 } 741 742 mIntentFilterVerificationStates.remove(verificationId); 743 744 final String packageName = ivs.getPackageName(); 745 IntentFilterVerificationInfo ivi = null; 746 747 synchronized (mPackages) { 748 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 749 } 750 if (ivi == null) { 751 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 752 + verificationId + " packageName:" + packageName); 753 return; 754 } 755 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 756 "Updating IntentFilterVerificationInfo for package " + packageName 757 +" verificationId:" + verificationId); 758 759 synchronized (mPackages) { 760 if (verified) { 761 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 762 } else { 763 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 764 } 765 scheduleWriteSettingsLocked(); 766 767 final int userId = ivs.getUserId(); 768 if (userId != UserHandle.USER_ALL) { 769 final int userStatus = 770 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 771 772 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 773 boolean needUpdate = false; 774 775 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 776 // already been set by the User thru the Disambiguation dialog 777 switch (userStatus) { 778 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 779 if (verified) { 780 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 781 } else { 782 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 783 } 784 needUpdate = true; 785 break; 786 787 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 788 if (verified) { 789 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 790 needUpdate = true; 791 } 792 break; 793 794 default: 795 // Nothing to do 796 } 797 798 if (needUpdate) { 799 mSettings.updateIntentFilterVerificationStatusLPw( 800 packageName, updatedStatus, userId); 801 scheduleWritePackageRestrictionsLocked(userId); 802 } 803 } 804 } 805 } 806 807 @Override 808 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 809 ActivityIntentInfo filter, String packageName) { 810 if (!hasValidDomains(filter)) { 811 return false; 812 } 813 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 814 if (ivs == null) { 815 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 816 packageName); 817 } 818 if (DEBUG_DOMAIN_VERIFICATION) { 819 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 820 } 821 ivs.addFilter(filter); 822 return true; 823 } 824 825 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 826 int userId, int verificationId, String packageName) { 827 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 828 verifierUid, userId, packageName); 829 ivs.setPendingState(); 830 synchronized (mPackages) { 831 mIntentFilterVerificationStates.append(verificationId, ivs); 832 mCurrentIntentFilterVerifications.add(verificationId); 833 } 834 return ivs; 835 } 836 } 837 838 private static boolean hasValidDomains(ActivityIntentInfo filter) { 839 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 840 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 841 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 842 } 843 844 // Set of pending broadcasts for aggregating enable/disable of components. 845 static class PendingPackageBroadcasts { 846 // for each user id, a map of <package name -> components within that package> 847 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 848 849 public PendingPackageBroadcasts() { 850 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 851 } 852 853 public ArrayList<String> get(int userId, String packageName) { 854 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 855 return packages.get(packageName); 856 } 857 858 public void put(int userId, String packageName, ArrayList<String> components) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 packages.put(packageName, components); 861 } 862 863 public void remove(int userId, String packageName) { 864 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 865 if (packages != null) { 866 packages.remove(packageName); 867 } 868 } 869 870 public void remove(int userId) { 871 mUidMap.remove(userId); 872 } 873 874 public int userIdCount() { 875 return mUidMap.size(); 876 } 877 878 public int userIdAt(int n) { 879 return mUidMap.keyAt(n); 880 } 881 882 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 883 return mUidMap.get(userId); 884 } 885 886 public int size() { 887 // total number of pending broadcast entries across all userIds 888 int num = 0; 889 for (int i = 0; i< mUidMap.size(); i++) { 890 num += mUidMap.valueAt(i).size(); 891 } 892 return num; 893 } 894 895 public void clear() { 896 mUidMap.clear(); 897 } 898 899 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 900 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 901 if (map == null) { 902 map = new ArrayMap<String, ArrayList<String>>(); 903 mUidMap.put(userId, map); 904 } 905 return map; 906 } 907 } 908 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 909 910 // Service Connection to remote media container service to copy 911 // package uri's from external media onto secure containers 912 // or internal storage. 913 private IMediaContainerService mContainerService = null; 914 915 static final int SEND_PENDING_BROADCAST = 1; 916 static final int MCS_BOUND = 3; 917 static final int END_COPY = 4; 918 static final int INIT_COPY = 5; 919 static final int MCS_UNBIND = 6; 920 static final int START_CLEANING_PACKAGE = 7; 921 static final int FIND_INSTALL_LOC = 8; 922 static final int POST_INSTALL = 9; 923 static final int MCS_RECONNECT = 10; 924 static final int MCS_GIVE_UP = 11; 925 static final int UPDATED_MEDIA_STATUS = 12; 926 static final int WRITE_SETTINGS = 13; 927 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 928 static final int PACKAGE_VERIFIED = 15; 929 static final int CHECK_PENDING_VERIFICATION = 16; 930 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 931 static final int INTENT_FILTER_VERIFIED = 18; 932 933 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 934 935 // Delay time in millisecs 936 static final int BROADCAST_DELAY = 10 * 1000; 937 938 static UserManagerService sUserManager; 939 940 // Stores a list of users whose package restrictions file needs to be updated 941 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 942 943 final private DefaultContainerConnection mDefContainerConn = 944 new DefaultContainerConnection(); 945 class DefaultContainerConnection implements ServiceConnection { 946 public void onServiceConnected(ComponentName name, IBinder service) { 947 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 948 IMediaContainerService imcs = 949 IMediaContainerService.Stub.asInterface(service); 950 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 951 } 952 953 public void onServiceDisconnected(ComponentName name) { 954 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 955 } 956 } 957 958 // Recordkeeping of restore-after-install operations that are currently in flight 959 // between the Package Manager and the Backup Manager 960 static class PostInstallData { 961 public InstallArgs args; 962 public PackageInstalledInfo res; 963 964 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 965 args = _a; 966 res = _r; 967 } 968 } 969 970 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 971 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 972 973 // XML tags for backup/restore of various bits of state 974 private static final String TAG_PREFERRED_BACKUP = "pa"; 975 private static final String TAG_DEFAULT_APPS = "da"; 976 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 977 978 final @Nullable String mRequiredVerifierPackage; 979 final @Nullable String mRequiredInstallerPackage; 980 981 private final PackageUsage mPackageUsage = new PackageUsage(); 982 983 private class PackageUsage { 984 private static final int WRITE_INTERVAL 985 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 986 987 private final Object mFileLock = new Object(); 988 private final AtomicLong mLastWritten = new AtomicLong(0); 989 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 990 991 private boolean mIsHistoricalPackageUsageAvailable = true; 992 993 boolean isHistoricalPackageUsageAvailable() { 994 return mIsHistoricalPackageUsageAvailable; 995 } 996 997 void write(boolean force) { 998 if (force) { 999 writeInternal(); 1000 return; 1001 } 1002 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1003 && !DEBUG_DEXOPT) { 1004 return; 1005 } 1006 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1007 new Thread("PackageUsage_DiskWriter") { 1008 @Override 1009 public void run() { 1010 try { 1011 writeInternal(); 1012 } finally { 1013 mBackgroundWriteRunning.set(false); 1014 } 1015 } 1016 }.start(); 1017 } 1018 } 1019 1020 private void writeInternal() { 1021 synchronized (mPackages) { 1022 synchronized (mFileLock) { 1023 AtomicFile file = getFile(); 1024 FileOutputStream f = null; 1025 try { 1026 f = file.startWrite(); 1027 BufferedOutputStream out = new BufferedOutputStream(f); 1028 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1029 StringBuilder sb = new StringBuilder(); 1030 for (PackageParser.Package pkg : mPackages.values()) { 1031 if (pkg.mLastPackageUsageTimeInMills == 0) { 1032 continue; 1033 } 1034 sb.setLength(0); 1035 sb.append(pkg.packageName); 1036 sb.append(' '); 1037 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1038 sb.append('\n'); 1039 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1040 } 1041 out.flush(); 1042 file.finishWrite(f); 1043 } catch (IOException e) { 1044 if (f != null) { 1045 file.failWrite(f); 1046 } 1047 Log.e(TAG, "Failed to write package usage times", e); 1048 } 1049 } 1050 } 1051 mLastWritten.set(SystemClock.elapsedRealtime()); 1052 } 1053 1054 void readLP() { 1055 synchronized (mFileLock) { 1056 AtomicFile file = getFile(); 1057 BufferedInputStream in = null; 1058 try { 1059 in = new BufferedInputStream(file.openRead()); 1060 StringBuffer sb = new StringBuffer(); 1061 while (true) { 1062 String packageName = readToken(in, sb, ' '); 1063 if (packageName == null) { 1064 break; 1065 } 1066 String timeInMillisString = readToken(in, sb, '\n'); 1067 if (timeInMillisString == null) { 1068 throw new IOException("Failed to find last usage time for package " 1069 + packageName); 1070 } 1071 PackageParser.Package pkg = mPackages.get(packageName); 1072 if (pkg == null) { 1073 continue; 1074 } 1075 long timeInMillis; 1076 try { 1077 timeInMillis = Long.parseLong(timeInMillisString); 1078 } catch (NumberFormatException e) { 1079 throw new IOException("Failed to parse " + timeInMillisString 1080 + " as a long.", e); 1081 } 1082 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1083 } 1084 } catch (FileNotFoundException expected) { 1085 mIsHistoricalPackageUsageAvailable = false; 1086 } catch (IOException e) { 1087 Log.w(TAG, "Failed to read package usage times", e); 1088 } finally { 1089 IoUtils.closeQuietly(in); 1090 } 1091 } 1092 mLastWritten.set(SystemClock.elapsedRealtime()); 1093 } 1094 1095 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1096 throws IOException { 1097 sb.setLength(0); 1098 while (true) { 1099 int ch = in.read(); 1100 if (ch == -1) { 1101 if (sb.length() == 0) { 1102 return null; 1103 } 1104 throw new IOException("Unexpected EOF"); 1105 } 1106 if (ch == endOfToken) { 1107 return sb.toString(); 1108 } 1109 sb.append((char)ch); 1110 } 1111 } 1112 1113 private AtomicFile getFile() { 1114 File dataDir = Environment.getDataDirectory(); 1115 File systemDir = new File(dataDir, "system"); 1116 File fname = new File(systemDir, "package-usage.list"); 1117 return new AtomicFile(fname); 1118 } 1119 } 1120 1121 class PackageHandler extends Handler { 1122 private boolean mBound = false; 1123 final ArrayList<HandlerParams> mPendingInstalls = 1124 new ArrayList<HandlerParams>(); 1125 1126 private boolean connectToService() { 1127 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1128 " DefaultContainerService"); 1129 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1130 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1131 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1132 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1133 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1134 mBound = true; 1135 return true; 1136 } 1137 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1138 return false; 1139 } 1140 1141 private void disconnectService() { 1142 mContainerService = null; 1143 mBound = false; 1144 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1145 mContext.unbindService(mDefContainerConn); 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1147 } 1148 1149 PackageHandler(Looper looper) { 1150 super(looper); 1151 } 1152 1153 public void handleMessage(Message msg) { 1154 try { 1155 doHandleMessage(msg); 1156 } finally { 1157 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1158 } 1159 } 1160 1161 void doHandleMessage(Message msg) { 1162 switch (msg.what) { 1163 case INIT_COPY: { 1164 HandlerParams params = (HandlerParams) msg.obj; 1165 int idx = mPendingInstalls.size(); 1166 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1167 // If a bind was already initiated we dont really 1168 // need to do anything. The pending install 1169 // will be processed later on. 1170 if (!mBound) { 1171 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1172 System.identityHashCode(mHandler)); 1173 // If this is the only one pending we might 1174 // have to bind to the service again. 1175 if (!connectToService()) { 1176 Slog.e(TAG, "Failed to bind to media container service"); 1177 params.serviceError(); 1178 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1179 System.identityHashCode(mHandler)); 1180 if (params.traceMethod != null) { 1181 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1182 params.traceCookie); 1183 } 1184 return; 1185 } else { 1186 // Once we bind to the service, the first 1187 // pending request will be processed. 1188 mPendingInstalls.add(idx, params); 1189 } 1190 } else { 1191 mPendingInstalls.add(idx, params); 1192 // Already bound to the service. Just make 1193 // sure we trigger off processing the first request. 1194 if (idx == 0) { 1195 mHandler.sendEmptyMessage(MCS_BOUND); 1196 } 1197 } 1198 break; 1199 } 1200 case MCS_BOUND: { 1201 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1202 if (msg.obj != null) { 1203 mContainerService = (IMediaContainerService) msg.obj; 1204 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1205 System.identityHashCode(mHandler)); 1206 } 1207 if (mContainerService == null) { 1208 if (!mBound) { 1209 // Something seriously wrong since we are not bound and we are not 1210 // waiting for connection. Bail out. 1211 Slog.e(TAG, "Cannot bind to media container service"); 1212 for (HandlerParams params : mPendingInstalls) { 1213 // Indicate service bind error 1214 params.serviceError(); 1215 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1216 System.identityHashCode(params)); 1217 if (params.traceMethod != null) { 1218 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1219 params.traceMethod, params.traceCookie); 1220 } 1221 return; 1222 } 1223 mPendingInstalls.clear(); 1224 } else { 1225 Slog.w(TAG, "Waiting to connect to media container service"); 1226 } 1227 } else if (mPendingInstalls.size() > 0) { 1228 HandlerParams params = mPendingInstalls.get(0); 1229 if (params != null) { 1230 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1231 System.identityHashCode(params)); 1232 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1233 if (params.startCopy()) { 1234 // We are done... look for more work or to 1235 // go idle. 1236 if (DEBUG_SD_INSTALL) Log.i(TAG, 1237 "Checking for more work or unbind..."); 1238 // Delete pending install 1239 if (mPendingInstalls.size() > 0) { 1240 mPendingInstalls.remove(0); 1241 } 1242 if (mPendingInstalls.size() == 0) { 1243 if (mBound) { 1244 if (DEBUG_SD_INSTALL) Log.i(TAG, 1245 "Posting delayed MCS_UNBIND"); 1246 removeMessages(MCS_UNBIND); 1247 Message ubmsg = obtainMessage(MCS_UNBIND); 1248 // Unbind after a little delay, to avoid 1249 // continual thrashing. 1250 sendMessageDelayed(ubmsg, 10000); 1251 } 1252 } else { 1253 // There are more pending requests in queue. 1254 // Just post MCS_BOUND message to trigger processing 1255 // of next pending install. 1256 if (DEBUG_SD_INSTALL) Log.i(TAG, 1257 "Posting MCS_BOUND for next work"); 1258 mHandler.sendEmptyMessage(MCS_BOUND); 1259 } 1260 } 1261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1262 } 1263 } else { 1264 // Should never happen ideally. 1265 Slog.w(TAG, "Empty queue"); 1266 } 1267 break; 1268 } 1269 case MCS_RECONNECT: { 1270 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1271 if (mPendingInstalls.size() > 0) { 1272 if (mBound) { 1273 disconnectService(); 1274 } 1275 if (!connectToService()) { 1276 Slog.e(TAG, "Failed to bind to media container service"); 1277 for (HandlerParams params : mPendingInstalls) { 1278 // Indicate service bind error 1279 params.serviceError(); 1280 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1281 System.identityHashCode(params)); 1282 } 1283 mPendingInstalls.clear(); 1284 } 1285 } 1286 break; 1287 } 1288 case MCS_UNBIND: { 1289 // If there is no actual work left, then time to unbind. 1290 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1291 1292 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1293 if (mBound) { 1294 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1295 1296 disconnectService(); 1297 } 1298 } else if (mPendingInstalls.size() > 0) { 1299 // There are more pending requests in queue. 1300 // Just post MCS_BOUND message to trigger processing 1301 // of next pending install. 1302 mHandler.sendEmptyMessage(MCS_BOUND); 1303 } 1304 1305 break; 1306 } 1307 case MCS_GIVE_UP: { 1308 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1309 HandlerParams params = mPendingInstalls.remove(0); 1310 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1311 System.identityHashCode(params)); 1312 break; 1313 } 1314 case SEND_PENDING_BROADCAST: { 1315 String packages[]; 1316 ArrayList<String> components[]; 1317 int size = 0; 1318 int uids[]; 1319 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1320 synchronized (mPackages) { 1321 if (mPendingBroadcasts == null) { 1322 return; 1323 } 1324 size = mPendingBroadcasts.size(); 1325 if (size <= 0) { 1326 // Nothing to be done. Just return 1327 return; 1328 } 1329 packages = new String[size]; 1330 components = new ArrayList[size]; 1331 uids = new int[size]; 1332 int i = 0; // filling out the above arrays 1333 1334 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1335 int packageUserId = mPendingBroadcasts.userIdAt(n); 1336 Iterator<Map.Entry<String, ArrayList<String>>> it 1337 = mPendingBroadcasts.packagesForUserId(packageUserId) 1338 .entrySet().iterator(); 1339 while (it.hasNext() && i < size) { 1340 Map.Entry<String, ArrayList<String>> ent = it.next(); 1341 packages[i] = ent.getKey(); 1342 components[i] = ent.getValue(); 1343 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1344 uids[i] = (ps != null) 1345 ? UserHandle.getUid(packageUserId, ps.appId) 1346 : -1; 1347 i++; 1348 } 1349 } 1350 size = i; 1351 mPendingBroadcasts.clear(); 1352 } 1353 // Send broadcasts 1354 for (int i = 0; i < size; i++) { 1355 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1356 } 1357 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1358 break; 1359 } 1360 case START_CLEANING_PACKAGE: { 1361 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1362 final String packageName = (String)msg.obj; 1363 final int userId = msg.arg1; 1364 final boolean andCode = msg.arg2 != 0; 1365 synchronized (mPackages) { 1366 if (userId == UserHandle.USER_ALL) { 1367 int[] users = sUserManager.getUserIds(); 1368 for (int user : users) { 1369 mSettings.addPackageToCleanLPw( 1370 new PackageCleanItem(user, packageName, andCode)); 1371 } 1372 } else { 1373 mSettings.addPackageToCleanLPw( 1374 new PackageCleanItem(userId, packageName, andCode)); 1375 } 1376 } 1377 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1378 startCleaningPackages(); 1379 } break; 1380 case POST_INSTALL: { 1381 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1382 1383 PostInstallData data = mRunningInstalls.get(msg.arg1); 1384 mRunningInstalls.delete(msg.arg1); 1385 boolean deleteOld = false; 1386 1387 if (data != null) { 1388 InstallArgs args = data.args; 1389 PackageInstalledInfo res = data.res; 1390 1391 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1392 final String packageName = res.pkg.applicationInfo.packageName; 1393 res.removedInfo.sendBroadcast(false, true, false); 1394 Bundle extras = new Bundle(1); 1395 extras.putInt(Intent.EXTRA_UID, res.uid); 1396 1397 // Now that we successfully installed the package, grant runtime 1398 // permissions if requested before broadcasting the install. 1399 if ((args.installFlags 1400 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1401 && res.pkg.applicationInfo.targetSdkVersion 1402 >= Build.VERSION_CODES.M) { 1403 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1404 args.installGrantPermissions); 1405 } 1406 1407 synchronized (mPackages) { 1408 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1409 } 1410 1411 // Determine the set of users who are adding this 1412 // package for the first time vs. those who are seeing 1413 // an update. 1414 int[] firstUsers; 1415 int[] updateUsers = new int[0]; 1416 if (res.origUsers == null || res.origUsers.length == 0) { 1417 firstUsers = res.newUsers; 1418 } else { 1419 firstUsers = new int[0]; 1420 for (int i=0; i<res.newUsers.length; i++) { 1421 int user = res.newUsers[i]; 1422 boolean isNew = true; 1423 for (int j=0; j<res.origUsers.length; j++) { 1424 if (res.origUsers[j] == user) { 1425 isNew = false; 1426 break; 1427 } 1428 } 1429 if (isNew) { 1430 int[] newFirst = new int[firstUsers.length+1]; 1431 System.arraycopy(firstUsers, 0, newFirst, 0, 1432 firstUsers.length); 1433 newFirst[firstUsers.length] = user; 1434 firstUsers = newFirst; 1435 } else { 1436 int[] newUpdate = new int[updateUsers.length+1]; 1437 System.arraycopy(updateUsers, 0, newUpdate, 0, 1438 updateUsers.length); 1439 newUpdate[updateUsers.length] = user; 1440 updateUsers = newUpdate; 1441 } 1442 } 1443 } 1444 // don't broadcast for ephemeral installs/updates 1445 final boolean isEphemeral = isEphemeral(res.pkg); 1446 if (!isEphemeral) { 1447 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1448 extras, 0 /*flags*/, null /*targetPackage*/, 1449 null /*finishedReceiver*/, firstUsers); 1450 } 1451 final boolean update = res.removedInfo.removedPackage != null; 1452 if (update) { 1453 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1454 } 1455 if (!isEphemeral) { 1456 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1457 extras, 0 /*flags*/, null /*targetPackage*/, 1458 null /*finishedReceiver*/, updateUsers); 1459 } 1460 if (update) { 1461 if (!isEphemeral) { 1462 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1463 packageName, extras, 0 /*flags*/, 1464 null /*targetPackage*/, null /*finishedReceiver*/, 1465 updateUsers); 1466 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1467 null /*package*/, null /*extras*/, 0 /*flags*/, 1468 packageName /*targetPackage*/, 1469 null /*finishedReceiver*/, updateUsers); 1470 } 1471 1472 // treat asec-hosted packages like removable media on upgrade 1473 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1474 if (DEBUG_INSTALL) { 1475 Slog.i(TAG, "upgrading pkg " + res.pkg 1476 + " is ASEC-hosted -> AVAILABLE"); 1477 } 1478 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1479 ArrayList<String> pkgList = new ArrayList<String>(1); 1480 pkgList.add(packageName); 1481 sendResourcesChangedBroadcast(true, true, 1482 pkgList,uidArray, null); 1483 } 1484 } 1485 if (res.removedInfo.args != null) { 1486 // Remove the replaced package's older resources safely now 1487 deleteOld = true; 1488 } 1489 1490 // If this app is a browser and it's newly-installed for some 1491 // users, clear any default-browser state in those users 1492 if (firstUsers.length > 0) { 1493 // the app's nature doesn't depend on the user, so we can just 1494 // check its browser nature in any user and generalize. 1495 if (packageIsBrowser(packageName, firstUsers[0])) { 1496 synchronized (mPackages) { 1497 for (int userId : firstUsers) { 1498 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1499 } 1500 } 1501 } 1502 } 1503 // Log current value of "unknown sources" setting 1504 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1505 getUnknownSourcesSettings()); 1506 } 1507 // Force a gc to clear up things 1508 Runtime.getRuntime().gc(); 1509 // We delete after a gc for applications on sdcard. 1510 if (deleteOld) { 1511 synchronized (mInstallLock) { 1512 res.removedInfo.args.doPostDeleteLI(true); 1513 } 1514 } 1515 if (args.observer != null) { 1516 try { 1517 Bundle extras = extrasForInstallResult(res); 1518 args.observer.onPackageInstalled(res.name, res.returnCode, 1519 res.returnMsg, extras); 1520 } catch (RemoteException e) { 1521 Slog.i(TAG, "Observer no longer exists."); 1522 } 1523 } 1524 if (args.traceMethod != null) { 1525 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1526 args.traceCookie); 1527 } 1528 return; 1529 } else { 1530 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1531 } 1532 1533 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1534 } break; 1535 case UPDATED_MEDIA_STATUS: { 1536 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1537 boolean reportStatus = msg.arg1 == 1; 1538 boolean doGc = msg.arg2 == 1; 1539 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1540 if (doGc) { 1541 // Force a gc to clear up stale containers. 1542 Runtime.getRuntime().gc(); 1543 } 1544 if (msg.obj != null) { 1545 @SuppressWarnings("unchecked") 1546 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1548 // Unload containers 1549 unloadAllContainers(args); 1550 } 1551 if (reportStatus) { 1552 try { 1553 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1554 PackageHelper.getMountService().finishMediaUpdate(); 1555 } catch (RemoteException e) { 1556 Log.e(TAG, "MountService not running?"); 1557 } 1558 } 1559 } break; 1560 case WRITE_SETTINGS: { 1561 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1562 synchronized (mPackages) { 1563 removeMessages(WRITE_SETTINGS); 1564 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1565 mSettings.writeLPr(); 1566 mDirtyUsers.clear(); 1567 } 1568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1569 } break; 1570 case WRITE_PACKAGE_RESTRICTIONS: { 1571 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1572 synchronized (mPackages) { 1573 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1574 for (int userId : mDirtyUsers) { 1575 mSettings.writePackageRestrictionsLPr(userId); 1576 } 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case CHECK_PENDING_VERIFICATION: { 1582 final int verificationId = msg.arg1; 1583 final PackageVerificationState state = mPendingVerification.get(verificationId); 1584 1585 if ((state != null) && !state.timeoutExtended()) { 1586 final InstallArgs args = state.getInstallArgs(); 1587 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1588 1589 Slog.i(TAG, "Verification timed out for " + originUri); 1590 mPendingVerification.remove(verificationId); 1591 1592 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1593 1594 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1595 Slog.i(TAG, "Continuing with installation of " + originUri); 1596 state.setVerifierResponse(Binder.getCallingUid(), 1597 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1598 broadcastPackageVerified(verificationId, originUri, 1599 PackageManager.VERIFICATION_ALLOW, 1600 state.getInstallArgs().getUser()); 1601 try { 1602 ret = args.copyApk(mContainerService, true); 1603 } catch (RemoteException e) { 1604 Slog.e(TAG, "Could not contact the ContainerService"); 1605 } 1606 } else { 1607 broadcastPackageVerified(verificationId, originUri, 1608 PackageManager.VERIFICATION_REJECT, 1609 state.getInstallArgs().getUser()); 1610 } 1611 1612 Trace.asyncTraceEnd( 1613 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1614 1615 processPendingInstall(args, ret); 1616 mHandler.sendEmptyMessage(MCS_UNBIND); 1617 } 1618 break; 1619 } 1620 case PACKAGE_VERIFIED: { 1621 final int verificationId = msg.arg1; 1622 1623 final PackageVerificationState state = mPendingVerification.get(verificationId); 1624 if (state == null) { 1625 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1626 break; 1627 } 1628 1629 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1630 1631 state.setVerifierResponse(response.callerUid, response.code); 1632 1633 if (state.isVerificationComplete()) { 1634 mPendingVerification.remove(verificationId); 1635 1636 final InstallArgs args = state.getInstallArgs(); 1637 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1638 1639 int ret; 1640 if (state.isInstallAllowed()) { 1641 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1642 broadcastPackageVerified(verificationId, originUri, 1643 response.code, state.getInstallArgs().getUser()); 1644 try { 1645 ret = args.copyApk(mContainerService, true); 1646 } catch (RemoteException e) { 1647 Slog.e(TAG, "Could not contact the ContainerService"); 1648 } 1649 } else { 1650 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1651 } 1652 1653 Trace.asyncTraceEnd( 1654 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1655 1656 processPendingInstall(args, ret); 1657 mHandler.sendEmptyMessage(MCS_UNBIND); 1658 } 1659 1660 break; 1661 } 1662 case START_INTENT_FILTER_VERIFICATIONS: { 1663 IFVerificationParams params = (IFVerificationParams) msg.obj; 1664 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1665 params.replacing, params.pkg); 1666 break; 1667 } 1668 case INTENT_FILTER_VERIFIED: { 1669 final int verificationId = msg.arg1; 1670 1671 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1672 verificationId); 1673 if (state == null) { 1674 Slog.w(TAG, "Invalid IntentFilter verification token " 1675 + verificationId + " received"); 1676 break; 1677 } 1678 1679 final int userId = state.getUserId(); 1680 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1682 "Processing IntentFilter verification with token:" 1683 + verificationId + " and userId:" + userId); 1684 1685 final IntentFilterVerificationResponse response = 1686 (IntentFilterVerificationResponse) msg.obj; 1687 1688 state.setVerifierResponse(response.callerUid, response.code); 1689 1690 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1691 "IntentFilter verification with token:" + verificationId 1692 + " and userId:" + userId 1693 + " is settings verifier response with response code:" 1694 + response.code); 1695 1696 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1697 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1698 + response.getFailedDomainsString()); 1699 } 1700 1701 if (state.isVerificationComplete()) { 1702 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1703 } else { 1704 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1705 "IntentFilter verification with token:" + verificationId 1706 + " was not said to be complete"); 1707 } 1708 1709 break; 1710 } 1711 } 1712 } 1713 } 1714 1715 private StorageEventListener mStorageListener = new StorageEventListener() { 1716 @Override 1717 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1718 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1719 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1720 final String volumeUuid = vol.getFsUuid(); 1721 1722 // Clean up any users or apps that were removed or recreated 1723 // while this volume was missing 1724 reconcileUsers(volumeUuid); 1725 reconcileApps(volumeUuid); 1726 1727 // Clean up any install sessions that expired or were 1728 // cancelled while this volume was missing 1729 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1730 1731 loadPrivatePackages(vol); 1732 1733 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1734 unloadPrivatePackages(vol); 1735 } 1736 } 1737 1738 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1739 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1740 updateExternalMediaStatus(true, false); 1741 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1742 updateExternalMediaStatus(false, false); 1743 } 1744 } 1745 } 1746 1747 @Override 1748 public void onVolumeForgotten(String fsUuid) { 1749 if (TextUtils.isEmpty(fsUuid)) { 1750 Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1751 return; 1752 } 1753 1754 // Remove any apps installed on the forgotten volume 1755 synchronized (mPackages) { 1756 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1757 for (PackageSetting ps : packages) { 1758 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1759 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1760 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1761 } 1762 1763 mSettings.onVolumeForgotten(fsUuid); 1764 mSettings.writeLPr(); 1765 } 1766 } 1767 }; 1768 1769 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1770 String[] grantedPermissions) { 1771 if (userId >= UserHandle.USER_SYSTEM) { 1772 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1773 } else if (userId == UserHandle.USER_ALL) { 1774 final int[] userIds; 1775 synchronized (mPackages) { 1776 userIds = UserManagerService.getInstance().getUserIds(); 1777 } 1778 for (int someUserId : userIds) { 1779 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1780 } 1781 } 1782 1783 // We could have touched GID membership, so flush out packages.list 1784 synchronized (mPackages) { 1785 mSettings.writePackageListLPr(); 1786 } 1787 } 1788 1789 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1790 String[] grantedPermissions) { 1791 SettingBase sb = (SettingBase) pkg.mExtras; 1792 if (sb == null) { 1793 return; 1794 } 1795 1796 PermissionsState permissionsState = sb.getPermissionsState(); 1797 1798 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1799 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1800 1801 synchronized (mPackages) { 1802 for (String permission : pkg.requestedPermissions) { 1803 BasePermission bp = mSettings.mPermissions.get(permission); 1804 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1805 && (grantedPermissions == null 1806 || ArrayUtils.contains(grantedPermissions, permission))) { 1807 final int flags = permissionsState.getPermissionFlags(permission, userId); 1808 // Installer cannot change immutable permissions. 1809 if ((flags & immutableFlags) == 0) { 1810 grantRuntimePermission(pkg.packageName, permission, userId); 1811 } 1812 } 1813 } 1814 } 1815 } 1816 1817 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1818 Bundle extras = null; 1819 switch (res.returnCode) { 1820 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1821 extras = new Bundle(); 1822 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1823 res.origPermission); 1824 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1825 res.origPackage); 1826 break; 1827 } 1828 case PackageManager.INSTALL_SUCCEEDED: { 1829 extras = new Bundle(); 1830 extras.putBoolean(Intent.EXTRA_REPLACING, 1831 res.removedInfo != null && res.removedInfo.removedPackage != null); 1832 break; 1833 } 1834 } 1835 return extras; 1836 } 1837 1838 void scheduleWriteSettingsLocked() { 1839 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1840 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1841 } 1842 } 1843 1844 void scheduleWritePackageRestrictionsLocked(int userId) { 1845 if (!sUserManager.exists(userId)) return; 1846 mDirtyUsers.add(userId); 1847 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1848 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1849 } 1850 } 1851 1852 public static PackageManagerService main(Context context, Installer installer, 1853 boolean factoryTest, boolean onlyCore) { 1854 PackageManagerService m = new PackageManagerService(context, installer, 1855 factoryTest, onlyCore); 1856 m.enableSystemUserPackages(); 1857 ServiceManager.addService("package", m); 1858 return m; 1859 } 1860 1861 private void enableSystemUserPackages() { 1862 if (!UserManager.isSplitSystemUser()) { 1863 return; 1864 } 1865 // For system user, enable apps based on the following conditions: 1866 // - app is whitelisted or belong to one of these groups: 1867 // -- system app which has no launcher icons 1868 // -- system app which has INTERACT_ACROSS_USERS permission 1869 // -- system IME app 1870 // - app is not in the blacklist 1871 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1872 Set<String> enableApps = new ArraySet<>(); 1873 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1874 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1875 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1876 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1877 enableApps.addAll(wlApps); 1878 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1879 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1880 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1881 enableApps.removeAll(blApps); 1882 Log.i(TAG, "Applications installed for system user: " + enableApps); 1883 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1884 UserHandle.SYSTEM); 1885 final int allAppsSize = allAps.size(); 1886 synchronized (mPackages) { 1887 for (int i = 0; i < allAppsSize; i++) { 1888 String pName = allAps.get(i); 1889 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1890 // Should not happen, but we shouldn't be failing if it does 1891 if (pkgSetting == null) { 1892 continue; 1893 } 1894 boolean install = enableApps.contains(pName); 1895 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1896 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1897 + " for system user"); 1898 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1899 } 1900 } 1901 } 1902 } 1903 1904 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1905 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1906 Context.DISPLAY_SERVICE); 1907 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1908 } 1909 1910 public PackageManagerService(Context context, Installer installer, 1911 boolean factoryTest, boolean onlyCore) { 1912 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1913 SystemClock.uptimeMillis()); 1914 1915 if (mSdkVersion <= 0) { 1916 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1917 } 1918 1919 mContext = context; 1920 mFactoryTest = factoryTest; 1921 mOnlyCore = onlyCore; 1922 mMetrics = new DisplayMetrics(); 1923 mSettings = new Settings(mPackages); 1924 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1925 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1926 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1927 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1928 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1929 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1930 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1931 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1932 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1933 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1934 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1935 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1936 1937 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1938 if (separateProcesses != null && separateProcesses.length() > 0) { 1939 if ("*".equals(separateProcesses)) { 1940 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1941 mSeparateProcesses = null; 1942 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1943 } else { 1944 mDefParseFlags = 0; 1945 mSeparateProcesses = separateProcesses.split(","); 1946 Slog.w(TAG, "Running with debug.separate_processes: " 1947 + separateProcesses); 1948 } 1949 } else { 1950 mDefParseFlags = 0; 1951 mSeparateProcesses = null; 1952 } 1953 1954 mInstaller = installer; 1955 mPackageDexOptimizer = new PackageDexOptimizer(this); 1956 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1957 1958 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1959 FgThread.get().getLooper()); 1960 1961 getDefaultDisplayMetrics(context, mMetrics); 1962 1963 SystemConfig systemConfig = SystemConfig.getInstance(); 1964 mGlobalGids = systemConfig.getGlobalGids(); 1965 mSystemPermissions = systemConfig.getSystemPermissions(); 1966 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1967 1968 synchronized (mInstallLock) { 1969 // writer 1970 synchronized (mPackages) { 1971 mHandlerThread = new ServiceThread(TAG, 1972 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1973 mHandlerThread.start(); 1974 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1975 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1976 1977 File dataDir = Environment.getDataDirectory(); 1978 mAppInstallDir = new File(dataDir, "app"); 1979 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1980 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 1981 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1982 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1983 1984 sUserManager = new UserManagerService(context, this, mPackages); 1985 1986 // Propagate permission configuration in to package manager. 1987 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1988 = systemConfig.getPermissions(); 1989 for (int i=0; i<permConfig.size(); i++) { 1990 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1991 BasePermission bp = mSettings.mPermissions.get(perm.name); 1992 if (bp == null) { 1993 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1994 mSettings.mPermissions.put(perm.name, bp); 1995 } 1996 if (perm.gids != null) { 1997 bp.setGids(perm.gids, perm.perUser); 1998 } 1999 } 2000 2001 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2002 for (int i=0; i<libConfig.size(); i++) { 2003 mSharedLibraries.put(libConfig.keyAt(i), 2004 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2005 } 2006 2007 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2008 2009 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2010 2011 String customResolverActivity = Resources.getSystem().getString( 2012 R.string.config_customResolverActivity); 2013 if (TextUtils.isEmpty(customResolverActivity)) { 2014 customResolverActivity = null; 2015 } else { 2016 mCustomResolverComponentName = ComponentName.unflattenFromString( 2017 customResolverActivity); 2018 } 2019 2020 long startTime = SystemClock.uptimeMillis(); 2021 2022 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2023 startTime); 2024 2025 // Set flag to monitor and not change apk file paths when 2026 // scanning install directories. 2027 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2028 2029 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2030 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2031 2032 if (bootClassPath == null) { 2033 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2034 } 2035 2036 if (systemServerClassPath == null) { 2037 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2038 } 2039 2040 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2041 final String[] dexCodeInstructionSets = 2042 getDexCodeInstructionSets( 2043 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2044 2045 /** 2046 * Ensure all external libraries have had dexopt run on them. 2047 */ 2048 if (mSharedLibraries.size() > 0) { 2049 // NOTE: For now, we're compiling these system "shared libraries" 2050 // (and framework jars) into all available architectures. It's possible 2051 // to compile them only when we come across an app that uses them (there's 2052 // already logic for that in scanPackageLI) but that adds some complexity. 2053 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2054 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2055 final String lib = libEntry.path; 2056 if (lib == null) { 2057 continue; 2058 } 2059 2060 try { 2061 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2062 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2063 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2064 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/); 2065 } 2066 } catch (FileNotFoundException e) { 2067 Slog.w(TAG, "Library not found: " + lib); 2068 } catch (IOException e) { 2069 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2070 + e.getMessage()); 2071 } 2072 } 2073 } 2074 } 2075 2076 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2077 2078 final VersionInfo ver = mSettings.getInternalVersion(); 2079 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2080 // when upgrading from pre-M, promote system app permissions from install to runtime 2081 mPromoteSystemApps = 2082 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2083 2084 // save off the names of pre-existing system packages prior to scanning; we don't 2085 // want to automatically grant runtime permissions for new system apps 2086 if (mPromoteSystemApps) { 2087 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2088 while (pkgSettingIter.hasNext()) { 2089 PackageSetting ps = pkgSettingIter.next(); 2090 if (isSystemApp(ps)) { 2091 mExistingSystemPackages.add(ps.name); 2092 } 2093 } 2094 } 2095 2096 // Collect vendor overlay packages. 2097 // (Do this before scanning any apps.) 2098 // For security and version matching reason, only consider 2099 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2100 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2101 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2102 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2103 2104 // Find base frameworks (resource packages without code). 2105 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2106 | PackageParser.PARSE_IS_SYSTEM_DIR 2107 | PackageParser.PARSE_IS_PRIVILEGED, 2108 scanFlags | SCAN_NO_DEX, 0); 2109 2110 // Collected privileged system packages. 2111 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2112 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2113 | PackageParser.PARSE_IS_SYSTEM_DIR 2114 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2115 2116 // Collect ordinary system packages. 2117 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2118 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2119 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2120 2121 // Collect all vendor packages. 2122 File vendorAppDir = new File("/vendor/app"); 2123 try { 2124 vendorAppDir = vendorAppDir.getCanonicalFile(); 2125 } catch (IOException e) { 2126 // failed to look up canonical path, continue with original one 2127 } 2128 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2129 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2130 2131 // Collect all OEM packages. 2132 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2133 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2134 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2135 2136 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 2137 mInstaller.moveFiles(); 2138 2139 // Prune any system packages that no longer exist. 2140 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2141 if (!mOnlyCore) { 2142 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2143 while (psit.hasNext()) { 2144 PackageSetting ps = psit.next(); 2145 2146 /* 2147 * If this is not a system app, it can't be a 2148 * disable system app. 2149 */ 2150 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2151 continue; 2152 } 2153 2154 /* 2155 * If the package is scanned, it's not erased. 2156 */ 2157 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2158 if (scannedPkg != null) { 2159 /* 2160 * If the system app is both scanned and in the 2161 * disabled packages list, then it must have been 2162 * added via OTA. Remove it from the currently 2163 * scanned package so the previously user-installed 2164 * application can be scanned. 2165 */ 2166 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2167 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2168 + ps.name + "; removing system app. Last known codePath=" 2169 + ps.codePathString + ", installStatus=" + ps.installStatus 2170 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2171 + scannedPkg.mVersionCode); 2172 removePackageLI(ps, true); 2173 mExpectingBetter.put(ps.name, ps.codePath); 2174 } 2175 2176 continue; 2177 } 2178 2179 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2180 psit.remove(); 2181 logCriticalInfo(Log.WARN, "System package " + ps.name 2182 + " no longer exists; wiping its data"); 2183 removeDataDirsLI(null, ps.name); 2184 } else { 2185 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2186 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2187 possiblyDeletedUpdatedSystemApps.add(ps.name); 2188 } 2189 } 2190 } 2191 } 2192 2193 //look for any incomplete package installations 2194 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2195 //clean up list 2196 for(int i = 0; i < deletePkgsList.size(); i++) { 2197 //clean up here 2198 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2199 } 2200 //delete tmp files 2201 deleteTempPackageFiles(); 2202 2203 // Remove any shared userIDs that have no associated packages 2204 mSettings.pruneSharedUsersLPw(); 2205 2206 if (!mOnlyCore) { 2207 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2208 SystemClock.uptimeMillis()); 2209 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2210 2211 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2212 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2213 2214 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2215 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2216 2217 /** 2218 * Remove disable package settings for any updated system 2219 * apps that were removed via an OTA. If they're not a 2220 * previously-updated app, remove them completely. 2221 * Otherwise, just revoke their system-level permissions. 2222 */ 2223 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2224 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2225 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2226 2227 String msg; 2228 if (deletedPkg == null) { 2229 msg = "Updated system package " + deletedAppName 2230 + " no longer exists; wiping its data"; 2231 removeDataDirsLI(null, deletedAppName); 2232 } else { 2233 msg = "Updated system app + " + deletedAppName 2234 + " no longer present; removing system privileges for " 2235 + deletedAppName; 2236 2237 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2238 2239 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2240 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2241 } 2242 logCriticalInfo(Log.WARN, msg); 2243 } 2244 2245 /** 2246 * Make sure all system apps that we expected to appear on 2247 * the userdata partition actually showed up. If they never 2248 * appeared, crawl back and revive the system version. 2249 */ 2250 for (int i = 0; i < mExpectingBetter.size(); i++) { 2251 final String packageName = mExpectingBetter.keyAt(i); 2252 if (!mPackages.containsKey(packageName)) { 2253 final File scanFile = mExpectingBetter.valueAt(i); 2254 2255 logCriticalInfo(Log.WARN, "Expected better " + packageName 2256 + " but never showed up; reverting to system"); 2257 2258 final int reparseFlags; 2259 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2260 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR 2262 | PackageParser.PARSE_IS_PRIVILEGED; 2263 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2264 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2265 | PackageParser.PARSE_IS_SYSTEM_DIR; 2266 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2267 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2268 | PackageParser.PARSE_IS_SYSTEM_DIR; 2269 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2270 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2271 | PackageParser.PARSE_IS_SYSTEM_DIR; 2272 } else { 2273 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2274 continue; 2275 } 2276 2277 mSettings.enableSystemPackageLPw(packageName); 2278 2279 try { 2280 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2281 } catch (PackageManagerException e) { 2282 Slog.e(TAG, "Failed to parse original system package: " 2283 + e.getMessage()); 2284 } 2285 } 2286 } 2287 } 2288 mExpectingBetter.clear(); 2289 2290 // Now that we know all of the shared libraries, update all clients to have 2291 // the correct library paths. 2292 updateAllSharedLibrariesLPw(); 2293 2294 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2295 // NOTE: We ignore potential failures here during a system scan (like 2296 // the rest of the commands above) because there's precious little we 2297 // can do about it. A settings error is reported, though. 2298 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2299 false /* boot complete */); 2300 } 2301 2302 // Now that we know all the packages we are keeping, 2303 // read and update their last usage times. 2304 mPackageUsage.readLP(); 2305 2306 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2307 SystemClock.uptimeMillis()); 2308 Slog.i(TAG, "Time to scan packages: " 2309 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2310 + " seconds"); 2311 2312 // If the platform SDK has changed since the last time we booted, 2313 // we need to re-grant app permission to catch any new ones that 2314 // appear. This is really a hack, and means that apps can in some 2315 // cases get permissions that the user didn't initially explicitly 2316 // allow... it would be nice to have some better way to handle 2317 // this situation. 2318 int updateFlags = UPDATE_PERMISSIONS_ALL; 2319 if (ver.sdkVersion != mSdkVersion) { 2320 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2321 + mSdkVersion + "; regranting permissions for internal storage"); 2322 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2323 } 2324 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2325 ver.sdkVersion = mSdkVersion; 2326 2327 // If this is the first boot or an update from pre-M, and it is a normal 2328 // boot, then we need to initialize the default preferred apps across 2329 // all defined users. 2330 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2331 for (UserInfo user : sUserManager.getUsers(true)) { 2332 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2333 applyFactoryDefaultBrowserLPw(user.id); 2334 primeDomainVerificationsLPw(user.id); 2335 } 2336 } 2337 2338 // If this is first boot after an OTA, and a normal boot, then 2339 // we need to clear code cache directories. 2340 if (mIsUpgrade && !onlyCore) { 2341 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2342 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2343 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2344 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2345 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2346 } 2347 } 2348 ver.fingerprint = Build.FINGERPRINT; 2349 } 2350 2351 checkDefaultBrowser(); 2352 2353 // clear only after permissions and other defaults have been updated 2354 mExistingSystemPackages.clear(); 2355 mPromoteSystemApps = false; 2356 2357 // All the changes are done during package scanning. 2358 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2359 2360 // can downgrade to reader 2361 mSettings.writeLPr(); 2362 2363 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2364 SystemClock.uptimeMillis()); 2365 2366 if (!mOnlyCore) { 2367 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2368 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2369 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2370 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2371 mIntentFilterVerifierComponent); 2372 } else { 2373 mRequiredVerifierPackage = null; 2374 mRequiredInstallerPackage = null; 2375 mIntentFilterVerifierComponent = null; 2376 mIntentFilterVerifier = null; 2377 } 2378 2379 mInstallerService = new PackageInstallerService(context, this); 2380 2381 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2382 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2383 // both the installer and resolver must be present to enable ephemeral 2384 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2385 if (DEBUG_EPHEMERAL) { 2386 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2387 + " installer:" + ephemeralInstallerComponent); 2388 } 2389 mEphemeralResolverComponent = ephemeralResolverComponent; 2390 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2391 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2392 mEphemeralResolverConnection = 2393 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2394 } else { 2395 if (DEBUG_EPHEMERAL) { 2396 final String missingComponent = 2397 (ephemeralResolverComponent == null) 2398 ? (ephemeralInstallerComponent == null) 2399 ? "resolver and installer" 2400 : "resolver" 2401 : "installer"; 2402 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2403 } 2404 mEphemeralResolverComponent = null; 2405 mEphemeralInstallerComponent = null; 2406 mEphemeralResolverConnection = null; 2407 } 2408 2409 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2410 } // synchronized (mPackages) 2411 } // synchronized (mInstallLock) 2412 2413 // Now after opening every single application zip, make sure they 2414 // are all flushed. Not really needed, but keeps things nice and 2415 // tidy. 2416 Runtime.getRuntime().gc(); 2417 2418 // The initial scanning above does many calls into installd while 2419 // holding the mPackages lock, but we're mostly interested in yelling 2420 // once we have a booted system. 2421 mInstaller.setWarnIfHeld(mPackages); 2422 2423 // Expose private service for system components to use. 2424 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2425 } 2426 2427 @Override 2428 public boolean isFirstBoot() { 2429 return !mRestoredSettings; 2430 } 2431 2432 @Override 2433 public boolean isOnlyCoreApps() { 2434 return mOnlyCore; 2435 } 2436 2437 @Override 2438 public boolean isUpgrade() { 2439 return mIsUpgrade; 2440 } 2441 2442 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2443 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2444 2445 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2446 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2447 if (matches.size() == 1) { 2448 return matches.get(0).getComponentInfo().packageName; 2449 } else { 2450 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2451 return null; 2452 } 2453 } 2454 2455 private @NonNull String getRequiredInstallerLPr() { 2456 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2457 intent.addCategory(Intent.CATEGORY_DEFAULT); 2458 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2459 2460 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2461 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2462 if (matches.size() == 1) { 2463 return matches.get(0).getComponentInfo().packageName; 2464 } else { 2465 throw new RuntimeException("There must be exactly one installer; found " + matches); 2466 } 2467 } 2468 2469 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2470 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2471 2472 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2473 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2474 ResolveInfo best = null; 2475 final int N = matches.size(); 2476 for (int i = 0; i < N; i++) { 2477 final ResolveInfo cur = matches.get(i); 2478 final String packageName = cur.getComponentInfo().packageName; 2479 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2480 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2481 continue; 2482 } 2483 2484 if (best == null || cur.priority > best.priority) { 2485 best = cur; 2486 } 2487 } 2488 2489 if (best != null) { 2490 return best.getComponentInfo().getComponentName(); 2491 } else { 2492 throw new RuntimeException("There must be at least one intent filter verifier"); 2493 } 2494 } 2495 2496 private @Nullable ComponentName getEphemeralResolverLPr() { 2497 final String[] packageArray = 2498 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2499 if (packageArray.length == 0) { 2500 if (DEBUG_EPHEMERAL) { 2501 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2502 } 2503 return null; 2504 } 2505 2506 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2507 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2508 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2509 2510 final int N = resolvers.size(); 2511 if (N == 0) { 2512 if (DEBUG_EPHEMERAL) { 2513 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2514 } 2515 return null; 2516 } 2517 2518 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2519 for (int i = 0; i < N; i++) { 2520 final ResolveInfo info = resolvers.get(i); 2521 2522 if (info.serviceInfo == null) { 2523 continue; 2524 } 2525 2526 final String packageName = info.serviceInfo.packageName; 2527 if (!possiblePackages.contains(packageName)) { 2528 if (DEBUG_EPHEMERAL) { 2529 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2530 + " pkg: " + packageName + ", info:" + info); 2531 } 2532 continue; 2533 } 2534 2535 if (DEBUG_EPHEMERAL) { 2536 Slog.v(TAG, "Ephemeral resolver found;" 2537 + " pkg: " + packageName + ", info:" + info); 2538 } 2539 return new ComponentName(packageName, info.serviceInfo.name); 2540 } 2541 if (DEBUG_EPHEMERAL) { 2542 Slog.v(TAG, "Ephemeral resolver NOT found"); 2543 } 2544 return null; 2545 } 2546 2547 private @Nullable ComponentName getEphemeralInstallerLPr() { 2548 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2549 intent.addCategory(Intent.CATEGORY_DEFAULT); 2550 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2551 2552 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2553 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2554 if (matches.size() == 0) { 2555 return null; 2556 } else if (matches.size() == 1) { 2557 return matches.get(0).getComponentInfo().getComponentName(); 2558 } else { 2559 throw new RuntimeException( 2560 "There must be at most one ephemeral installer; found " + matches); 2561 } 2562 } 2563 2564 private void primeDomainVerificationsLPw(int userId) { 2565 if (DEBUG_DOMAIN_VERIFICATION) { 2566 Slog.d(TAG, "Priming domain verifications in user " + userId); 2567 } 2568 2569 SystemConfig systemConfig = SystemConfig.getInstance(); 2570 ArraySet<String> packages = systemConfig.getLinkedApps(); 2571 ArraySet<String> domains = new ArraySet<String>(); 2572 2573 for (String packageName : packages) { 2574 PackageParser.Package pkg = mPackages.get(packageName); 2575 if (pkg != null) { 2576 if (!pkg.isSystemApp()) { 2577 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2578 continue; 2579 } 2580 2581 domains.clear(); 2582 for (PackageParser.Activity a : pkg.activities) { 2583 for (ActivityIntentInfo filter : a.intents) { 2584 if (hasValidDomains(filter)) { 2585 domains.addAll(filter.getHostsList()); 2586 } 2587 } 2588 } 2589 2590 if (domains.size() > 0) { 2591 if (DEBUG_DOMAIN_VERIFICATION) { 2592 Slog.v(TAG, " + " + packageName); 2593 } 2594 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2595 // state w.r.t. the formal app-linkage "no verification attempted" state; 2596 // and then 'always' in the per-user state actually used for intent resolution. 2597 final IntentFilterVerificationInfo ivi; 2598 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2599 new ArrayList<String>(domains)); 2600 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2601 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2602 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2603 } else { 2604 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2605 + "' does not handle web links"); 2606 } 2607 } else { 2608 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2609 } 2610 } 2611 2612 scheduleWritePackageRestrictionsLocked(userId); 2613 scheduleWriteSettingsLocked(); 2614 } 2615 2616 private void applyFactoryDefaultBrowserLPw(int userId) { 2617 // The default browser app's package name is stored in a string resource, 2618 // with a product-specific overlay used for vendor customization. 2619 String browserPkg = mContext.getResources().getString( 2620 com.android.internal.R.string.default_browser); 2621 if (!TextUtils.isEmpty(browserPkg)) { 2622 // non-empty string => required to be a known package 2623 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2624 if (ps == null) { 2625 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2626 browserPkg = null; 2627 } else { 2628 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2629 } 2630 } 2631 2632 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2633 // default. If there's more than one, just leave everything alone. 2634 if (browserPkg == null) { 2635 calculateDefaultBrowserLPw(userId); 2636 } 2637 } 2638 2639 private void calculateDefaultBrowserLPw(int userId) { 2640 List<String> allBrowsers = resolveAllBrowserApps(userId); 2641 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2642 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2643 } 2644 2645 private List<String> resolveAllBrowserApps(int userId) { 2646 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2647 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2648 PackageManager.MATCH_ALL, userId); 2649 2650 final int count = list.size(); 2651 List<String> result = new ArrayList<String>(count); 2652 for (int i=0; i<count; i++) { 2653 ResolveInfo info = list.get(i); 2654 if (info.activityInfo == null 2655 || !info.handleAllWebDataURI 2656 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2657 || result.contains(info.activityInfo.packageName)) { 2658 continue; 2659 } 2660 result.add(info.activityInfo.packageName); 2661 } 2662 2663 return result; 2664 } 2665 2666 private boolean packageIsBrowser(String packageName, int userId) { 2667 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2668 PackageManager.MATCH_ALL, userId); 2669 final int N = list.size(); 2670 for (int i = 0; i < N; i++) { 2671 ResolveInfo info = list.get(i); 2672 if (packageName.equals(info.activityInfo.packageName)) { 2673 return true; 2674 } 2675 } 2676 return false; 2677 } 2678 2679 private void checkDefaultBrowser() { 2680 final int myUserId = UserHandle.myUserId(); 2681 final String packageName = getDefaultBrowserPackageName(myUserId); 2682 if (packageName != null) { 2683 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2684 if (info == null) { 2685 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2686 synchronized (mPackages) { 2687 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2688 } 2689 } 2690 } 2691 } 2692 2693 @Override 2694 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2695 throws RemoteException { 2696 try { 2697 return super.onTransact(code, data, reply, flags); 2698 } catch (RuntimeException e) { 2699 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2700 Slog.wtf(TAG, "Package Manager Crash", e); 2701 } 2702 throw e; 2703 } 2704 } 2705 2706 void cleanupInstallFailedPackage(PackageSetting ps) { 2707 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2708 2709 removeDataDirsLI(ps.volumeUuid, ps.name); 2710 if (ps.codePath != null) { 2711 if (ps.codePath.isDirectory()) { 2712 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2713 } else { 2714 ps.codePath.delete(); 2715 } 2716 } 2717 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2718 if (ps.resourcePath.isDirectory()) { 2719 FileUtils.deleteContents(ps.resourcePath); 2720 } 2721 ps.resourcePath.delete(); 2722 } 2723 mSettings.removePackageLPw(ps.name); 2724 } 2725 2726 static int[] appendInts(int[] cur, int[] add) { 2727 if (add == null) return cur; 2728 if (cur == null) return add; 2729 final int N = add.length; 2730 for (int i=0; i<N; i++) { 2731 cur = appendInt(cur, add[i]); 2732 } 2733 return cur; 2734 } 2735 2736 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2737 if (!sUserManager.exists(userId)) return null; 2738 final PackageSetting ps = (PackageSetting) p.mExtras; 2739 if (ps == null) { 2740 return null; 2741 } 2742 2743 final PermissionsState permissionsState = ps.getPermissionsState(); 2744 2745 final int[] gids = permissionsState.computeGids(userId); 2746 final Set<String> permissions = permissionsState.getPermissions(userId); 2747 final PackageUserState state = ps.readUserState(userId); 2748 2749 return PackageParser.generatePackageInfo(p, gids, flags, 2750 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2751 } 2752 2753 @Override 2754 public void checkPackageStartable(String packageName, int userId) { 2755 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2756 2757 synchronized (mPackages) { 2758 final PackageSetting ps = mSettings.mPackages.get(packageName); 2759 if (ps == null) { 2760 throw new SecurityException("Package " + packageName + " was not found!"); 2761 } 2762 2763 if (ps.frozen) { 2764 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2765 } 2766 2767 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2768 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2769 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2770 } 2771 } 2772 } 2773 2774 @Override 2775 public boolean isPackageAvailable(String packageName, int userId) { 2776 if (!sUserManager.exists(userId)) return false; 2777 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2778 synchronized (mPackages) { 2779 PackageParser.Package p = mPackages.get(packageName); 2780 if (p != null) { 2781 final PackageSetting ps = (PackageSetting) p.mExtras; 2782 if (ps != null) { 2783 final PackageUserState state = ps.readUserState(userId); 2784 if (state != null) { 2785 return PackageParser.isAvailable(state); 2786 } 2787 } 2788 } 2789 } 2790 return false; 2791 } 2792 2793 @Override 2794 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2795 if (!sUserManager.exists(userId)) return null; 2796 flags = updateFlagsForPackage(flags, userId, packageName); 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2798 // reader 2799 synchronized (mPackages) { 2800 PackageParser.Package p = mPackages.get(packageName); 2801 if (DEBUG_PACKAGE_INFO) 2802 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2803 if (p != null) { 2804 return generatePackageInfo(p, flags, userId); 2805 } 2806 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2807 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2808 } 2809 } 2810 return null; 2811 } 2812 2813 @Override 2814 public String[] currentToCanonicalPackageNames(String[] names) { 2815 String[] out = new String[names.length]; 2816 // reader 2817 synchronized (mPackages) { 2818 for (int i=names.length-1; i>=0; i--) { 2819 PackageSetting ps = mSettings.mPackages.get(names[i]); 2820 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2821 } 2822 } 2823 return out; 2824 } 2825 2826 @Override 2827 public String[] canonicalToCurrentPackageNames(String[] names) { 2828 String[] out = new String[names.length]; 2829 // reader 2830 synchronized (mPackages) { 2831 for (int i=names.length-1; i>=0; i--) { 2832 String cur = mSettings.mRenamedPackages.get(names[i]); 2833 out[i] = cur != null ? cur : names[i]; 2834 } 2835 } 2836 return out; 2837 } 2838 2839 @Override 2840 public int getPackageUid(String packageName, int flags, int userId) { 2841 if (!sUserManager.exists(userId)) return -1; 2842 flags = updateFlagsForPackage(flags, userId, packageName); 2843 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2844 2845 // reader 2846 synchronized (mPackages) { 2847 final PackageParser.Package p = mPackages.get(packageName); 2848 if (p != null && p.isMatch(flags)) { 2849 return UserHandle.getUid(userId, p.applicationInfo.uid); 2850 } 2851 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2852 final PackageSetting ps = mSettings.mPackages.get(packageName); 2853 if (ps != null && ps.isMatch(flags)) { 2854 return UserHandle.getUid(userId, ps.appId); 2855 } 2856 } 2857 } 2858 2859 return -1; 2860 } 2861 2862 @Override 2863 public int[] getPackageGids(String packageName, int flags, int userId) { 2864 if (!sUserManager.exists(userId)) return null; 2865 flags = updateFlagsForPackage(flags, userId, packageName); 2866 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2867 "getPackageGids"); 2868 2869 // reader 2870 synchronized (mPackages) { 2871 final PackageParser.Package p = mPackages.get(packageName); 2872 if (p != null && p.isMatch(flags)) { 2873 PackageSetting ps = (PackageSetting) p.mExtras; 2874 return ps.getPermissionsState().computeGids(userId); 2875 } 2876 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2877 final PackageSetting ps = mSettings.mPackages.get(packageName); 2878 if (ps != null && ps.isMatch(flags)) { 2879 return ps.getPermissionsState().computeGids(userId); 2880 } 2881 } 2882 } 2883 2884 return null; 2885 } 2886 2887 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2888 if (bp.perm != null) { 2889 return PackageParser.generatePermissionInfo(bp.perm, flags); 2890 } 2891 PermissionInfo pi = new PermissionInfo(); 2892 pi.name = bp.name; 2893 pi.packageName = bp.sourcePackage; 2894 pi.nonLocalizedLabel = bp.name; 2895 pi.protectionLevel = bp.protectionLevel; 2896 return pi; 2897 } 2898 2899 @Override 2900 public PermissionInfo getPermissionInfo(String name, int flags) { 2901 // reader 2902 synchronized (mPackages) { 2903 final BasePermission p = mSettings.mPermissions.get(name); 2904 if (p != null) { 2905 return generatePermissionInfo(p, flags); 2906 } 2907 return null; 2908 } 2909 } 2910 2911 @Override 2912 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2913 // reader 2914 synchronized (mPackages) { 2915 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2916 for (BasePermission p : mSettings.mPermissions.values()) { 2917 if (group == null) { 2918 if (p.perm == null || p.perm.info.group == null) { 2919 out.add(generatePermissionInfo(p, flags)); 2920 } 2921 } else { 2922 if (p.perm != null && group.equals(p.perm.info.group)) { 2923 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2924 } 2925 } 2926 } 2927 2928 if (out.size() > 0) { 2929 return out; 2930 } 2931 return mPermissionGroups.containsKey(group) ? out : null; 2932 } 2933 } 2934 2935 @Override 2936 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2937 // reader 2938 synchronized (mPackages) { 2939 return PackageParser.generatePermissionGroupInfo( 2940 mPermissionGroups.get(name), flags); 2941 } 2942 } 2943 2944 @Override 2945 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2946 // reader 2947 synchronized (mPackages) { 2948 final int N = mPermissionGroups.size(); 2949 ArrayList<PermissionGroupInfo> out 2950 = new ArrayList<PermissionGroupInfo>(N); 2951 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2952 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2953 } 2954 return out; 2955 } 2956 } 2957 2958 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2959 int userId) { 2960 if (!sUserManager.exists(userId)) return null; 2961 PackageSetting ps = mSettings.mPackages.get(packageName); 2962 if (ps != null) { 2963 if (ps.pkg == null) { 2964 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2965 flags, userId); 2966 if (pInfo != null) { 2967 return pInfo.applicationInfo; 2968 } 2969 return null; 2970 } 2971 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2972 ps.readUserState(userId), userId); 2973 } 2974 return null; 2975 } 2976 2977 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2978 int userId) { 2979 if (!sUserManager.exists(userId)) return null; 2980 PackageSetting ps = mSettings.mPackages.get(packageName); 2981 if (ps != null) { 2982 PackageParser.Package pkg = ps.pkg; 2983 if (pkg == null) { 2984 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 2985 return null; 2986 } 2987 // Only data remains, so we aren't worried about code paths 2988 pkg = new PackageParser.Package(packageName); 2989 pkg.applicationInfo.packageName = packageName; 2990 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2991 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2992 pkg.applicationInfo.uid = ps.appId; 2993 pkg.applicationInfo.initForUser(userId); 2994 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2995 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2996 } 2997 return generatePackageInfo(pkg, flags, userId); 2998 } 2999 return null; 3000 } 3001 3002 @Override 3003 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3004 if (!sUserManager.exists(userId)) return null; 3005 flags = updateFlagsForApplication(flags, userId, packageName); 3006 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3007 // writer 3008 synchronized (mPackages) { 3009 PackageParser.Package p = mPackages.get(packageName); 3010 if (DEBUG_PACKAGE_INFO) Log.v( 3011 TAG, "getApplicationInfo " + packageName 3012 + ": " + p); 3013 if (p != null) { 3014 PackageSetting ps = mSettings.mPackages.get(packageName); 3015 if (ps == null) return null; 3016 // Note: isEnabledLP() does not apply here - always return info 3017 return PackageParser.generateApplicationInfo( 3018 p, flags, ps.readUserState(userId), userId); 3019 } 3020 if ("android".equals(packageName)||"system".equals(packageName)) { 3021 return mAndroidApplication; 3022 } 3023 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3024 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3025 } 3026 } 3027 return null; 3028 } 3029 3030 @Override 3031 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3032 final IPackageDataObserver observer) { 3033 mContext.enforceCallingOrSelfPermission( 3034 android.Manifest.permission.CLEAR_APP_CACHE, null); 3035 // Queue up an async operation since clearing cache may take a little while. 3036 mHandler.post(new Runnable() { 3037 public void run() { 3038 mHandler.removeCallbacks(this); 3039 int retCode = -1; 3040 synchronized (mInstallLock) { 3041 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3042 if (retCode < 0) { 3043 Slog.w(TAG, "Couldn't clear application caches"); 3044 } 3045 } 3046 if (observer != null) { 3047 try { 3048 observer.onRemoveCompleted(null, (retCode >= 0)); 3049 } catch (RemoteException e) { 3050 Slog.w(TAG, "RemoveException when invoking call back"); 3051 } 3052 } 3053 } 3054 }); 3055 } 3056 3057 @Override 3058 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3059 final IntentSender pi) { 3060 mContext.enforceCallingOrSelfPermission( 3061 android.Manifest.permission.CLEAR_APP_CACHE, null); 3062 // Queue up an async operation since clearing cache may take a little while. 3063 mHandler.post(new Runnable() { 3064 public void run() { 3065 mHandler.removeCallbacks(this); 3066 int retCode = -1; 3067 synchronized (mInstallLock) { 3068 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 3069 if (retCode < 0) { 3070 Slog.w(TAG, "Couldn't clear application caches"); 3071 } 3072 } 3073 if(pi != null) { 3074 try { 3075 // Callback via pending intent 3076 int code = (retCode >= 0) ? 1 : 0; 3077 pi.sendIntent(null, code, null, 3078 null, null); 3079 } catch (SendIntentException e1) { 3080 Slog.i(TAG, "Failed to send pending intent"); 3081 } 3082 } 3083 } 3084 }); 3085 } 3086 3087 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3088 synchronized (mInstallLock) { 3089 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 3090 throw new IOException("Failed to free enough space"); 3091 } 3092 } 3093 } 3094 3095 /** 3096 * Return if the user key is currently unlocked. 3097 */ 3098 private boolean isUserKeyUnlocked(int userId) { 3099 if (StorageManager.isFileBasedEncryptionEnabled()) { 3100 final IMountService mount = IMountService.Stub 3101 .asInterface(ServiceManager.getService("mount")); 3102 if (mount == null) { 3103 Slog.w(TAG, "Early during boot, assuming locked"); 3104 return false; 3105 } 3106 final long token = Binder.clearCallingIdentity(); 3107 try { 3108 return mount.isUserKeyUnlocked(userId); 3109 } catch (RemoteException e) { 3110 throw e.rethrowAsRuntimeException(); 3111 } finally { 3112 Binder.restoreCallingIdentity(token); 3113 } 3114 } else { 3115 return true; 3116 } 3117 } 3118 3119 /** 3120 * Update given flags based on encryption status of current user. 3121 */ 3122 private int updateFlagsForEncryption(int flags, int userId) { 3123 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3124 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3125 // Caller expressed an explicit opinion about what encryption 3126 // aware/unaware components they want to see, so fall through and 3127 // give them what they want 3128 } else { 3129 // Caller expressed no opinion, so match based on user state 3130 if (isUserKeyUnlocked(userId)) { 3131 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3132 } else { 3133 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3134 } 3135 } 3136 return flags; 3137 } 3138 3139 /** 3140 * Update given flags when being used to request {@link PackageInfo}. 3141 */ 3142 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3143 boolean triaged = true; 3144 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3145 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3146 // Caller is asking for component details, so they'd better be 3147 // asking for specific encryption matching behavior, or be triaged 3148 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3149 | PackageManager.MATCH_ENCRYPTION_AWARE 3150 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3151 triaged = false; 3152 } 3153 } 3154 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3155 | PackageManager.MATCH_SYSTEM_ONLY 3156 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3157 triaged = false; 3158 } 3159 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3160 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3161 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3162 } 3163 return updateFlagsForEncryption(flags, userId); 3164 } 3165 3166 /** 3167 * Update given flags when being used to request {@link ApplicationInfo}. 3168 */ 3169 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3170 return updateFlagsForPackage(flags, userId, cookie); 3171 } 3172 3173 /** 3174 * Update given flags when being used to request {@link ComponentInfo}. 3175 */ 3176 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3177 if (cookie instanceof Intent) { 3178 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3179 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3180 } 3181 } 3182 3183 boolean triaged = true; 3184 // Caller is asking for component details, so they'd better be 3185 // asking for specific encryption matching behavior, or be triaged 3186 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3187 | PackageManager.MATCH_ENCRYPTION_AWARE 3188 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3189 triaged = false; 3190 } 3191 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3192 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3193 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3194 } 3195 return updateFlagsForEncryption(flags, userId); 3196 } 3197 3198 /** 3199 * Update given flags when being used to request {@link ResolveInfo}. 3200 */ 3201 private int updateFlagsForResolve(int flags, int userId, Object cookie) { 3202 return updateFlagsForComponent(flags, userId, cookie); 3203 } 3204 3205 @Override 3206 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3207 if (!sUserManager.exists(userId)) return null; 3208 flags = updateFlagsForComponent(flags, userId, component); 3209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3210 synchronized (mPackages) { 3211 PackageParser.Activity a = mActivities.mActivities.get(component); 3212 3213 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3214 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3215 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3216 if (ps == null) return null; 3217 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3218 userId); 3219 } 3220 if (mResolveComponentName.equals(component)) { 3221 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3222 new PackageUserState(), userId); 3223 } 3224 } 3225 return null; 3226 } 3227 3228 @Override 3229 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3230 String resolvedType) { 3231 synchronized (mPackages) { 3232 if (component.equals(mResolveComponentName)) { 3233 // The resolver supports EVERYTHING! 3234 return true; 3235 } 3236 PackageParser.Activity a = mActivities.mActivities.get(component); 3237 if (a == null) { 3238 return false; 3239 } 3240 for (int i=0; i<a.intents.size(); i++) { 3241 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3242 intent.getData(), intent.getCategories(), TAG) >= 0) { 3243 return true; 3244 } 3245 } 3246 return false; 3247 } 3248 } 3249 3250 @Override 3251 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3252 if (!sUserManager.exists(userId)) return null; 3253 flags = updateFlagsForComponent(flags, userId, component); 3254 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3255 synchronized (mPackages) { 3256 PackageParser.Activity a = mReceivers.mActivities.get(component); 3257 if (DEBUG_PACKAGE_INFO) Log.v( 3258 TAG, "getReceiverInfo " + component + ": " + a); 3259 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3260 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3261 if (ps == null) return null; 3262 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3263 userId); 3264 } 3265 } 3266 return null; 3267 } 3268 3269 @Override 3270 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3271 if (!sUserManager.exists(userId)) return null; 3272 flags = updateFlagsForComponent(flags, userId, component); 3273 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3274 synchronized (mPackages) { 3275 PackageParser.Service s = mServices.mServices.get(component); 3276 if (DEBUG_PACKAGE_INFO) Log.v( 3277 TAG, "getServiceInfo " + component + ": " + s); 3278 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3279 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3280 if (ps == null) return null; 3281 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3282 userId); 3283 } 3284 } 3285 return null; 3286 } 3287 3288 @Override 3289 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3290 if (!sUserManager.exists(userId)) return null; 3291 flags = updateFlagsForComponent(flags, userId, component); 3292 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3293 synchronized (mPackages) { 3294 PackageParser.Provider p = mProviders.mProviders.get(component); 3295 if (DEBUG_PACKAGE_INFO) Log.v( 3296 TAG, "getProviderInfo " + component + ": " + p); 3297 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3298 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3299 if (ps == null) return null; 3300 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3301 userId); 3302 } 3303 } 3304 return null; 3305 } 3306 3307 @Override 3308 public String[] getSystemSharedLibraryNames() { 3309 Set<String> libSet; 3310 synchronized (mPackages) { 3311 libSet = mSharedLibraries.keySet(); 3312 int size = libSet.size(); 3313 if (size > 0) { 3314 String[] libs = new String[size]; 3315 libSet.toArray(libs); 3316 return libs; 3317 } 3318 } 3319 return null; 3320 } 3321 3322 /** 3323 * @hide 3324 */ 3325 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3326 synchronized (mPackages) { 3327 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3328 if (lib != null && lib.apk != null) { 3329 return mPackages.get(lib.apk); 3330 } 3331 } 3332 return null; 3333 } 3334 3335 @Override 3336 public FeatureInfo[] getSystemAvailableFeatures() { 3337 Collection<FeatureInfo> featSet; 3338 synchronized (mPackages) { 3339 featSet = mAvailableFeatures.values(); 3340 int size = featSet.size(); 3341 if (size > 0) { 3342 FeatureInfo[] features = new FeatureInfo[size+1]; 3343 featSet.toArray(features); 3344 FeatureInfo fi = new FeatureInfo(); 3345 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3346 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3347 features[size] = fi; 3348 return features; 3349 } 3350 } 3351 return null; 3352 } 3353 3354 @Override 3355 public boolean hasSystemFeature(String name) { 3356 synchronized (mPackages) { 3357 return mAvailableFeatures.containsKey(name); 3358 } 3359 } 3360 3361 @Override 3362 public int checkPermission(String permName, String pkgName, int userId) { 3363 if (!sUserManager.exists(userId)) { 3364 return PackageManager.PERMISSION_DENIED; 3365 } 3366 3367 synchronized (mPackages) { 3368 final PackageParser.Package p = mPackages.get(pkgName); 3369 if (p != null && p.mExtras != null) { 3370 final PackageSetting ps = (PackageSetting) p.mExtras; 3371 final PermissionsState permissionsState = ps.getPermissionsState(); 3372 if (permissionsState.hasPermission(permName, userId)) { 3373 return PackageManager.PERMISSION_GRANTED; 3374 } 3375 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3376 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3377 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3378 return PackageManager.PERMISSION_GRANTED; 3379 } 3380 } 3381 } 3382 3383 return PackageManager.PERMISSION_DENIED; 3384 } 3385 3386 @Override 3387 public int checkUidPermission(String permName, int uid) { 3388 final int userId = UserHandle.getUserId(uid); 3389 3390 if (!sUserManager.exists(userId)) { 3391 return PackageManager.PERMISSION_DENIED; 3392 } 3393 3394 synchronized (mPackages) { 3395 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3396 if (obj != null) { 3397 final SettingBase ps = (SettingBase) obj; 3398 final PermissionsState permissionsState = ps.getPermissionsState(); 3399 if (permissionsState.hasPermission(permName, userId)) { 3400 return PackageManager.PERMISSION_GRANTED; 3401 } 3402 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3403 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3404 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3405 return PackageManager.PERMISSION_GRANTED; 3406 } 3407 } else { 3408 ArraySet<String> perms = mSystemPermissions.get(uid); 3409 if (perms != null) { 3410 if (perms.contains(permName)) { 3411 return PackageManager.PERMISSION_GRANTED; 3412 } 3413 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3414 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3415 return PackageManager.PERMISSION_GRANTED; 3416 } 3417 } 3418 } 3419 } 3420 3421 return PackageManager.PERMISSION_DENIED; 3422 } 3423 3424 @Override 3425 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3426 if (UserHandle.getCallingUserId() != userId) { 3427 mContext.enforceCallingPermission( 3428 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3429 "isPermissionRevokedByPolicy for user " + userId); 3430 } 3431 3432 if (checkPermission(permission, packageName, userId) 3433 == PackageManager.PERMISSION_GRANTED) { 3434 return false; 3435 } 3436 3437 final long identity = Binder.clearCallingIdentity(); 3438 try { 3439 final int flags = getPermissionFlags(permission, packageName, userId); 3440 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3441 } finally { 3442 Binder.restoreCallingIdentity(identity); 3443 } 3444 } 3445 3446 @Override 3447 public String getPermissionControllerPackageName() { 3448 synchronized (mPackages) { 3449 return mRequiredInstallerPackage; 3450 } 3451 } 3452 3453 /** 3454 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3455 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3456 * @param checkShell TODO(yamasani): 3457 * @param message the message to log on security exception 3458 */ 3459 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3460 boolean checkShell, String message) { 3461 if (userId < 0) { 3462 throw new IllegalArgumentException("Invalid userId " + userId); 3463 } 3464 if (checkShell) { 3465 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3466 } 3467 if (userId == UserHandle.getUserId(callingUid)) return; 3468 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3469 if (requireFullPermission) { 3470 mContext.enforceCallingOrSelfPermission( 3471 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3472 } else { 3473 try { 3474 mContext.enforceCallingOrSelfPermission( 3475 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3476 } catch (SecurityException se) { 3477 mContext.enforceCallingOrSelfPermission( 3478 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3479 } 3480 } 3481 } 3482 } 3483 3484 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3485 if (callingUid == Process.SHELL_UID) { 3486 if (userHandle >= 0 3487 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3488 throw new SecurityException("Shell does not have permission to access user " 3489 + userHandle); 3490 } else if (userHandle < 0) { 3491 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3492 + Debug.getCallers(3)); 3493 } 3494 } 3495 } 3496 3497 private BasePermission findPermissionTreeLP(String permName) { 3498 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3499 if (permName.startsWith(bp.name) && 3500 permName.length() > bp.name.length() && 3501 permName.charAt(bp.name.length()) == '.') { 3502 return bp; 3503 } 3504 } 3505 return null; 3506 } 3507 3508 private BasePermission checkPermissionTreeLP(String permName) { 3509 if (permName != null) { 3510 BasePermission bp = findPermissionTreeLP(permName); 3511 if (bp != null) { 3512 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3513 return bp; 3514 } 3515 throw new SecurityException("Calling uid " 3516 + Binder.getCallingUid() 3517 + " is not allowed to add to permission tree " 3518 + bp.name + " owned by uid " + bp.uid); 3519 } 3520 } 3521 throw new SecurityException("No permission tree found for " + permName); 3522 } 3523 3524 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3525 if (s1 == null) { 3526 return s2 == null; 3527 } 3528 if (s2 == null) { 3529 return false; 3530 } 3531 if (s1.getClass() != s2.getClass()) { 3532 return false; 3533 } 3534 return s1.equals(s2); 3535 } 3536 3537 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3538 if (pi1.icon != pi2.icon) return false; 3539 if (pi1.logo != pi2.logo) return false; 3540 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3541 if (!compareStrings(pi1.name, pi2.name)) return false; 3542 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3543 // We'll take care of setting this one. 3544 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3545 // These are not currently stored in settings. 3546 //if (!compareStrings(pi1.group, pi2.group)) return false; 3547 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3548 //if (pi1.labelRes != pi2.labelRes) return false; 3549 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3550 return true; 3551 } 3552 3553 int permissionInfoFootprint(PermissionInfo info) { 3554 int size = info.name.length(); 3555 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3556 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3557 return size; 3558 } 3559 3560 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3561 int size = 0; 3562 for (BasePermission perm : mSettings.mPermissions.values()) { 3563 if (perm.uid == tree.uid) { 3564 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3565 } 3566 } 3567 return size; 3568 } 3569 3570 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3571 // We calculate the max size of permissions defined by this uid and throw 3572 // if that plus the size of 'info' would exceed our stated maximum. 3573 if (tree.uid != Process.SYSTEM_UID) { 3574 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3575 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3576 throw new SecurityException("Permission tree size cap exceeded"); 3577 } 3578 } 3579 } 3580 3581 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3582 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3583 throw new SecurityException("Label must be specified in permission"); 3584 } 3585 BasePermission tree = checkPermissionTreeLP(info.name); 3586 BasePermission bp = mSettings.mPermissions.get(info.name); 3587 boolean added = bp == null; 3588 boolean changed = true; 3589 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3590 if (added) { 3591 enforcePermissionCapLocked(info, tree); 3592 bp = new BasePermission(info.name, tree.sourcePackage, 3593 BasePermission.TYPE_DYNAMIC); 3594 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3595 throw new SecurityException( 3596 "Not allowed to modify non-dynamic permission " 3597 + info.name); 3598 } else { 3599 if (bp.protectionLevel == fixedLevel 3600 && bp.perm.owner.equals(tree.perm.owner) 3601 && bp.uid == tree.uid 3602 && comparePermissionInfos(bp.perm.info, info)) { 3603 changed = false; 3604 } 3605 } 3606 bp.protectionLevel = fixedLevel; 3607 info = new PermissionInfo(info); 3608 info.protectionLevel = fixedLevel; 3609 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3610 bp.perm.info.packageName = tree.perm.info.packageName; 3611 bp.uid = tree.uid; 3612 if (added) { 3613 mSettings.mPermissions.put(info.name, bp); 3614 } 3615 if (changed) { 3616 if (!async) { 3617 mSettings.writeLPr(); 3618 } else { 3619 scheduleWriteSettingsLocked(); 3620 } 3621 } 3622 return added; 3623 } 3624 3625 @Override 3626 public boolean addPermission(PermissionInfo info) { 3627 synchronized (mPackages) { 3628 return addPermissionLocked(info, false); 3629 } 3630 } 3631 3632 @Override 3633 public boolean addPermissionAsync(PermissionInfo info) { 3634 synchronized (mPackages) { 3635 return addPermissionLocked(info, true); 3636 } 3637 } 3638 3639 @Override 3640 public void removePermission(String name) { 3641 synchronized (mPackages) { 3642 checkPermissionTreeLP(name); 3643 BasePermission bp = mSettings.mPermissions.get(name); 3644 if (bp != null) { 3645 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3646 throw new SecurityException( 3647 "Not allowed to modify non-dynamic permission " 3648 + name); 3649 } 3650 mSettings.mPermissions.remove(name); 3651 mSettings.writeLPr(); 3652 } 3653 } 3654 } 3655 3656 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3657 BasePermission bp) { 3658 int index = pkg.requestedPermissions.indexOf(bp.name); 3659 if (index == -1) { 3660 throw new SecurityException("Package " + pkg.packageName 3661 + " has not requested permission " + bp.name); 3662 } 3663 if (!bp.isRuntime() && !bp.isDevelopment()) { 3664 throw new SecurityException("Permission " + bp.name 3665 + " is not a changeable permission type"); 3666 } 3667 } 3668 3669 @Override 3670 public void grantRuntimePermission(String packageName, String name, final int userId) { 3671 if (!sUserManager.exists(userId)) { 3672 Log.e(TAG, "No such user:" + userId); 3673 return; 3674 } 3675 3676 mContext.enforceCallingOrSelfPermission( 3677 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3678 "grantRuntimePermission"); 3679 3680 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3681 "grantRuntimePermission"); 3682 3683 final int uid; 3684 final SettingBase sb; 3685 3686 synchronized (mPackages) { 3687 final PackageParser.Package pkg = mPackages.get(packageName); 3688 if (pkg == null) { 3689 throw new IllegalArgumentException("Unknown package: " + packageName); 3690 } 3691 3692 final BasePermission bp = mSettings.mPermissions.get(name); 3693 if (bp == null) { 3694 throw new IllegalArgumentException("Unknown permission: " + name); 3695 } 3696 3697 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3698 3699 // If a permission review is required for legacy apps we represent 3700 // their permissions as always granted runtime ones since we need 3701 // to keep the review required permission flag per user while an 3702 // install permission's state is shared across all users. 3703 if (Build.PERMISSIONS_REVIEW_REQUIRED 3704 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3705 && bp.isRuntime()) { 3706 return; 3707 } 3708 3709 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3710 sb = (SettingBase) pkg.mExtras; 3711 if (sb == null) { 3712 throw new IllegalArgumentException("Unknown package: " + packageName); 3713 } 3714 3715 final PermissionsState permissionsState = sb.getPermissionsState(); 3716 3717 final int flags = permissionsState.getPermissionFlags(name, userId); 3718 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3719 throw new SecurityException("Cannot grant system fixed permission " 3720 + name + " for package " + packageName); 3721 } 3722 3723 if (bp.isDevelopment()) { 3724 // Development permissions must be handled specially, since they are not 3725 // normal runtime permissions. For now they apply to all users. 3726 if (permissionsState.grantInstallPermission(bp) != 3727 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3728 scheduleWriteSettingsLocked(); 3729 } 3730 return; 3731 } 3732 3733 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3734 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3735 return; 3736 } 3737 3738 final int result = permissionsState.grantRuntimePermission(bp, userId); 3739 switch (result) { 3740 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3741 return; 3742 } 3743 3744 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3745 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3746 mHandler.post(new Runnable() { 3747 @Override 3748 public void run() { 3749 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3750 } 3751 }); 3752 } 3753 break; 3754 } 3755 3756 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3757 3758 // Not critical if that is lost - app has to request again. 3759 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3760 } 3761 3762 // Only need to do this if user is initialized. Otherwise it's a new user 3763 // and there are no processes running as the user yet and there's no need 3764 // to make an expensive call to remount processes for the changed permissions. 3765 if (READ_EXTERNAL_STORAGE.equals(name) 3766 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3767 final long token = Binder.clearCallingIdentity(); 3768 try { 3769 if (sUserManager.isInitialized(userId)) { 3770 MountServiceInternal mountServiceInternal = LocalServices.getService( 3771 MountServiceInternal.class); 3772 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3773 } 3774 } finally { 3775 Binder.restoreCallingIdentity(token); 3776 } 3777 } 3778 } 3779 3780 @Override 3781 public void revokeRuntimePermission(String packageName, String name, int userId) { 3782 if (!sUserManager.exists(userId)) { 3783 Log.e(TAG, "No such user:" + userId); 3784 return; 3785 } 3786 3787 mContext.enforceCallingOrSelfPermission( 3788 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3789 "revokeRuntimePermission"); 3790 3791 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3792 "revokeRuntimePermission"); 3793 3794 final int appId; 3795 3796 synchronized (mPackages) { 3797 final PackageParser.Package pkg = mPackages.get(packageName); 3798 if (pkg == null) { 3799 throw new IllegalArgumentException("Unknown package: " + packageName); 3800 } 3801 3802 final BasePermission bp = mSettings.mPermissions.get(name); 3803 if (bp == null) { 3804 throw new IllegalArgumentException("Unknown permission: " + name); 3805 } 3806 3807 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3808 3809 // If a permission review is required for legacy apps we represent 3810 // their permissions as always granted runtime ones since we need 3811 // to keep the review required permission flag per user while an 3812 // install permission's state is shared across all users. 3813 if (Build.PERMISSIONS_REVIEW_REQUIRED 3814 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3815 && bp.isRuntime()) { 3816 return; 3817 } 3818 3819 SettingBase sb = (SettingBase) pkg.mExtras; 3820 if (sb == null) { 3821 throw new IllegalArgumentException("Unknown package: " + packageName); 3822 } 3823 3824 final PermissionsState permissionsState = sb.getPermissionsState(); 3825 3826 final int flags = permissionsState.getPermissionFlags(name, userId); 3827 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3828 throw new SecurityException("Cannot revoke system fixed permission " 3829 + name + " for package " + packageName); 3830 } 3831 3832 if (bp.isDevelopment()) { 3833 // Development permissions must be handled specially, since they are not 3834 // normal runtime permissions. For now they apply to all users. 3835 if (permissionsState.revokeInstallPermission(bp) != 3836 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3837 scheduleWriteSettingsLocked(); 3838 } 3839 return; 3840 } 3841 3842 if (permissionsState.revokeRuntimePermission(bp, userId) == 3843 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3844 return; 3845 } 3846 3847 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3848 3849 // Critical, after this call app should never have the permission. 3850 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3851 3852 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3853 } 3854 3855 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3856 } 3857 3858 @Override 3859 public void resetRuntimePermissions() { 3860 mContext.enforceCallingOrSelfPermission( 3861 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3862 "revokeRuntimePermission"); 3863 3864 int callingUid = Binder.getCallingUid(); 3865 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3866 mContext.enforceCallingOrSelfPermission( 3867 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3868 "resetRuntimePermissions"); 3869 } 3870 3871 synchronized (mPackages) { 3872 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3873 for (int userId : UserManagerService.getInstance().getUserIds()) { 3874 final int packageCount = mPackages.size(); 3875 for (int i = 0; i < packageCount; i++) { 3876 PackageParser.Package pkg = mPackages.valueAt(i); 3877 if (!(pkg.mExtras instanceof PackageSetting)) { 3878 continue; 3879 } 3880 PackageSetting ps = (PackageSetting) pkg.mExtras; 3881 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3882 } 3883 } 3884 } 3885 } 3886 3887 @Override 3888 public int getPermissionFlags(String name, String packageName, int userId) { 3889 if (!sUserManager.exists(userId)) { 3890 return 0; 3891 } 3892 3893 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3894 3895 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3896 "getPermissionFlags"); 3897 3898 synchronized (mPackages) { 3899 final PackageParser.Package pkg = mPackages.get(packageName); 3900 if (pkg == null) { 3901 throw new IllegalArgumentException("Unknown package: " + packageName); 3902 } 3903 3904 final BasePermission bp = mSettings.mPermissions.get(name); 3905 if (bp == null) { 3906 throw new IllegalArgumentException("Unknown permission: " + name); 3907 } 3908 3909 SettingBase sb = (SettingBase) pkg.mExtras; 3910 if (sb == null) { 3911 throw new IllegalArgumentException("Unknown package: " + packageName); 3912 } 3913 3914 PermissionsState permissionsState = sb.getPermissionsState(); 3915 return permissionsState.getPermissionFlags(name, userId); 3916 } 3917 } 3918 3919 @Override 3920 public void updatePermissionFlags(String name, String packageName, int flagMask, 3921 int flagValues, int userId) { 3922 if (!sUserManager.exists(userId)) { 3923 return; 3924 } 3925 3926 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3927 3928 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3929 "updatePermissionFlags"); 3930 3931 // Only the system can change these flags and nothing else. 3932 if (getCallingUid() != Process.SYSTEM_UID) { 3933 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3934 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3935 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3936 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3937 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3938 } 3939 3940 synchronized (mPackages) { 3941 final PackageParser.Package pkg = mPackages.get(packageName); 3942 if (pkg == null) { 3943 throw new IllegalArgumentException("Unknown package: " + packageName); 3944 } 3945 3946 final BasePermission bp = mSettings.mPermissions.get(name); 3947 if (bp == null) { 3948 throw new IllegalArgumentException("Unknown permission: " + name); 3949 } 3950 3951 SettingBase sb = (SettingBase) pkg.mExtras; 3952 if (sb == null) { 3953 throw new IllegalArgumentException("Unknown package: " + packageName); 3954 } 3955 3956 PermissionsState permissionsState = sb.getPermissionsState(); 3957 3958 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3959 3960 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3961 // Install and runtime permissions are stored in different places, 3962 // so figure out what permission changed and persist the change. 3963 if (permissionsState.getInstallPermissionState(name) != null) { 3964 scheduleWriteSettingsLocked(); 3965 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3966 || hadState) { 3967 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3968 } 3969 } 3970 } 3971 } 3972 3973 /** 3974 * Update the permission flags for all packages and runtime permissions of a user in order 3975 * to allow device or profile owner to remove POLICY_FIXED. 3976 */ 3977 @Override 3978 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3979 if (!sUserManager.exists(userId)) { 3980 return; 3981 } 3982 3983 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3984 3985 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3986 "updatePermissionFlagsForAllApps"); 3987 3988 // Only the system can change system fixed flags. 3989 if (getCallingUid() != Process.SYSTEM_UID) { 3990 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3991 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3992 } 3993 3994 synchronized (mPackages) { 3995 boolean changed = false; 3996 final int packageCount = mPackages.size(); 3997 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 3998 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 3999 SettingBase sb = (SettingBase) pkg.mExtras; 4000 if (sb == null) { 4001 continue; 4002 } 4003 PermissionsState permissionsState = sb.getPermissionsState(); 4004 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4005 userId, flagMask, flagValues); 4006 } 4007 if (changed) { 4008 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4009 } 4010 } 4011 } 4012 4013 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4014 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4015 != PackageManager.PERMISSION_GRANTED 4016 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4017 != PackageManager.PERMISSION_GRANTED) { 4018 throw new SecurityException(message + " requires " 4019 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4020 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4021 } 4022 } 4023 4024 @Override 4025 public boolean shouldShowRequestPermissionRationale(String permissionName, 4026 String packageName, int userId) { 4027 if (UserHandle.getCallingUserId() != userId) { 4028 mContext.enforceCallingPermission( 4029 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4030 "canShowRequestPermissionRationale for user " + userId); 4031 } 4032 4033 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4034 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4035 return false; 4036 } 4037 4038 if (checkPermission(permissionName, packageName, userId) 4039 == PackageManager.PERMISSION_GRANTED) { 4040 return false; 4041 } 4042 4043 final int flags; 4044 4045 final long identity = Binder.clearCallingIdentity(); 4046 try { 4047 flags = getPermissionFlags(permissionName, 4048 packageName, userId); 4049 } finally { 4050 Binder.restoreCallingIdentity(identity); 4051 } 4052 4053 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4054 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4055 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4056 4057 if ((flags & fixedFlags) != 0) { 4058 return false; 4059 } 4060 4061 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4062 } 4063 4064 @Override 4065 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4066 mContext.enforceCallingOrSelfPermission( 4067 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4068 "addOnPermissionsChangeListener"); 4069 4070 synchronized (mPackages) { 4071 mOnPermissionChangeListeners.addListenerLocked(listener); 4072 } 4073 } 4074 4075 @Override 4076 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4077 synchronized (mPackages) { 4078 mOnPermissionChangeListeners.removeListenerLocked(listener); 4079 } 4080 } 4081 4082 @Override 4083 public boolean isProtectedBroadcast(String actionName) { 4084 synchronized (mPackages) { 4085 if (mProtectedBroadcasts.contains(actionName)) { 4086 return true; 4087 } else if (actionName != null) { 4088 // TODO: remove these terrible hacks 4089 if (actionName.startsWith("android.net.netmon.lingerExpired") 4090 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4091 return true; 4092 } 4093 } 4094 } 4095 return false; 4096 } 4097 4098 @Override 4099 public int checkSignatures(String pkg1, String pkg2) { 4100 synchronized (mPackages) { 4101 final PackageParser.Package p1 = mPackages.get(pkg1); 4102 final PackageParser.Package p2 = mPackages.get(pkg2); 4103 if (p1 == null || p1.mExtras == null 4104 || p2 == null || p2.mExtras == null) { 4105 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4106 } 4107 return compareSignatures(p1.mSignatures, p2.mSignatures); 4108 } 4109 } 4110 4111 @Override 4112 public int checkUidSignatures(int uid1, int uid2) { 4113 // Map to base uids. 4114 uid1 = UserHandle.getAppId(uid1); 4115 uid2 = UserHandle.getAppId(uid2); 4116 // reader 4117 synchronized (mPackages) { 4118 Signature[] s1; 4119 Signature[] s2; 4120 Object obj = mSettings.getUserIdLPr(uid1); 4121 if (obj != null) { 4122 if (obj instanceof SharedUserSetting) { 4123 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4124 } else if (obj instanceof PackageSetting) { 4125 s1 = ((PackageSetting)obj).signatures.mSignatures; 4126 } else { 4127 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4128 } 4129 } else { 4130 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4131 } 4132 obj = mSettings.getUserIdLPr(uid2); 4133 if (obj != null) { 4134 if (obj instanceof SharedUserSetting) { 4135 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4136 } else if (obj instanceof PackageSetting) { 4137 s2 = ((PackageSetting)obj).signatures.mSignatures; 4138 } else { 4139 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4140 } 4141 } else { 4142 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4143 } 4144 return compareSignatures(s1, s2); 4145 } 4146 } 4147 4148 private void killUid(int appId, int userId, String reason) { 4149 final long identity = Binder.clearCallingIdentity(); 4150 try { 4151 IActivityManager am = ActivityManagerNative.getDefault(); 4152 if (am != null) { 4153 try { 4154 am.killUid(appId, userId, reason); 4155 } catch (RemoteException e) { 4156 /* ignore - same process */ 4157 } 4158 } 4159 } finally { 4160 Binder.restoreCallingIdentity(identity); 4161 } 4162 } 4163 4164 /** 4165 * Compares two sets of signatures. Returns: 4166 * <br /> 4167 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4168 * <br /> 4169 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4170 * <br /> 4171 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4176 */ 4177 static int compareSignatures(Signature[] s1, Signature[] s2) { 4178 if (s1 == null) { 4179 return s2 == null 4180 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4181 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4182 } 4183 4184 if (s2 == null) { 4185 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4186 } 4187 4188 if (s1.length != s2.length) { 4189 return PackageManager.SIGNATURE_NO_MATCH; 4190 } 4191 4192 // Since both signature sets are of size 1, we can compare without HashSets. 4193 if (s1.length == 1) { 4194 return s1[0].equals(s2[0]) ? 4195 PackageManager.SIGNATURE_MATCH : 4196 PackageManager.SIGNATURE_NO_MATCH; 4197 } 4198 4199 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4200 for (Signature sig : s1) { 4201 set1.add(sig); 4202 } 4203 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4204 for (Signature sig : s2) { 4205 set2.add(sig); 4206 } 4207 // Make sure s2 contains all signatures in s1. 4208 if (set1.equals(set2)) { 4209 return PackageManager.SIGNATURE_MATCH; 4210 } 4211 return PackageManager.SIGNATURE_NO_MATCH; 4212 } 4213 4214 /** 4215 * If the database version for this type of package (internal storage or 4216 * external storage) is less than the version where package signatures 4217 * were updated, return true. 4218 */ 4219 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4220 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4221 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4222 } 4223 4224 /** 4225 * Used for backward compatibility to make sure any packages with 4226 * certificate chains get upgraded to the new style. {@code existingSigs} 4227 * will be in the old format (since they were stored on disk from before the 4228 * system upgrade) and {@code scannedSigs} will be in the newer format. 4229 */ 4230 private int compareSignaturesCompat(PackageSignatures existingSigs, 4231 PackageParser.Package scannedPkg) { 4232 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4233 return PackageManager.SIGNATURE_NO_MATCH; 4234 } 4235 4236 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4237 for (Signature sig : existingSigs.mSignatures) { 4238 existingSet.add(sig); 4239 } 4240 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4241 for (Signature sig : scannedPkg.mSignatures) { 4242 try { 4243 Signature[] chainSignatures = sig.getChainSignatures(); 4244 for (Signature chainSig : chainSignatures) { 4245 scannedCompatSet.add(chainSig); 4246 } 4247 } catch (CertificateEncodingException e) { 4248 scannedCompatSet.add(sig); 4249 } 4250 } 4251 /* 4252 * Make sure the expanded scanned set contains all signatures in the 4253 * existing one. 4254 */ 4255 if (scannedCompatSet.equals(existingSet)) { 4256 // Migrate the old signatures to the new scheme. 4257 existingSigs.assignSignatures(scannedPkg.mSignatures); 4258 // The new KeySets will be re-added later in the scanning process. 4259 synchronized (mPackages) { 4260 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4261 } 4262 return PackageManager.SIGNATURE_MATCH; 4263 } 4264 return PackageManager.SIGNATURE_NO_MATCH; 4265 } 4266 4267 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4268 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4269 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4270 } 4271 4272 private int compareSignaturesRecover(PackageSignatures existingSigs, 4273 PackageParser.Package scannedPkg) { 4274 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4275 return PackageManager.SIGNATURE_NO_MATCH; 4276 } 4277 4278 String msg = null; 4279 try { 4280 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4281 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4282 + scannedPkg.packageName); 4283 return PackageManager.SIGNATURE_MATCH; 4284 } 4285 } catch (CertificateException e) { 4286 msg = e.getMessage(); 4287 } 4288 4289 logCriticalInfo(Log.INFO, 4290 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 @Override 4295 public String[] getPackagesForUid(int uid) { 4296 uid = UserHandle.getAppId(uid); 4297 // reader 4298 synchronized (mPackages) { 4299 Object obj = mSettings.getUserIdLPr(uid); 4300 if (obj instanceof SharedUserSetting) { 4301 final SharedUserSetting sus = (SharedUserSetting) obj; 4302 final int N = sus.packages.size(); 4303 final String[] res = new String[N]; 4304 final Iterator<PackageSetting> it = sus.packages.iterator(); 4305 int i = 0; 4306 while (it.hasNext()) { 4307 res[i++] = it.next().name; 4308 } 4309 return res; 4310 } else if (obj instanceof PackageSetting) { 4311 final PackageSetting ps = (PackageSetting) obj; 4312 return new String[] { ps.name }; 4313 } 4314 } 4315 return null; 4316 } 4317 4318 @Override 4319 public String getNameForUid(int uid) { 4320 // reader 4321 synchronized (mPackages) { 4322 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4323 if (obj instanceof SharedUserSetting) { 4324 final SharedUserSetting sus = (SharedUserSetting) obj; 4325 return sus.name + ":" + sus.userId; 4326 } else if (obj instanceof PackageSetting) { 4327 final PackageSetting ps = (PackageSetting) obj; 4328 return ps.name; 4329 } 4330 } 4331 return null; 4332 } 4333 4334 @Override 4335 public int getUidForSharedUser(String sharedUserName) { 4336 if(sharedUserName == null) { 4337 return -1; 4338 } 4339 // reader 4340 synchronized (mPackages) { 4341 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4342 if (suid == null) { 4343 return -1; 4344 } 4345 return suid.userId; 4346 } 4347 } 4348 4349 @Override 4350 public int getFlagsForUid(int uid) { 4351 synchronized (mPackages) { 4352 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4353 if (obj instanceof SharedUserSetting) { 4354 final SharedUserSetting sus = (SharedUserSetting) obj; 4355 return sus.pkgFlags; 4356 } else if (obj instanceof PackageSetting) { 4357 final PackageSetting ps = (PackageSetting) obj; 4358 return ps.pkgFlags; 4359 } 4360 } 4361 return 0; 4362 } 4363 4364 @Override 4365 public int getPrivateFlagsForUid(int uid) { 4366 synchronized (mPackages) { 4367 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4368 if (obj instanceof SharedUserSetting) { 4369 final SharedUserSetting sus = (SharedUserSetting) obj; 4370 return sus.pkgPrivateFlags; 4371 } else if (obj instanceof PackageSetting) { 4372 final PackageSetting ps = (PackageSetting) obj; 4373 return ps.pkgPrivateFlags; 4374 } 4375 } 4376 return 0; 4377 } 4378 4379 @Override 4380 public boolean isUidPrivileged(int uid) { 4381 uid = UserHandle.getAppId(uid); 4382 // reader 4383 synchronized (mPackages) { 4384 Object obj = mSettings.getUserIdLPr(uid); 4385 if (obj instanceof SharedUserSetting) { 4386 final SharedUserSetting sus = (SharedUserSetting) obj; 4387 final Iterator<PackageSetting> it = sus.packages.iterator(); 4388 while (it.hasNext()) { 4389 if (it.next().isPrivileged()) { 4390 return true; 4391 } 4392 } 4393 } else if (obj instanceof PackageSetting) { 4394 final PackageSetting ps = (PackageSetting) obj; 4395 return ps.isPrivileged(); 4396 } 4397 } 4398 return false; 4399 } 4400 4401 @Override 4402 public String[] getAppOpPermissionPackages(String permissionName) { 4403 synchronized (mPackages) { 4404 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4405 if (pkgs == null) { 4406 return null; 4407 } 4408 return pkgs.toArray(new String[pkgs.size()]); 4409 } 4410 } 4411 4412 @Override 4413 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4414 int flags, int userId) { 4415 if (!sUserManager.exists(userId)) return null; 4416 flags = updateFlagsForResolve(flags, userId, intent); 4417 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4418 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4419 final ResolveInfo bestChoice = 4420 chooseBestActivity(intent, resolvedType, flags, query, userId); 4421 4422 if (isEphemeralAllowed(intent, query, userId)) { 4423 final EphemeralResolveInfo ai = 4424 getEphemeralResolveInfo(intent, resolvedType, userId); 4425 if (ai != null) { 4426 if (DEBUG_EPHEMERAL) { 4427 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4428 } 4429 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4430 bestChoice.ephemeralResolveInfo = ai; 4431 } 4432 } 4433 return bestChoice; 4434 } 4435 4436 @Override 4437 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4438 IntentFilter filter, int match, ComponentName activity) { 4439 final int userId = UserHandle.getCallingUserId(); 4440 if (DEBUG_PREFERRED) { 4441 Log.v(TAG, "setLastChosenActivity intent=" + intent 4442 + " resolvedType=" + resolvedType 4443 + " flags=" + flags 4444 + " filter=" + filter 4445 + " match=" + match 4446 + " activity=" + activity); 4447 filter.dump(new PrintStreamPrinter(System.out), " "); 4448 } 4449 intent.setComponent(null); 4450 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4451 // Find any earlier preferred or last chosen entries and nuke them 4452 findPreferredActivity(intent, resolvedType, 4453 flags, query, 0, false, true, false, userId); 4454 // Add the new activity as the last chosen for this filter 4455 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4456 "Setting last chosen"); 4457 } 4458 4459 @Override 4460 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4461 final int userId = UserHandle.getCallingUserId(); 4462 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4463 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4464 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4465 false, false, false, userId); 4466 } 4467 4468 4469 private boolean isEphemeralAllowed( 4470 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4471 // Short circuit and return early if possible. 4472 final int callingUser = UserHandle.getCallingUserId(); 4473 if (callingUser != UserHandle.USER_SYSTEM) { 4474 return false; 4475 } 4476 if (mEphemeralResolverConnection == null) { 4477 return false; 4478 } 4479 if (intent.getComponent() != null) { 4480 return false; 4481 } 4482 if (intent.getPackage() != null) { 4483 return false; 4484 } 4485 final boolean isWebUri = hasWebURI(intent); 4486 if (!isWebUri) { 4487 return false; 4488 } 4489 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4490 synchronized (mPackages) { 4491 final int count = resolvedActivites.size(); 4492 for (int n = 0; n < count; n++) { 4493 ResolveInfo info = resolvedActivites.get(n); 4494 String packageName = info.activityInfo.packageName; 4495 PackageSetting ps = mSettings.mPackages.get(packageName); 4496 if (ps != null) { 4497 // Try to get the status from User settings first 4498 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4499 int status = (int) (packedStatus >> 32); 4500 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4501 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4502 if (DEBUG_EPHEMERAL) { 4503 Slog.v(TAG, "DENY ephemeral apps;" 4504 + " pkg: " + packageName + ", status: " + status); 4505 } 4506 return false; 4507 } 4508 } 4509 } 4510 } 4511 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4512 return true; 4513 } 4514 4515 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4516 int userId) { 4517 MessageDigest digest = null; 4518 try { 4519 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4520 } catch (NoSuchAlgorithmException e) { 4521 // If we can't create a digest, ignore ephemeral apps. 4522 return null; 4523 } 4524 4525 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4526 final byte[] digestBytes = digest.digest(hostBytes); 4527 int shaPrefix = 4528 digestBytes[0] << 24 4529 | digestBytes[1] << 16 4530 | digestBytes[2] << 8 4531 | digestBytes[3] << 0; 4532 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4533 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4534 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4535 // No hash prefix match; there are no ephemeral apps for this domain. 4536 return null; 4537 } 4538 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4539 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4540 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4541 continue; 4542 } 4543 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4544 // No filters; this should never happen. 4545 if (filters.isEmpty()) { 4546 continue; 4547 } 4548 // We have a domain match; resolve the filters to see if anything matches. 4549 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4550 for (int j = filters.size() - 1; j >= 0; --j) { 4551 final EphemeralResolveIntentInfo intentInfo = 4552 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4553 ephemeralResolver.addFilter(intentInfo); 4554 } 4555 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4556 intent, resolvedType, false /*defaultOnly*/, userId); 4557 if (!matchedResolveInfoList.isEmpty()) { 4558 return matchedResolveInfoList.get(0); 4559 } 4560 } 4561 // Hash or filter mis-match; no ephemeral apps for this domain. 4562 return null; 4563 } 4564 4565 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4566 int flags, List<ResolveInfo> query, int userId) { 4567 if (query != null) { 4568 final int N = query.size(); 4569 if (N == 1) { 4570 return query.get(0); 4571 } else if (N > 1) { 4572 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4573 // If there is more than one activity with the same priority, 4574 // then let the user decide between them. 4575 ResolveInfo r0 = query.get(0); 4576 ResolveInfo r1 = query.get(1); 4577 if (DEBUG_INTENT_MATCHING || debug) { 4578 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4579 + r1.activityInfo.name + "=" + r1.priority); 4580 } 4581 // If the first activity has a higher priority, or a different 4582 // default, then it is always desirable to pick it. 4583 if (r0.priority != r1.priority 4584 || r0.preferredOrder != r1.preferredOrder 4585 || r0.isDefault != r1.isDefault) { 4586 return query.get(0); 4587 } 4588 // If we have saved a preference for a preferred activity for 4589 // this Intent, use that. 4590 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4591 flags, query, r0.priority, true, false, debug, userId); 4592 if (ri != null) { 4593 return ri; 4594 } 4595 ri = new ResolveInfo(mResolveInfo); 4596 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4597 ri.activityInfo.applicationInfo = new ApplicationInfo( 4598 ri.activityInfo.applicationInfo); 4599 if (userId != 0) { 4600 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4601 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4602 } 4603 // Make sure that the resolver is displayable in car mode 4604 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4605 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4606 return ri; 4607 } 4608 } 4609 return null; 4610 } 4611 4612 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4613 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4614 final int N = query.size(); 4615 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4616 .get(userId); 4617 // Get the list of persistent preferred activities that handle the intent 4618 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4619 List<PersistentPreferredActivity> pprefs = ppir != null 4620 ? ppir.queryIntent(intent, resolvedType, 4621 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4622 : null; 4623 if (pprefs != null && pprefs.size() > 0) { 4624 final int M = pprefs.size(); 4625 for (int i=0; i<M; i++) { 4626 final PersistentPreferredActivity ppa = pprefs.get(i); 4627 if (DEBUG_PREFERRED || debug) { 4628 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4629 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4630 + "\n component=" + ppa.mComponent); 4631 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4632 } 4633 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4634 flags | MATCH_DISABLED_COMPONENTS, userId); 4635 if (DEBUG_PREFERRED || debug) { 4636 Slog.v(TAG, "Found persistent preferred activity:"); 4637 if (ai != null) { 4638 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4639 } else { 4640 Slog.v(TAG, " null"); 4641 } 4642 } 4643 if (ai == null) { 4644 // This previously registered persistent preferred activity 4645 // component is no longer known. Ignore it and do NOT remove it. 4646 continue; 4647 } 4648 for (int j=0; j<N; j++) { 4649 final ResolveInfo ri = query.get(j); 4650 if (!ri.activityInfo.applicationInfo.packageName 4651 .equals(ai.applicationInfo.packageName)) { 4652 continue; 4653 } 4654 if (!ri.activityInfo.name.equals(ai.name)) { 4655 continue; 4656 } 4657 // Found a persistent preference that can handle the intent. 4658 if (DEBUG_PREFERRED || debug) { 4659 Slog.v(TAG, "Returning persistent preferred activity: " + 4660 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4661 } 4662 return ri; 4663 } 4664 } 4665 } 4666 return null; 4667 } 4668 4669 // TODO: handle preferred activities missing while user has amnesia 4670 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4671 List<ResolveInfo> query, int priority, boolean always, 4672 boolean removeMatches, boolean debug, int userId) { 4673 if (!sUserManager.exists(userId)) return null; 4674 flags = updateFlagsForResolve(flags, userId, intent); 4675 // writer 4676 synchronized (mPackages) { 4677 if (intent.getSelector() != null) { 4678 intent = intent.getSelector(); 4679 } 4680 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4681 4682 // Try to find a matching persistent preferred activity. 4683 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4684 debug, userId); 4685 4686 // If a persistent preferred activity matched, use it. 4687 if (pri != null) { 4688 return pri; 4689 } 4690 4691 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4692 // Get the list of preferred activities that handle the intent 4693 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4694 List<PreferredActivity> prefs = pir != null 4695 ? pir.queryIntent(intent, resolvedType, 4696 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4697 : null; 4698 if (prefs != null && prefs.size() > 0) { 4699 boolean changed = false; 4700 try { 4701 // First figure out how good the original match set is. 4702 // We will only allow preferred activities that came 4703 // from the same match quality. 4704 int match = 0; 4705 4706 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4707 4708 final int N = query.size(); 4709 for (int j=0; j<N; j++) { 4710 final ResolveInfo ri = query.get(j); 4711 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4712 + ": 0x" + Integer.toHexString(match)); 4713 if (ri.match > match) { 4714 match = ri.match; 4715 } 4716 } 4717 4718 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4719 + Integer.toHexString(match)); 4720 4721 match &= IntentFilter.MATCH_CATEGORY_MASK; 4722 final int M = prefs.size(); 4723 for (int i=0; i<M; i++) { 4724 final PreferredActivity pa = prefs.get(i); 4725 if (DEBUG_PREFERRED || debug) { 4726 Slog.v(TAG, "Checking PreferredActivity ds=" 4727 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4728 + "\n component=" + pa.mPref.mComponent); 4729 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4730 } 4731 if (pa.mPref.mMatch != match) { 4732 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4733 + Integer.toHexString(pa.mPref.mMatch)); 4734 continue; 4735 } 4736 // If it's not an "always" type preferred activity and that's what we're 4737 // looking for, skip it. 4738 if (always && !pa.mPref.mAlways) { 4739 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4740 continue; 4741 } 4742 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4743 flags | MATCH_DISABLED_COMPONENTS, userId); 4744 if (DEBUG_PREFERRED || debug) { 4745 Slog.v(TAG, "Found preferred activity:"); 4746 if (ai != null) { 4747 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4748 } else { 4749 Slog.v(TAG, " null"); 4750 } 4751 } 4752 if (ai == null) { 4753 // This previously registered preferred activity 4754 // component is no longer known. Most likely an update 4755 // to the app was installed and in the new version this 4756 // component no longer exists. Clean it up by removing 4757 // it from the preferred activities list, and skip it. 4758 Slog.w(TAG, "Removing dangling preferred activity: " 4759 + pa.mPref.mComponent); 4760 pir.removeFilter(pa); 4761 changed = true; 4762 continue; 4763 } 4764 for (int j=0; j<N; j++) { 4765 final ResolveInfo ri = query.get(j); 4766 if (!ri.activityInfo.applicationInfo.packageName 4767 .equals(ai.applicationInfo.packageName)) { 4768 continue; 4769 } 4770 if (!ri.activityInfo.name.equals(ai.name)) { 4771 continue; 4772 } 4773 4774 if (removeMatches) { 4775 pir.removeFilter(pa); 4776 changed = true; 4777 if (DEBUG_PREFERRED) { 4778 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4779 } 4780 break; 4781 } 4782 4783 // Okay we found a previously set preferred or last chosen app. 4784 // If the result set is different from when this 4785 // was created, we need to clear it and re-ask the 4786 // user their preference, if we're looking for an "always" type entry. 4787 if (always && !pa.mPref.sameSet(query)) { 4788 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4789 + intent + " type " + resolvedType); 4790 if (DEBUG_PREFERRED) { 4791 Slog.v(TAG, "Removing preferred activity since set changed " 4792 + pa.mPref.mComponent); 4793 } 4794 pir.removeFilter(pa); 4795 // Re-add the filter as a "last chosen" entry (!always) 4796 PreferredActivity lastChosen = new PreferredActivity( 4797 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4798 pir.addFilter(lastChosen); 4799 changed = true; 4800 return null; 4801 } 4802 4803 // Yay! Either the set matched or we're looking for the last chosen 4804 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4805 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4806 return ri; 4807 } 4808 } 4809 } finally { 4810 if (changed) { 4811 if (DEBUG_PREFERRED) { 4812 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4813 } 4814 scheduleWritePackageRestrictionsLocked(userId); 4815 } 4816 } 4817 } 4818 } 4819 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4820 return null; 4821 } 4822 4823 /* 4824 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4825 */ 4826 @Override 4827 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4828 int targetUserId) { 4829 mContext.enforceCallingOrSelfPermission( 4830 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4831 List<CrossProfileIntentFilter> matches = 4832 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4833 if (matches != null) { 4834 int size = matches.size(); 4835 for (int i = 0; i < size; i++) { 4836 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4837 } 4838 } 4839 if (hasWebURI(intent)) { 4840 // cross-profile app linking works only towards the parent. 4841 final UserInfo parent = getProfileParent(sourceUserId); 4842 synchronized(mPackages) { 4843 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4844 intent, resolvedType, 0, sourceUserId, parent.id); 4845 return xpDomainInfo != null; 4846 } 4847 } 4848 return false; 4849 } 4850 4851 private UserInfo getProfileParent(int userId) { 4852 final long identity = Binder.clearCallingIdentity(); 4853 try { 4854 return sUserManager.getProfileParent(userId); 4855 } finally { 4856 Binder.restoreCallingIdentity(identity); 4857 } 4858 } 4859 4860 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4861 String resolvedType, int userId) { 4862 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4863 if (resolver != null) { 4864 return resolver.queryIntent(intent, resolvedType, false, userId); 4865 } 4866 return null; 4867 } 4868 4869 @Override 4870 public List<ResolveInfo> queryIntentActivities(Intent intent, 4871 String resolvedType, int flags, int userId) { 4872 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4873 flags = updateFlagsForResolve(flags, userId, intent); 4874 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4875 ComponentName comp = intent.getComponent(); 4876 if (comp == null) { 4877 if (intent.getSelector() != null) { 4878 intent = intent.getSelector(); 4879 comp = intent.getComponent(); 4880 } 4881 } 4882 4883 if (comp != null) { 4884 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4885 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4886 if (ai != null) { 4887 final ResolveInfo ri = new ResolveInfo(); 4888 ri.activityInfo = ai; 4889 list.add(ri); 4890 } 4891 return list; 4892 } 4893 4894 // reader 4895 synchronized (mPackages) { 4896 final String pkgName = intent.getPackage(); 4897 if (pkgName == null) { 4898 List<CrossProfileIntentFilter> matchingFilters = 4899 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4900 // Check for results that need to skip the current profile. 4901 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4902 resolvedType, flags, userId); 4903 if (xpResolveInfo != null) { 4904 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4905 result.add(xpResolveInfo); 4906 return filterIfNotSystemUser(result, userId); 4907 } 4908 4909 // Check for results in the current profile. 4910 List<ResolveInfo> result = mActivities.queryIntent( 4911 intent, resolvedType, flags, userId); 4912 result = filterIfNotSystemUser(result, userId); 4913 4914 // Check for cross profile results. 4915 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4916 xpResolveInfo = queryCrossProfileIntents( 4917 matchingFilters, intent, resolvedType, flags, userId, 4918 hasNonNegativePriorityResult); 4919 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4920 boolean isVisibleToUser = filterIfNotSystemUser( 4921 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4922 if (isVisibleToUser) { 4923 result.add(xpResolveInfo); 4924 Collections.sort(result, mResolvePrioritySorter); 4925 } 4926 } 4927 if (hasWebURI(intent)) { 4928 CrossProfileDomainInfo xpDomainInfo = null; 4929 final UserInfo parent = getProfileParent(userId); 4930 if (parent != null) { 4931 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4932 flags, userId, parent.id); 4933 } 4934 if (xpDomainInfo != null) { 4935 if (xpResolveInfo != null) { 4936 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4937 // in the result. 4938 result.remove(xpResolveInfo); 4939 } 4940 if (result.size() == 0) { 4941 result.add(xpDomainInfo.resolveInfo); 4942 return result; 4943 } 4944 } else if (result.size() <= 1) { 4945 return result; 4946 } 4947 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4948 xpDomainInfo, userId); 4949 Collections.sort(result, mResolvePrioritySorter); 4950 } 4951 return result; 4952 } 4953 final PackageParser.Package pkg = mPackages.get(pkgName); 4954 if (pkg != null) { 4955 return filterIfNotSystemUser( 4956 mActivities.queryIntentForPackage( 4957 intent, resolvedType, flags, pkg.activities, userId), 4958 userId); 4959 } 4960 return new ArrayList<ResolveInfo>(); 4961 } 4962 } 4963 4964 private static class CrossProfileDomainInfo { 4965 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4966 ResolveInfo resolveInfo; 4967 /* Best domain verification status of the activities found in the other profile */ 4968 int bestDomainVerificationStatus; 4969 } 4970 4971 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4972 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4973 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4974 sourceUserId)) { 4975 return null; 4976 } 4977 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4978 resolvedType, flags, parentUserId); 4979 4980 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4981 return null; 4982 } 4983 CrossProfileDomainInfo result = null; 4984 int size = resultTargetUser.size(); 4985 for (int i = 0; i < size; i++) { 4986 ResolveInfo riTargetUser = resultTargetUser.get(i); 4987 // Intent filter verification is only for filters that specify a host. So don't return 4988 // those that handle all web uris. 4989 if (riTargetUser.handleAllWebDataURI) { 4990 continue; 4991 } 4992 String packageName = riTargetUser.activityInfo.packageName; 4993 PackageSetting ps = mSettings.mPackages.get(packageName); 4994 if (ps == null) { 4995 continue; 4996 } 4997 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 4998 int status = (int)(verificationState >> 32); 4999 if (result == null) { 5000 result = new CrossProfileDomainInfo(); 5001 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5002 sourceUserId, parentUserId); 5003 result.bestDomainVerificationStatus = status; 5004 } else { 5005 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5006 result.bestDomainVerificationStatus); 5007 } 5008 } 5009 // Don't consider matches with status NEVER across profiles. 5010 if (result != null && result.bestDomainVerificationStatus 5011 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5012 return null; 5013 } 5014 return result; 5015 } 5016 5017 /** 5018 * Verification statuses are ordered from the worse to the best, except for 5019 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5020 */ 5021 private int bestDomainVerificationStatus(int status1, int status2) { 5022 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5023 return status2; 5024 } 5025 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5026 return status1; 5027 } 5028 return (int) MathUtils.max(status1, status2); 5029 } 5030 5031 private boolean isUserEnabled(int userId) { 5032 long callingId = Binder.clearCallingIdentity(); 5033 try { 5034 UserInfo userInfo = sUserManager.getUserInfo(userId); 5035 return userInfo != null && userInfo.isEnabled(); 5036 } finally { 5037 Binder.restoreCallingIdentity(callingId); 5038 } 5039 } 5040 5041 /** 5042 * Filter out activities with systemUserOnly flag set, when current user is not System. 5043 * 5044 * @return filtered list 5045 */ 5046 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5047 if (userId == UserHandle.USER_SYSTEM) { 5048 return resolveInfos; 5049 } 5050 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5051 ResolveInfo info = resolveInfos.get(i); 5052 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5053 resolveInfos.remove(i); 5054 } 5055 } 5056 return resolveInfos; 5057 } 5058 5059 /** 5060 * @param resolveInfos list of resolve infos in descending priority order 5061 * @return if the list contains a resolve info with non-negative priority 5062 */ 5063 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5064 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5065 } 5066 5067 private static boolean hasWebURI(Intent intent) { 5068 if (intent.getData() == null) { 5069 return false; 5070 } 5071 final String scheme = intent.getScheme(); 5072 if (TextUtils.isEmpty(scheme)) { 5073 return false; 5074 } 5075 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5076 } 5077 5078 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5079 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5080 int userId) { 5081 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5082 5083 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5084 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5085 candidates.size()); 5086 } 5087 5088 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5089 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5090 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5091 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5092 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5093 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5094 5095 synchronized (mPackages) { 5096 final int count = candidates.size(); 5097 // First, try to use linked apps. Partition the candidates into four lists: 5098 // one for the final results, one for the "do not use ever", one for "undefined status" 5099 // and finally one for "browser app type". 5100 for (int n=0; n<count; n++) { 5101 ResolveInfo info = candidates.get(n); 5102 String packageName = info.activityInfo.packageName; 5103 PackageSetting ps = mSettings.mPackages.get(packageName); 5104 if (ps != null) { 5105 // Add to the special match all list (Browser use case) 5106 if (info.handleAllWebDataURI) { 5107 matchAllList.add(info); 5108 continue; 5109 } 5110 // Try to get the status from User settings first 5111 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5112 int status = (int)(packedStatus >> 32); 5113 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5114 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5115 if (DEBUG_DOMAIN_VERIFICATION) { 5116 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5117 + " : linkgen=" + linkGeneration); 5118 } 5119 // Use link-enabled generation as preferredOrder, i.e. 5120 // prefer newly-enabled over earlier-enabled. 5121 info.preferredOrder = linkGeneration; 5122 alwaysList.add(info); 5123 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5124 if (DEBUG_DOMAIN_VERIFICATION) { 5125 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5126 } 5127 neverList.add(info); 5128 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5129 if (DEBUG_DOMAIN_VERIFICATION) { 5130 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5131 } 5132 alwaysAskList.add(info); 5133 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5134 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5135 if (DEBUG_DOMAIN_VERIFICATION) { 5136 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5137 } 5138 undefinedList.add(info); 5139 } 5140 } 5141 } 5142 5143 // We'll want to include browser possibilities in a few cases 5144 boolean includeBrowser = false; 5145 5146 // First try to add the "always" resolution(s) for the current user, if any 5147 if (alwaysList.size() > 0) { 5148 result.addAll(alwaysList); 5149 } else { 5150 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5151 result.addAll(undefinedList); 5152 // Maybe add one for the other profile. 5153 if (xpDomainInfo != null && ( 5154 xpDomainInfo.bestDomainVerificationStatus 5155 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5156 result.add(xpDomainInfo.resolveInfo); 5157 } 5158 includeBrowser = true; 5159 } 5160 5161 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5162 // If there were 'always' entries their preferred order has been set, so we also 5163 // back that off to make the alternatives equivalent 5164 if (alwaysAskList.size() > 0) { 5165 for (ResolveInfo i : result) { 5166 i.preferredOrder = 0; 5167 } 5168 result.addAll(alwaysAskList); 5169 includeBrowser = true; 5170 } 5171 5172 if (includeBrowser) { 5173 // Also add browsers (all of them or only the default one) 5174 if (DEBUG_DOMAIN_VERIFICATION) { 5175 Slog.v(TAG, " ...including browsers in candidate set"); 5176 } 5177 if ((matchFlags & MATCH_ALL) != 0) { 5178 result.addAll(matchAllList); 5179 } else { 5180 // Browser/generic handling case. If there's a default browser, go straight 5181 // to that (but only if there is no other higher-priority match). 5182 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5183 int maxMatchPrio = 0; 5184 ResolveInfo defaultBrowserMatch = null; 5185 final int numCandidates = matchAllList.size(); 5186 for (int n = 0; n < numCandidates; n++) { 5187 ResolveInfo info = matchAllList.get(n); 5188 // track the highest overall match priority... 5189 if (info.priority > maxMatchPrio) { 5190 maxMatchPrio = info.priority; 5191 } 5192 // ...and the highest-priority default browser match 5193 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5194 if (defaultBrowserMatch == null 5195 || (defaultBrowserMatch.priority < info.priority)) { 5196 if (debug) { 5197 Slog.v(TAG, "Considering default browser match " + info); 5198 } 5199 defaultBrowserMatch = info; 5200 } 5201 } 5202 } 5203 if (defaultBrowserMatch != null 5204 && defaultBrowserMatch.priority >= maxMatchPrio 5205 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5206 { 5207 if (debug) { 5208 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5209 } 5210 result.add(defaultBrowserMatch); 5211 } else { 5212 result.addAll(matchAllList); 5213 } 5214 } 5215 5216 // If there is nothing selected, add all candidates and remove the ones that the user 5217 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5218 if (result.size() == 0) { 5219 result.addAll(candidates); 5220 result.removeAll(neverList); 5221 } 5222 } 5223 } 5224 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5225 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5226 result.size()); 5227 for (ResolveInfo info : result) { 5228 Slog.v(TAG, " + " + info.activityInfo); 5229 } 5230 } 5231 return result; 5232 } 5233 5234 // Returns a packed value as a long: 5235 // 5236 // high 'int'-sized word: link status: undefined/ask/never/always. 5237 // low 'int'-sized word: relative priority among 'always' results. 5238 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5239 long result = ps.getDomainVerificationStatusForUser(userId); 5240 // if none available, get the master status 5241 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5242 if (ps.getIntentFilterVerificationInfo() != null) { 5243 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5244 } 5245 } 5246 return result; 5247 } 5248 5249 private ResolveInfo querySkipCurrentProfileIntents( 5250 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5251 int flags, int sourceUserId) { 5252 if (matchingFilters != null) { 5253 int size = matchingFilters.size(); 5254 for (int i = 0; i < size; i ++) { 5255 CrossProfileIntentFilter filter = matchingFilters.get(i); 5256 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5257 // Checking if there are activities in the target user that can handle the 5258 // intent. 5259 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5260 resolvedType, flags, sourceUserId); 5261 if (resolveInfo != null) { 5262 return resolveInfo; 5263 } 5264 } 5265 } 5266 } 5267 return null; 5268 } 5269 5270 // Return matching ResolveInfo in target user if any. 5271 private ResolveInfo queryCrossProfileIntents( 5272 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5273 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5274 if (matchingFilters != null) { 5275 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5276 // match the same intent. For performance reasons, it is better not to 5277 // run queryIntent twice for the same userId 5278 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5279 int size = matchingFilters.size(); 5280 for (int i = 0; i < size; i++) { 5281 CrossProfileIntentFilter filter = matchingFilters.get(i); 5282 int targetUserId = filter.getTargetUserId(); 5283 boolean skipCurrentProfile = 5284 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5285 boolean skipCurrentProfileIfNoMatchFound = 5286 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5287 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5288 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5289 // Checking if there are activities in the target user that can handle the 5290 // intent. 5291 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5292 resolvedType, flags, sourceUserId); 5293 if (resolveInfo != null) return resolveInfo; 5294 alreadyTriedUserIds.put(targetUserId, true); 5295 } 5296 } 5297 } 5298 return null; 5299 } 5300 5301 /** 5302 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5303 * will forward the intent to the filter's target user. 5304 * Otherwise, returns null. 5305 */ 5306 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5307 String resolvedType, int flags, int sourceUserId) { 5308 int targetUserId = filter.getTargetUserId(); 5309 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5310 resolvedType, flags, targetUserId); 5311 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5312 && isUserEnabled(targetUserId)) { 5313 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5314 } 5315 return null; 5316 } 5317 5318 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5319 int sourceUserId, int targetUserId) { 5320 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5321 long ident = Binder.clearCallingIdentity(); 5322 boolean targetIsProfile; 5323 try { 5324 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5325 } finally { 5326 Binder.restoreCallingIdentity(ident); 5327 } 5328 String className; 5329 if (targetIsProfile) { 5330 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5331 } else { 5332 className = FORWARD_INTENT_TO_PARENT; 5333 } 5334 ComponentName forwardingActivityComponentName = new ComponentName( 5335 mAndroidApplication.packageName, className); 5336 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5337 sourceUserId); 5338 if (!targetIsProfile) { 5339 forwardingActivityInfo.showUserIcon = targetUserId; 5340 forwardingResolveInfo.noResourceId = true; 5341 } 5342 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5343 forwardingResolveInfo.priority = 0; 5344 forwardingResolveInfo.preferredOrder = 0; 5345 forwardingResolveInfo.match = 0; 5346 forwardingResolveInfo.isDefault = true; 5347 forwardingResolveInfo.filter = filter; 5348 forwardingResolveInfo.targetUserId = targetUserId; 5349 return forwardingResolveInfo; 5350 } 5351 5352 @Override 5353 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5354 Intent[] specifics, String[] specificTypes, Intent intent, 5355 String resolvedType, int flags, int userId) { 5356 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5357 flags = updateFlagsForResolve(flags, userId, intent); 5358 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5359 false, "query intent activity options"); 5360 final String resultsAction = intent.getAction(); 5361 5362 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5363 | PackageManager.GET_RESOLVED_FILTER, userId); 5364 5365 if (DEBUG_INTENT_MATCHING) { 5366 Log.v(TAG, "Query " + intent + ": " + results); 5367 } 5368 5369 int specificsPos = 0; 5370 int N; 5371 5372 // todo: note that the algorithm used here is O(N^2). This 5373 // isn't a problem in our current environment, but if we start running 5374 // into situations where we have more than 5 or 10 matches then this 5375 // should probably be changed to something smarter... 5376 5377 // First we go through and resolve each of the specific items 5378 // that were supplied, taking care of removing any corresponding 5379 // duplicate items in the generic resolve list. 5380 if (specifics != null) { 5381 for (int i=0; i<specifics.length; i++) { 5382 final Intent sintent = specifics[i]; 5383 if (sintent == null) { 5384 continue; 5385 } 5386 5387 if (DEBUG_INTENT_MATCHING) { 5388 Log.v(TAG, "Specific #" + i + ": " + sintent); 5389 } 5390 5391 String action = sintent.getAction(); 5392 if (resultsAction != null && resultsAction.equals(action)) { 5393 // If this action was explicitly requested, then don't 5394 // remove things that have it. 5395 action = null; 5396 } 5397 5398 ResolveInfo ri = null; 5399 ActivityInfo ai = null; 5400 5401 ComponentName comp = sintent.getComponent(); 5402 if (comp == null) { 5403 ri = resolveIntent( 5404 sintent, 5405 specificTypes != null ? specificTypes[i] : null, 5406 flags, userId); 5407 if (ri == null) { 5408 continue; 5409 } 5410 if (ri == mResolveInfo) { 5411 // ACK! Must do something better with this. 5412 } 5413 ai = ri.activityInfo; 5414 comp = new ComponentName(ai.applicationInfo.packageName, 5415 ai.name); 5416 } else { 5417 ai = getActivityInfo(comp, flags, userId); 5418 if (ai == null) { 5419 continue; 5420 } 5421 } 5422 5423 // Look for any generic query activities that are duplicates 5424 // of this specific one, and remove them from the results. 5425 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5426 N = results.size(); 5427 int j; 5428 for (j=specificsPos; j<N; j++) { 5429 ResolveInfo sri = results.get(j); 5430 if ((sri.activityInfo.name.equals(comp.getClassName()) 5431 && sri.activityInfo.applicationInfo.packageName.equals( 5432 comp.getPackageName())) 5433 || (action != null && sri.filter.matchAction(action))) { 5434 results.remove(j); 5435 if (DEBUG_INTENT_MATCHING) Log.v( 5436 TAG, "Removing duplicate item from " + j 5437 + " due to specific " + specificsPos); 5438 if (ri == null) { 5439 ri = sri; 5440 } 5441 j--; 5442 N--; 5443 } 5444 } 5445 5446 // Add this specific item to its proper place. 5447 if (ri == null) { 5448 ri = new ResolveInfo(); 5449 ri.activityInfo = ai; 5450 } 5451 results.add(specificsPos, ri); 5452 ri.specificIndex = i; 5453 specificsPos++; 5454 } 5455 } 5456 5457 // Now we go through the remaining generic results and remove any 5458 // duplicate actions that are found here. 5459 N = results.size(); 5460 for (int i=specificsPos; i<N-1; i++) { 5461 final ResolveInfo rii = results.get(i); 5462 if (rii.filter == null) { 5463 continue; 5464 } 5465 5466 // Iterate over all of the actions of this result's intent 5467 // filter... typically this should be just one. 5468 final Iterator<String> it = rii.filter.actionsIterator(); 5469 if (it == null) { 5470 continue; 5471 } 5472 while (it.hasNext()) { 5473 final String action = it.next(); 5474 if (resultsAction != null && resultsAction.equals(action)) { 5475 // If this action was explicitly requested, then don't 5476 // remove things that have it. 5477 continue; 5478 } 5479 for (int j=i+1; j<N; j++) { 5480 final ResolveInfo rij = results.get(j); 5481 if (rij.filter != null && rij.filter.hasAction(action)) { 5482 results.remove(j); 5483 if (DEBUG_INTENT_MATCHING) Log.v( 5484 TAG, "Removing duplicate item from " + j 5485 + " due to action " + action + " at " + i); 5486 j--; 5487 N--; 5488 } 5489 } 5490 } 5491 5492 // If the caller didn't request filter information, drop it now 5493 // so we don't have to marshall/unmarshall it. 5494 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5495 rii.filter = null; 5496 } 5497 } 5498 5499 // Filter out the caller activity if so requested. 5500 if (caller != null) { 5501 N = results.size(); 5502 for (int i=0; i<N; i++) { 5503 ActivityInfo ainfo = results.get(i).activityInfo; 5504 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5505 && caller.getClassName().equals(ainfo.name)) { 5506 results.remove(i); 5507 break; 5508 } 5509 } 5510 } 5511 5512 // If the caller didn't request filter information, 5513 // drop them now so we don't have to 5514 // marshall/unmarshall it. 5515 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5516 N = results.size(); 5517 for (int i=0; i<N; i++) { 5518 results.get(i).filter = null; 5519 } 5520 } 5521 5522 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5523 return results; 5524 } 5525 5526 @Override 5527 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5528 int userId) { 5529 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5530 flags = updateFlagsForResolve(flags, userId, intent); 5531 ComponentName comp = intent.getComponent(); 5532 if (comp == null) { 5533 if (intent.getSelector() != null) { 5534 intent = intent.getSelector(); 5535 comp = intent.getComponent(); 5536 } 5537 } 5538 if (comp != null) { 5539 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5540 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5541 if (ai != null) { 5542 ResolveInfo ri = new ResolveInfo(); 5543 ri.activityInfo = ai; 5544 list.add(ri); 5545 } 5546 return list; 5547 } 5548 5549 // reader 5550 synchronized (mPackages) { 5551 String pkgName = intent.getPackage(); 5552 if (pkgName == null) { 5553 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5554 } 5555 final PackageParser.Package pkg = mPackages.get(pkgName); 5556 if (pkg != null) { 5557 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5558 userId); 5559 } 5560 return null; 5561 } 5562 } 5563 5564 @Override 5565 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5566 if (!sUserManager.exists(userId)) return null; 5567 flags = updateFlagsForResolve(flags, userId, intent); 5568 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5569 if (query != null) { 5570 if (query.size() >= 1) { 5571 // If there is more than one service with the same priority, 5572 // just arbitrarily pick the first one. 5573 return query.get(0); 5574 } 5575 } 5576 return null; 5577 } 5578 5579 @Override 5580 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5581 int userId) { 5582 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5583 flags = updateFlagsForResolve(flags, userId, intent); 5584 ComponentName comp = intent.getComponent(); 5585 if (comp == null) { 5586 if (intent.getSelector() != null) { 5587 intent = intent.getSelector(); 5588 comp = intent.getComponent(); 5589 } 5590 } 5591 if (comp != null) { 5592 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5593 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5594 if (si != null) { 5595 final ResolveInfo ri = new ResolveInfo(); 5596 ri.serviceInfo = si; 5597 list.add(ri); 5598 } 5599 return list; 5600 } 5601 5602 // reader 5603 synchronized (mPackages) { 5604 String pkgName = intent.getPackage(); 5605 if (pkgName == null) { 5606 return mServices.queryIntent(intent, resolvedType, flags, userId); 5607 } 5608 final PackageParser.Package pkg = mPackages.get(pkgName); 5609 if (pkg != null) { 5610 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5611 userId); 5612 } 5613 return null; 5614 } 5615 } 5616 5617 @Override 5618 public List<ResolveInfo> queryIntentContentProviders( 5619 Intent intent, String resolvedType, int flags, int userId) { 5620 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5621 flags = updateFlagsForResolve(flags, userId, intent); 5622 ComponentName comp = intent.getComponent(); 5623 if (comp == null) { 5624 if (intent.getSelector() != null) { 5625 intent = intent.getSelector(); 5626 comp = intent.getComponent(); 5627 } 5628 } 5629 if (comp != null) { 5630 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5631 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5632 if (pi != null) { 5633 final ResolveInfo ri = new ResolveInfo(); 5634 ri.providerInfo = pi; 5635 list.add(ri); 5636 } 5637 return list; 5638 } 5639 5640 // reader 5641 synchronized (mPackages) { 5642 String pkgName = intent.getPackage(); 5643 if (pkgName == null) { 5644 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5645 } 5646 final PackageParser.Package pkg = mPackages.get(pkgName); 5647 if (pkg != null) { 5648 return mProviders.queryIntentForPackage( 5649 intent, resolvedType, flags, pkg.providers, userId); 5650 } 5651 return null; 5652 } 5653 } 5654 5655 @Override 5656 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5657 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5658 flags = updateFlagsForPackage(flags, userId, null); 5659 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5660 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5661 5662 // writer 5663 synchronized (mPackages) { 5664 ArrayList<PackageInfo> list; 5665 if (listUninstalled) { 5666 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5667 for (PackageSetting ps : mSettings.mPackages.values()) { 5668 PackageInfo pi; 5669 if (ps.pkg != null) { 5670 pi = generatePackageInfo(ps.pkg, flags, userId); 5671 } else { 5672 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5673 } 5674 if (pi != null) { 5675 list.add(pi); 5676 } 5677 } 5678 } else { 5679 list = new ArrayList<PackageInfo>(mPackages.size()); 5680 for (PackageParser.Package p : mPackages.values()) { 5681 PackageInfo pi = generatePackageInfo(p, flags, userId); 5682 if (pi != null) { 5683 list.add(pi); 5684 } 5685 } 5686 } 5687 5688 return new ParceledListSlice<PackageInfo>(list); 5689 } 5690 } 5691 5692 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5693 String[] permissions, boolean[] tmp, int flags, int userId) { 5694 int numMatch = 0; 5695 final PermissionsState permissionsState = ps.getPermissionsState(); 5696 for (int i=0; i<permissions.length; i++) { 5697 final String permission = permissions[i]; 5698 if (permissionsState.hasPermission(permission, userId)) { 5699 tmp[i] = true; 5700 numMatch++; 5701 } else { 5702 tmp[i] = false; 5703 } 5704 } 5705 if (numMatch == 0) { 5706 return; 5707 } 5708 PackageInfo pi; 5709 if (ps.pkg != null) { 5710 pi = generatePackageInfo(ps.pkg, flags, userId); 5711 } else { 5712 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5713 } 5714 // The above might return null in cases of uninstalled apps or install-state 5715 // skew across users/profiles. 5716 if (pi != null) { 5717 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5718 if (numMatch == permissions.length) { 5719 pi.requestedPermissions = permissions; 5720 } else { 5721 pi.requestedPermissions = new String[numMatch]; 5722 numMatch = 0; 5723 for (int i=0; i<permissions.length; i++) { 5724 if (tmp[i]) { 5725 pi.requestedPermissions[numMatch] = permissions[i]; 5726 numMatch++; 5727 } 5728 } 5729 } 5730 } 5731 list.add(pi); 5732 } 5733 } 5734 5735 @Override 5736 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5737 String[] permissions, int flags, int userId) { 5738 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5739 flags = updateFlagsForPackage(flags, userId, permissions); 5740 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5741 5742 // writer 5743 synchronized (mPackages) { 5744 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5745 boolean[] tmpBools = new boolean[permissions.length]; 5746 if (listUninstalled) { 5747 for (PackageSetting ps : mSettings.mPackages.values()) { 5748 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5749 } 5750 } else { 5751 for (PackageParser.Package pkg : mPackages.values()) { 5752 PackageSetting ps = (PackageSetting)pkg.mExtras; 5753 if (ps != null) { 5754 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5755 userId); 5756 } 5757 } 5758 } 5759 5760 return new ParceledListSlice<PackageInfo>(list); 5761 } 5762 } 5763 5764 @Override 5765 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5766 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5767 flags = updateFlagsForApplication(flags, userId, null); 5768 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5769 5770 // writer 5771 synchronized (mPackages) { 5772 ArrayList<ApplicationInfo> list; 5773 if (listUninstalled) { 5774 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5775 for (PackageSetting ps : mSettings.mPackages.values()) { 5776 ApplicationInfo ai; 5777 if (ps.pkg != null) { 5778 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5779 ps.readUserState(userId), userId); 5780 } else { 5781 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5782 } 5783 if (ai != null) { 5784 list.add(ai); 5785 } 5786 } 5787 } else { 5788 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5789 for (PackageParser.Package p : mPackages.values()) { 5790 if (p.mExtras != null) { 5791 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5792 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5793 if (ai != null) { 5794 list.add(ai); 5795 } 5796 } 5797 } 5798 } 5799 5800 return new ParceledListSlice<ApplicationInfo>(list); 5801 } 5802 } 5803 5804 @Override 5805 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5806 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5807 "getEphemeralApplications"); 5808 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5809 "getEphemeralApplications"); 5810 synchronized (mPackages) { 5811 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5812 .getEphemeralApplicationsLPw(userId); 5813 if (ephemeralApps != null) { 5814 return new ParceledListSlice<>(ephemeralApps); 5815 } 5816 } 5817 return null; 5818 } 5819 5820 @Override 5821 public boolean isEphemeralApplication(String packageName, int userId) { 5822 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5823 "isEphemeral"); 5824 if (!isCallerSameApp(packageName)) { 5825 return false; 5826 } 5827 synchronized (mPackages) { 5828 PackageParser.Package pkg = mPackages.get(packageName); 5829 if (pkg != null) { 5830 return pkg.applicationInfo.isEphemeralApp(); 5831 } 5832 } 5833 return false; 5834 } 5835 5836 @Override 5837 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5838 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5839 "getCookie"); 5840 if (!isCallerSameApp(packageName)) { 5841 return null; 5842 } 5843 synchronized (mPackages) { 5844 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5845 packageName, userId); 5846 } 5847 } 5848 5849 @Override 5850 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5851 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5852 "setCookie"); 5853 if (!isCallerSameApp(packageName)) { 5854 return false; 5855 } 5856 synchronized (mPackages) { 5857 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5858 packageName, cookie, userId); 5859 } 5860 } 5861 5862 @Override 5863 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5864 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5865 "getEphemeralApplicationIcon"); 5866 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5867 "getEphemeralApplicationIcon"); 5868 synchronized (mPackages) { 5869 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5870 packageName, userId); 5871 } 5872 } 5873 5874 private boolean isCallerSameApp(String packageName) { 5875 PackageParser.Package pkg = mPackages.get(packageName); 5876 return pkg != null 5877 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5878 } 5879 5880 public List<ApplicationInfo> getPersistentApplications(int flags) { 5881 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5882 5883 // reader 5884 synchronized (mPackages) { 5885 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5886 final int userId = UserHandle.getCallingUserId(); 5887 while (i.hasNext()) { 5888 final PackageParser.Package p = i.next(); 5889 if (p.applicationInfo != null 5890 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5891 && (!mSafeMode || isSystemApp(p))) { 5892 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5893 if (ps != null) { 5894 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5895 ps.readUserState(userId), userId); 5896 if (ai != null) { 5897 finalList.add(ai); 5898 } 5899 } 5900 } 5901 } 5902 } 5903 5904 return finalList; 5905 } 5906 5907 @Override 5908 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5909 if (!sUserManager.exists(userId)) return null; 5910 flags = updateFlagsForComponent(flags, userId, name); 5911 // reader 5912 synchronized (mPackages) { 5913 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5914 PackageSetting ps = provider != null 5915 ? mSettings.mPackages.get(provider.owner.packageName) 5916 : null; 5917 return ps != null 5918 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 5919 && (!mSafeMode || (provider.info.applicationInfo.flags 5920 &ApplicationInfo.FLAG_SYSTEM) != 0) 5921 ? PackageParser.generateProviderInfo(provider, flags, 5922 ps.readUserState(userId), userId) 5923 : null; 5924 } 5925 } 5926 5927 /** 5928 * @deprecated 5929 */ 5930 @Deprecated 5931 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5932 // reader 5933 synchronized (mPackages) { 5934 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5935 .entrySet().iterator(); 5936 final int userId = UserHandle.getCallingUserId(); 5937 while (i.hasNext()) { 5938 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5939 PackageParser.Provider p = entry.getValue(); 5940 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5941 5942 if (ps != null && p.syncable 5943 && (!mSafeMode || (p.info.applicationInfo.flags 5944 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5945 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5946 ps.readUserState(userId), userId); 5947 if (info != null) { 5948 outNames.add(entry.getKey()); 5949 outInfo.add(info); 5950 } 5951 } 5952 } 5953 } 5954 } 5955 5956 @Override 5957 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5958 int uid, int flags) { 5959 final int userId = processName != null ? UserHandle.getUserId(uid) 5960 : UserHandle.getCallingUserId(); 5961 if (!sUserManager.exists(userId)) return null; 5962 flags = updateFlagsForComponent(flags, userId, processName); 5963 5964 ArrayList<ProviderInfo> finalList = null; 5965 // reader 5966 synchronized (mPackages) { 5967 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5968 while (i.hasNext()) { 5969 final PackageParser.Provider p = i.next(); 5970 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5971 if (ps != null && p.info.authority != null 5972 && (processName == null 5973 || (p.info.processName.equals(processName) 5974 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5975 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId) 5976 && (!mSafeMode 5977 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5978 if (finalList == null) { 5979 finalList = new ArrayList<ProviderInfo>(3); 5980 } 5981 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5982 ps.readUserState(userId), userId); 5983 if (info != null) { 5984 finalList.add(info); 5985 } 5986 } 5987 } 5988 } 5989 5990 if (finalList != null) { 5991 Collections.sort(finalList, mProviderInitOrderSorter); 5992 return new ParceledListSlice<ProviderInfo>(finalList); 5993 } 5994 5995 return null; 5996 } 5997 5998 @Override 5999 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6000 // reader 6001 synchronized (mPackages) { 6002 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6003 return PackageParser.generateInstrumentationInfo(i, flags); 6004 } 6005 } 6006 6007 @Override 6008 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6009 int flags) { 6010 ArrayList<InstrumentationInfo> finalList = 6011 new ArrayList<InstrumentationInfo>(); 6012 6013 // reader 6014 synchronized (mPackages) { 6015 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6016 while (i.hasNext()) { 6017 final PackageParser.Instrumentation p = i.next(); 6018 if (targetPackage == null 6019 || targetPackage.equals(p.info.targetPackage)) { 6020 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6021 flags); 6022 if (ii != null) { 6023 finalList.add(ii); 6024 } 6025 } 6026 } 6027 } 6028 6029 return finalList; 6030 } 6031 6032 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6033 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6034 if (overlays == null) { 6035 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6036 return; 6037 } 6038 for (PackageParser.Package opkg : overlays.values()) { 6039 // Not much to do if idmap fails: we already logged the error 6040 // and we certainly don't want to abort installation of pkg simply 6041 // because an overlay didn't fit properly. For these reasons, 6042 // ignore the return value of createIdmapForPackagePairLI. 6043 createIdmapForPackagePairLI(pkg, opkg); 6044 } 6045 } 6046 6047 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6048 PackageParser.Package opkg) { 6049 if (!opkg.mTrustedOverlay) { 6050 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6051 opkg.baseCodePath + ": overlay not trusted"); 6052 return false; 6053 } 6054 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6055 if (overlaySet == null) { 6056 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6057 opkg.baseCodePath + " but target package has no known overlays"); 6058 return false; 6059 } 6060 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6061 // TODO: generate idmap for split APKs 6062 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6063 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6064 + opkg.baseCodePath); 6065 return false; 6066 } 6067 PackageParser.Package[] overlayArray = 6068 overlaySet.values().toArray(new PackageParser.Package[0]); 6069 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6070 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6071 return p1.mOverlayPriority - p2.mOverlayPriority; 6072 } 6073 }; 6074 Arrays.sort(overlayArray, cmp); 6075 6076 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6077 int i = 0; 6078 for (PackageParser.Package p : overlayArray) { 6079 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6080 } 6081 return true; 6082 } 6083 6084 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6085 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6086 try { 6087 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6088 } finally { 6089 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6090 } 6091 } 6092 6093 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6094 final File[] files = dir.listFiles(); 6095 if (ArrayUtils.isEmpty(files)) { 6096 Log.d(TAG, "No files in app dir " + dir); 6097 return; 6098 } 6099 6100 if (DEBUG_PACKAGE_SCANNING) { 6101 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6102 + " flags=0x" + Integer.toHexString(parseFlags)); 6103 } 6104 6105 for (File file : files) { 6106 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6107 && !PackageInstallerService.isStageName(file.getName()); 6108 if (!isPackage) { 6109 // Ignore entries which are not packages 6110 continue; 6111 } 6112 try { 6113 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6114 scanFlags, currentTime, null); 6115 } catch (PackageManagerException e) { 6116 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6117 6118 // Delete invalid userdata apps 6119 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6120 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6121 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6122 if (file.isDirectory()) { 6123 mInstaller.rmPackageDir(file.getAbsolutePath()); 6124 } else { 6125 file.delete(); 6126 } 6127 } 6128 } 6129 } 6130 } 6131 6132 private static File getSettingsProblemFile() { 6133 File dataDir = Environment.getDataDirectory(); 6134 File systemDir = new File(dataDir, "system"); 6135 File fname = new File(systemDir, "uiderrors.txt"); 6136 return fname; 6137 } 6138 6139 static void reportSettingsProblem(int priority, String msg) { 6140 logCriticalInfo(priority, msg); 6141 } 6142 6143 static void logCriticalInfo(int priority, String msg) { 6144 Slog.println(priority, TAG, msg); 6145 EventLogTags.writePmCriticalInfo(msg); 6146 try { 6147 File fname = getSettingsProblemFile(); 6148 FileOutputStream out = new FileOutputStream(fname, true); 6149 PrintWriter pw = new FastPrintWriter(out); 6150 SimpleDateFormat formatter = new SimpleDateFormat(); 6151 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6152 pw.println(dateString + ": " + msg); 6153 pw.close(); 6154 FileUtils.setPermissions( 6155 fname.toString(), 6156 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6157 -1, -1); 6158 } catch (java.io.IOException e) { 6159 } 6160 } 6161 6162 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6163 PackageParser.Package pkg, File srcFile, int parseFlags) 6164 throws PackageManagerException { 6165 if (ps != null 6166 && ps.codePath.equals(srcFile) 6167 && ps.timeStamp == srcFile.lastModified() 6168 && !isCompatSignatureUpdateNeeded(pkg) 6169 && !isRecoverSignatureUpdateNeeded(pkg)) { 6170 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6171 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6172 ArraySet<PublicKey> signingKs; 6173 synchronized (mPackages) { 6174 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6175 } 6176 if (ps.signatures.mSignatures != null 6177 && ps.signatures.mSignatures.length != 0 6178 && signingKs != null) { 6179 // Optimization: reuse the existing cached certificates 6180 // if the package appears to be unchanged. 6181 pkg.mSignatures = ps.signatures.mSignatures; 6182 pkg.mSigningKeys = signingKs; 6183 return; 6184 } 6185 6186 Slog.w(TAG, "PackageSetting for " + ps.name 6187 + " is missing signatures. Collecting certs again to recover them."); 6188 } else { 6189 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6190 } 6191 6192 try { 6193 pp.collectCertificates(pkg, parseFlags); 6194 } catch (PackageParserException e) { 6195 throw PackageManagerException.from(e); 6196 } 6197 } 6198 6199 /** 6200 * Traces a package scan. 6201 * @see #scanPackageLI(File, int, int, long, UserHandle) 6202 */ 6203 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6204 long currentTime, UserHandle user) throws PackageManagerException { 6205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6206 try { 6207 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6208 } finally { 6209 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6210 } 6211 } 6212 6213 /** 6214 * Scans a package and returns the newly parsed package. 6215 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6216 */ 6217 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6218 long currentTime, UserHandle user) throws PackageManagerException { 6219 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6220 parseFlags |= mDefParseFlags; 6221 PackageParser pp = new PackageParser(); 6222 pp.setSeparateProcesses(mSeparateProcesses); 6223 pp.setOnlyCoreApps(mOnlyCore); 6224 pp.setDisplayMetrics(mMetrics); 6225 6226 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6227 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6228 } 6229 6230 final PackageParser.Package pkg; 6231 try { 6232 pkg = pp.parsePackage(scanFile, parseFlags); 6233 } catch (PackageParserException e) { 6234 throw PackageManagerException.from(e); 6235 } 6236 6237 PackageSetting ps = null; 6238 PackageSetting updatedPkg; 6239 // reader 6240 synchronized (mPackages) { 6241 // Look to see if we already know about this package. 6242 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6243 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6244 // This package has been renamed to its original name. Let's 6245 // use that. 6246 ps = mSettings.peekPackageLPr(oldName); 6247 } 6248 // If there was no original package, see one for the real package name. 6249 if (ps == null) { 6250 ps = mSettings.peekPackageLPr(pkg.packageName); 6251 } 6252 // Check to see if this package could be hiding/updating a system 6253 // package. Must look for it either under the original or real 6254 // package name depending on our state. 6255 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6256 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6257 } 6258 boolean updatedPkgBetter = false; 6259 // First check if this is a system package that may involve an update 6260 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6261 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6262 // it needs to drop FLAG_PRIVILEGED. 6263 if (locationIsPrivileged(scanFile)) { 6264 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6265 } else { 6266 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6267 } 6268 6269 if (ps != null && !ps.codePath.equals(scanFile)) { 6270 // The path has changed from what was last scanned... check the 6271 // version of the new path against what we have stored to determine 6272 // what to do. 6273 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6274 if (pkg.mVersionCode <= ps.versionCode) { 6275 // The system package has been updated and the code path does not match 6276 // Ignore entry. Skip it. 6277 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6278 + " ignored: updated version " + ps.versionCode 6279 + " better than this " + pkg.mVersionCode); 6280 if (!updatedPkg.codePath.equals(scanFile)) { 6281 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6282 + ps.name + " changing from " + updatedPkg.codePathString 6283 + " to " + scanFile); 6284 updatedPkg.codePath = scanFile; 6285 updatedPkg.codePathString = scanFile.toString(); 6286 updatedPkg.resourcePath = scanFile; 6287 updatedPkg.resourcePathString = scanFile.toString(); 6288 } 6289 updatedPkg.pkg = pkg; 6290 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6291 "Package " + ps.name + " at " + scanFile 6292 + " ignored: updated version " + ps.versionCode 6293 + " better than this " + pkg.mVersionCode); 6294 } else { 6295 // The current app on the system partition is better than 6296 // what we have updated to on the data partition; switch 6297 // back to the system partition version. 6298 // At this point, its safely assumed that package installation for 6299 // apps in system partition will go through. If not there won't be a working 6300 // version of the app 6301 // writer 6302 synchronized (mPackages) { 6303 // Just remove the loaded entries from package lists. 6304 mPackages.remove(ps.name); 6305 } 6306 6307 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6308 + " reverting from " + ps.codePathString 6309 + ": new version " + pkg.mVersionCode 6310 + " better than installed " + ps.versionCode); 6311 6312 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6313 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6314 synchronized (mInstallLock) { 6315 args.cleanUpResourcesLI(); 6316 } 6317 synchronized (mPackages) { 6318 mSettings.enableSystemPackageLPw(ps.name); 6319 } 6320 updatedPkgBetter = true; 6321 } 6322 } 6323 } 6324 6325 if (updatedPkg != null) { 6326 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6327 // initially 6328 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6329 6330 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6331 // flag set initially 6332 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6333 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6334 } 6335 } 6336 6337 // Verify certificates against what was last scanned 6338 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6339 6340 /* 6341 * A new system app appeared, but we already had a non-system one of the 6342 * same name installed earlier. 6343 */ 6344 boolean shouldHideSystemApp = false; 6345 if (updatedPkg == null && ps != null 6346 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6347 /* 6348 * Check to make sure the signatures match first. If they don't, 6349 * wipe the installed application and its data. 6350 */ 6351 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6352 != PackageManager.SIGNATURE_MATCH) { 6353 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6354 + " signatures don't match existing userdata copy; removing"); 6355 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6356 ps = null; 6357 } else { 6358 /* 6359 * If the newly-added system app is an older version than the 6360 * already installed version, hide it. It will be scanned later 6361 * and re-added like an update. 6362 */ 6363 if (pkg.mVersionCode <= ps.versionCode) { 6364 shouldHideSystemApp = true; 6365 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6366 + " but new version " + pkg.mVersionCode + " better than installed " 6367 + ps.versionCode + "; hiding system"); 6368 } else { 6369 /* 6370 * The newly found system app is a newer version that the 6371 * one previously installed. Simply remove the 6372 * already-installed application and replace it with our own 6373 * while keeping the application data. 6374 */ 6375 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6376 + " reverting from " + ps.codePathString + ": new version " 6377 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6378 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6379 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6380 synchronized (mInstallLock) { 6381 args.cleanUpResourcesLI(); 6382 } 6383 } 6384 } 6385 } 6386 6387 // The apk is forward locked (not public) if its code and resources 6388 // are kept in different files. (except for app in either system or 6389 // vendor path). 6390 // TODO grab this value from PackageSettings 6391 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6392 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6393 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6394 } 6395 } 6396 6397 // TODO: extend to support forward-locked splits 6398 String resourcePath = null; 6399 String baseResourcePath = null; 6400 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6401 if (ps != null && ps.resourcePathString != null) { 6402 resourcePath = ps.resourcePathString; 6403 baseResourcePath = ps.resourcePathString; 6404 } else { 6405 // Should not happen at all. Just log an error. 6406 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6407 } 6408 } else { 6409 resourcePath = pkg.codePath; 6410 baseResourcePath = pkg.baseCodePath; 6411 } 6412 6413 // Set application objects path explicitly. 6414 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6415 pkg.applicationInfo.setCodePath(pkg.codePath); 6416 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6417 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6418 pkg.applicationInfo.setResourcePath(resourcePath); 6419 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6420 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6421 6422 // Note that we invoke the following method only if we are about to unpack an application 6423 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6424 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6425 6426 /* 6427 * If the system app should be overridden by a previously installed 6428 * data, hide the system app now and let the /data/app scan pick it up 6429 * again. 6430 */ 6431 if (shouldHideSystemApp) { 6432 synchronized (mPackages) { 6433 mSettings.disableSystemPackageLPw(pkg.packageName); 6434 } 6435 } 6436 6437 return scannedPkg; 6438 } 6439 6440 private static String fixProcessName(String defProcessName, 6441 String processName, int uid) { 6442 if (processName == null) { 6443 return defProcessName; 6444 } 6445 return processName; 6446 } 6447 6448 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6449 throws PackageManagerException { 6450 if (pkgSetting.signatures.mSignatures != null) { 6451 // Already existing package. Make sure signatures match 6452 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6453 == PackageManager.SIGNATURE_MATCH; 6454 if (!match) { 6455 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6456 == PackageManager.SIGNATURE_MATCH; 6457 } 6458 if (!match) { 6459 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6460 == PackageManager.SIGNATURE_MATCH; 6461 } 6462 if (!match) { 6463 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6464 + pkg.packageName + " signatures do not match the " 6465 + "previously installed version; ignoring!"); 6466 } 6467 } 6468 6469 // Check for shared user signatures 6470 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6471 // Already existing package. Make sure signatures match 6472 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6473 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6474 if (!match) { 6475 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6476 == PackageManager.SIGNATURE_MATCH; 6477 } 6478 if (!match) { 6479 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6480 == PackageManager.SIGNATURE_MATCH; 6481 } 6482 if (!match) { 6483 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6484 "Package " + pkg.packageName 6485 + " has no signatures that match those in shared user " 6486 + pkgSetting.sharedUser.name + "; ignoring!"); 6487 } 6488 } 6489 } 6490 6491 /** 6492 * Enforces that only the system UID or root's UID can call a method exposed 6493 * via Binder. 6494 * 6495 * @param message used as message if SecurityException is thrown 6496 * @throws SecurityException if the caller is not system or root 6497 */ 6498 private static final void enforceSystemOrRoot(String message) { 6499 final int uid = Binder.getCallingUid(); 6500 if (uid != Process.SYSTEM_UID && uid != 0) { 6501 throw new SecurityException(message); 6502 } 6503 } 6504 6505 @Override 6506 public void performFstrimIfNeeded() { 6507 enforceSystemOrRoot("Only the system can request fstrim"); 6508 6509 // Before everything else, see whether we need to fstrim. 6510 try { 6511 IMountService ms = PackageHelper.getMountService(); 6512 if (ms != null) { 6513 final boolean isUpgrade = isUpgrade(); 6514 boolean doTrim = isUpgrade; 6515 if (doTrim) { 6516 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6517 } else { 6518 final long interval = android.provider.Settings.Global.getLong( 6519 mContext.getContentResolver(), 6520 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6521 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6522 if (interval > 0) { 6523 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6524 if (timeSinceLast > interval) { 6525 doTrim = true; 6526 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6527 + "; running immediately"); 6528 } 6529 } 6530 } 6531 if (doTrim) { 6532 if (!isFirstBoot()) { 6533 try { 6534 ActivityManagerNative.getDefault().showBootMessage( 6535 mContext.getResources().getString( 6536 R.string.android_upgrading_fstrim), true); 6537 } catch (RemoteException e) { 6538 } 6539 } 6540 ms.runMaintenance(); 6541 } 6542 } else { 6543 Slog.e(TAG, "Mount service unavailable!"); 6544 } 6545 } catch (RemoteException e) { 6546 // Can't happen; MountService is local 6547 } 6548 } 6549 6550 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6551 List<ResolveInfo> ris = null; 6552 try { 6553 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6554 intent, null, 0, userId); 6555 } catch (RemoteException e) { 6556 } 6557 ArraySet<String> pkgNames = new ArraySet<String>(); 6558 if (ris != null) { 6559 for (ResolveInfo ri : ris) { 6560 pkgNames.add(ri.activityInfo.packageName); 6561 } 6562 } 6563 return pkgNames; 6564 } 6565 6566 @Override 6567 public void notifyPackageUse(String packageName) { 6568 synchronized (mPackages) { 6569 PackageParser.Package p = mPackages.get(packageName); 6570 if (p == null) { 6571 return; 6572 } 6573 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6574 } 6575 } 6576 6577 @Override 6578 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6579 return performDexOptTraced(packageName, instructionSet); 6580 } 6581 6582 public boolean performDexOpt(String packageName, String instructionSet) { 6583 return performDexOptTraced(packageName, instructionSet); 6584 } 6585 6586 private boolean performDexOptTraced(String packageName, String instructionSet) { 6587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6588 try { 6589 return performDexOptInternal(packageName, instructionSet); 6590 } finally { 6591 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6592 } 6593 } 6594 6595 private boolean performDexOptInternal(String packageName, String instructionSet) { 6596 PackageParser.Package p; 6597 final String targetInstructionSet; 6598 synchronized (mPackages) { 6599 p = mPackages.get(packageName); 6600 if (p == null) { 6601 return false; 6602 } 6603 mPackageUsage.write(false); 6604 6605 targetInstructionSet = instructionSet != null ? instructionSet : 6606 getPrimaryInstructionSet(p.applicationInfo); 6607 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6608 return false; 6609 } 6610 } 6611 long callingId = Binder.clearCallingIdentity(); 6612 try { 6613 synchronized (mInstallLock) { 6614 final String[] instructionSets = new String[] { targetInstructionSet }; 6615 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6616 true /* inclDependencies */); 6617 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6618 } 6619 } finally { 6620 Binder.restoreCallingIdentity(callingId); 6621 } 6622 } 6623 6624 public ArraySet<String> getPackagesThatNeedDexOpt() { 6625 ArraySet<String> pkgs = null; 6626 synchronized (mPackages) { 6627 for (PackageParser.Package p : mPackages.values()) { 6628 if (DEBUG_DEXOPT) { 6629 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6630 } 6631 if (!p.mDexOptPerformed.isEmpty()) { 6632 continue; 6633 } 6634 if (pkgs == null) { 6635 pkgs = new ArraySet<String>(); 6636 } 6637 pkgs.add(p.packageName); 6638 } 6639 } 6640 return pkgs; 6641 } 6642 6643 public void shutdown() { 6644 mPackageUsage.write(true); 6645 } 6646 6647 @Override 6648 public void forceDexOpt(String packageName) { 6649 enforceSystemOrRoot("forceDexOpt"); 6650 6651 PackageParser.Package pkg; 6652 synchronized (mPackages) { 6653 pkg = mPackages.get(packageName); 6654 if (pkg == null) { 6655 throw new IllegalArgumentException("Unknown package: " + packageName); 6656 } 6657 } 6658 6659 synchronized (mInstallLock) { 6660 final String[] instructionSets = new String[] { 6661 getPrimaryInstructionSet(pkg.applicationInfo) }; 6662 6663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6664 6665 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6666 true /* inclDependencies */); 6667 6668 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6669 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6670 throw new IllegalStateException("Failed to dexopt: " + res); 6671 } 6672 } 6673 } 6674 6675 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6676 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6677 Slog.w(TAG, "Unable to update from " + oldPkg.name 6678 + " to " + newPkg.packageName 6679 + ": old package not in system partition"); 6680 return false; 6681 } else if (mPackages.get(oldPkg.name) != null) { 6682 Slog.w(TAG, "Unable to update from " + oldPkg.name 6683 + " to " + newPkg.packageName 6684 + ": old package still exists"); 6685 return false; 6686 } 6687 return true; 6688 } 6689 6690 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6691 throws PackageManagerException { 6692 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6693 if (res != 0) { 6694 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6695 "Failed to install " + packageName + ": " + res); 6696 } 6697 6698 final int[] users = sUserManager.getUserIds(); 6699 for (int user : users) { 6700 if (user != 0) { 6701 res = mInstaller.createUserData(volumeUuid, packageName, 6702 UserHandle.getUid(user, uid), user, seinfo); 6703 if (res != 0) { 6704 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6705 "Failed to createUserData " + packageName + ": " + res); 6706 } 6707 } 6708 } 6709 } 6710 6711 private int removeDataDirsLI(String volumeUuid, String packageName) { 6712 int[] users = sUserManager.getUserIds(); 6713 int res = 0; 6714 for (int user : users) { 6715 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6716 if (resInner < 0) { 6717 res = resInner; 6718 } 6719 } 6720 6721 return res; 6722 } 6723 6724 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6725 int[] users = sUserManager.getUserIds(); 6726 int res = 0; 6727 for (int user : users) { 6728 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6729 if (resInner < 0) { 6730 res = resInner; 6731 } 6732 } 6733 return res; 6734 } 6735 6736 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6737 PackageParser.Package changingLib) { 6738 if (file.path != null) { 6739 usesLibraryFiles.add(file.path); 6740 return; 6741 } 6742 PackageParser.Package p = mPackages.get(file.apk); 6743 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6744 // If we are doing this while in the middle of updating a library apk, 6745 // then we need to make sure to use that new apk for determining the 6746 // dependencies here. (We haven't yet finished committing the new apk 6747 // to the package manager state.) 6748 if (p == null || p.packageName.equals(changingLib.packageName)) { 6749 p = changingLib; 6750 } 6751 } 6752 if (p != null) { 6753 usesLibraryFiles.addAll(p.getAllCodePaths()); 6754 } 6755 } 6756 6757 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6758 PackageParser.Package changingLib) throws PackageManagerException { 6759 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6760 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6761 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6762 for (int i=0; i<N; i++) { 6763 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6764 if (file == null) { 6765 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6766 "Package " + pkg.packageName + " requires unavailable shared library " 6767 + pkg.usesLibraries.get(i) + "; failing!"); 6768 } 6769 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6770 } 6771 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6772 for (int i=0; i<N; i++) { 6773 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6774 if (file == null) { 6775 Slog.w(TAG, "Package " + pkg.packageName 6776 + " desires unavailable shared library " 6777 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6778 } else { 6779 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6780 } 6781 } 6782 N = usesLibraryFiles.size(); 6783 if (N > 0) { 6784 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6785 } else { 6786 pkg.usesLibraryFiles = null; 6787 } 6788 } 6789 } 6790 6791 private static boolean hasString(List<String> list, List<String> which) { 6792 if (list == null) { 6793 return false; 6794 } 6795 for (int i=list.size()-1; i>=0; i--) { 6796 for (int j=which.size()-1; j>=0; j--) { 6797 if (which.get(j).equals(list.get(i))) { 6798 return true; 6799 } 6800 } 6801 } 6802 return false; 6803 } 6804 6805 private void updateAllSharedLibrariesLPw() { 6806 for (PackageParser.Package pkg : mPackages.values()) { 6807 try { 6808 updateSharedLibrariesLPw(pkg, null); 6809 } catch (PackageManagerException e) { 6810 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6811 } 6812 } 6813 } 6814 6815 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6816 PackageParser.Package changingPkg) { 6817 ArrayList<PackageParser.Package> res = null; 6818 for (PackageParser.Package pkg : mPackages.values()) { 6819 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6820 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6821 if (res == null) { 6822 res = new ArrayList<PackageParser.Package>(); 6823 } 6824 res.add(pkg); 6825 try { 6826 updateSharedLibrariesLPw(pkg, changingPkg); 6827 } catch (PackageManagerException e) { 6828 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6829 } 6830 } 6831 } 6832 return res; 6833 } 6834 6835 /** 6836 * Derive the value of the {@code cpuAbiOverride} based on the provided 6837 * value and an optional stored value from the package settings. 6838 */ 6839 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6840 String cpuAbiOverride = null; 6841 6842 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6843 cpuAbiOverride = null; 6844 } else if (abiOverride != null) { 6845 cpuAbiOverride = abiOverride; 6846 } else if (settings != null) { 6847 cpuAbiOverride = settings.cpuAbiOverrideString; 6848 } 6849 6850 return cpuAbiOverride; 6851 } 6852 6853 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6854 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6855 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6856 try { 6857 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6858 } finally { 6859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6860 } 6861 } 6862 6863 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6864 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6865 boolean success = false; 6866 try { 6867 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6868 currentTime, user); 6869 success = true; 6870 return res; 6871 } finally { 6872 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6873 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6874 } 6875 } 6876 } 6877 6878 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6879 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6880 final File scanFile = new File(pkg.codePath); 6881 if (pkg.applicationInfo.getCodePath() == null || 6882 pkg.applicationInfo.getResourcePath() == null) { 6883 // Bail out. The resource and code paths haven't been set. 6884 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6885 "Code and resource paths haven't been set correctly"); 6886 } 6887 6888 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6889 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6890 } else { 6891 // Only allow system apps to be flagged as core apps. 6892 pkg.coreApp = false; 6893 } 6894 6895 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6896 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6897 } 6898 6899 if (mCustomResolverComponentName != null && 6900 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6901 setUpCustomResolverActivity(pkg); 6902 } 6903 6904 if (pkg.packageName.equals("android")) { 6905 synchronized (mPackages) { 6906 if (mAndroidApplication != null) { 6907 Slog.w(TAG, "*************************************************"); 6908 Slog.w(TAG, "Core android package being redefined. Skipping."); 6909 Slog.w(TAG, " file=" + scanFile); 6910 Slog.w(TAG, "*************************************************"); 6911 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6912 "Core android package being redefined. Skipping."); 6913 } 6914 6915 // Set up information for our fall-back user intent resolution activity. 6916 mPlatformPackage = pkg; 6917 pkg.mVersionCode = mSdkVersion; 6918 mAndroidApplication = pkg.applicationInfo; 6919 6920 if (!mResolverReplaced) { 6921 mResolveActivity.applicationInfo = mAndroidApplication; 6922 mResolveActivity.name = ResolverActivity.class.getName(); 6923 mResolveActivity.packageName = mAndroidApplication.packageName; 6924 mResolveActivity.processName = "system:ui"; 6925 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6926 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6927 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6928 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6929 mResolveActivity.exported = true; 6930 mResolveActivity.enabled = true; 6931 mResolveInfo.activityInfo = mResolveActivity; 6932 mResolveInfo.priority = 0; 6933 mResolveInfo.preferredOrder = 0; 6934 mResolveInfo.match = 0; 6935 mResolveComponentName = new ComponentName( 6936 mAndroidApplication.packageName, mResolveActivity.name); 6937 } 6938 } 6939 } 6940 6941 if (DEBUG_PACKAGE_SCANNING) { 6942 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6943 Log.d(TAG, "Scanning package " + pkg.packageName); 6944 } 6945 6946 if (mPackages.containsKey(pkg.packageName) 6947 || mSharedLibraries.containsKey(pkg.packageName)) { 6948 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6949 "Application package " + pkg.packageName 6950 + " already installed. Skipping duplicate."); 6951 } 6952 6953 // If we're only installing presumed-existing packages, require that the 6954 // scanned APK is both already known and at the path previously established 6955 // for it. Previously unknown packages we pick up normally, but if we have an 6956 // a priori expectation about this package's install presence, enforce it. 6957 // With a singular exception for new system packages. When an OTA contains 6958 // a new system package, we allow the codepath to change from a system location 6959 // to the user-installed location. If we don't allow this change, any newer, 6960 // user-installed version of the application will be ignored. 6961 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6962 if (mExpectingBetter.containsKey(pkg.packageName)) { 6963 logCriticalInfo(Log.WARN, 6964 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6965 } else { 6966 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6967 if (known != null) { 6968 if (DEBUG_PACKAGE_SCANNING) { 6969 Log.d(TAG, "Examining " + pkg.codePath 6970 + " and requiring known paths " + known.codePathString 6971 + " & " + known.resourcePathString); 6972 } 6973 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6974 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6975 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6976 "Application package " + pkg.packageName 6977 + " found at " + pkg.applicationInfo.getCodePath() 6978 + " but expected at " + known.codePathString + "; ignoring."); 6979 } 6980 } 6981 } 6982 } 6983 6984 // Initialize package source and resource directories 6985 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6986 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6987 6988 SharedUserSetting suid = null; 6989 PackageSetting pkgSetting = null; 6990 6991 if (!isSystemApp(pkg)) { 6992 // Only system apps can use these features. 6993 pkg.mOriginalPackages = null; 6994 pkg.mRealPackage = null; 6995 pkg.mAdoptPermissions = null; 6996 } 6997 6998 // writer 6999 synchronized (mPackages) { 7000 if (pkg.mSharedUserId != null) { 7001 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7002 if (suid == null) { 7003 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7004 "Creating application package " + pkg.packageName 7005 + " for shared user failed"); 7006 } 7007 if (DEBUG_PACKAGE_SCANNING) { 7008 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7009 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7010 + "): packages=" + suid.packages); 7011 } 7012 } 7013 7014 // Check if we are renaming from an original package name. 7015 PackageSetting origPackage = null; 7016 String realName = null; 7017 if (pkg.mOriginalPackages != null) { 7018 // This package may need to be renamed to a previously 7019 // installed name. Let's check on that... 7020 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7021 if (pkg.mOriginalPackages.contains(renamed)) { 7022 // This package had originally been installed as the 7023 // original name, and we have already taken care of 7024 // transitioning to the new one. Just update the new 7025 // one to continue using the old name. 7026 realName = pkg.mRealPackage; 7027 if (!pkg.packageName.equals(renamed)) { 7028 // Callers into this function may have already taken 7029 // care of renaming the package; only do it here if 7030 // it is not already done. 7031 pkg.setPackageName(renamed); 7032 } 7033 7034 } else { 7035 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7036 if ((origPackage = mSettings.peekPackageLPr( 7037 pkg.mOriginalPackages.get(i))) != null) { 7038 // We do have the package already installed under its 7039 // original name... should we use it? 7040 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7041 // New package is not compatible with original. 7042 origPackage = null; 7043 continue; 7044 } else if (origPackage.sharedUser != null) { 7045 // Make sure uid is compatible between packages. 7046 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7047 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7048 + " to " + pkg.packageName + ": old uid " 7049 + origPackage.sharedUser.name 7050 + " differs from " + pkg.mSharedUserId); 7051 origPackage = null; 7052 continue; 7053 } 7054 } else { 7055 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7056 + pkg.packageName + " to old name " + origPackage.name); 7057 } 7058 break; 7059 } 7060 } 7061 } 7062 } 7063 7064 if (mTransferedPackages.contains(pkg.packageName)) { 7065 Slog.w(TAG, "Package " + pkg.packageName 7066 + " was transferred to another, but its .apk remains"); 7067 } 7068 7069 // Just create the setting, don't add it yet. For already existing packages 7070 // the PkgSetting exists already and doesn't have to be created. 7071 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7072 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7073 pkg.applicationInfo.primaryCpuAbi, 7074 pkg.applicationInfo.secondaryCpuAbi, 7075 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7076 user, false); 7077 if (pkgSetting == null) { 7078 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7079 "Creating application package " + pkg.packageName + " failed"); 7080 } 7081 7082 if (pkgSetting.origPackage != null) { 7083 // If we are first transitioning from an original package, 7084 // fix up the new package's name now. We need to do this after 7085 // looking up the package under its new name, so getPackageLP 7086 // can take care of fiddling things correctly. 7087 pkg.setPackageName(origPackage.name); 7088 7089 // File a report about this. 7090 String msg = "New package " + pkgSetting.realName 7091 + " renamed to replace old package " + pkgSetting.name; 7092 reportSettingsProblem(Log.WARN, msg); 7093 7094 // Make a note of it. 7095 mTransferedPackages.add(origPackage.name); 7096 7097 // No longer need to retain this. 7098 pkgSetting.origPackage = null; 7099 } 7100 7101 if (realName != null) { 7102 // Make a note of it. 7103 mTransferedPackages.add(pkg.packageName); 7104 } 7105 7106 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7107 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7108 } 7109 7110 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7111 // Check all shared libraries and map to their actual file path. 7112 // We only do this here for apps not on a system dir, because those 7113 // are the only ones that can fail an install due to this. We 7114 // will take care of the system apps by updating all of their 7115 // library paths after the scan is done. 7116 updateSharedLibrariesLPw(pkg, null); 7117 } 7118 7119 if (mFoundPolicyFile) { 7120 SELinuxMMAC.assignSeinfoValue(pkg); 7121 } 7122 7123 pkg.applicationInfo.uid = pkgSetting.appId; 7124 pkg.mExtras = pkgSetting; 7125 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7126 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7127 // We just determined the app is signed correctly, so bring 7128 // over the latest parsed certs. 7129 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7130 } else { 7131 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7132 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7133 "Package " + pkg.packageName + " upgrade keys do not match the " 7134 + "previously installed version"); 7135 } else { 7136 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7137 String msg = "System package " + pkg.packageName 7138 + " signature changed; retaining data."; 7139 reportSettingsProblem(Log.WARN, msg); 7140 } 7141 } 7142 } else { 7143 try { 7144 verifySignaturesLP(pkgSetting, pkg); 7145 // We just determined the app is signed correctly, so bring 7146 // over the latest parsed certs. 7147 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7148 } catch (PackageManagerException e) { 7149 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7150 throw e; 7151 } 7152 // The signature has changed, but this package is in the system 7153 // image... let's recover! 7154 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7155 // However... if this package is part of a shared user, but it 7156 // doesn't match the signature of the shared user, let's fail. 7157 // What this means is that you can't change the signatures 7158 // associated with an overall shared user, which doesn't seem all 7159 // that unreasonable. 7160 if (pkgSetting.sharedUser != null) { 7161 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7162 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7163 throw new PackageManagerException( 7164 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7165 "Signature mismatch for shared user: " 7166 + pkgSetting.sharedUser); 7167 } 7168 } 7169 // File a report about this. 7170 String msg = "System package " + pkg.packageName 7171 + " signature changed; retaining data."; 7172 reportSettingsProblem(Log.WARN, msg); 7173 } 7174 } 7175 // Verify that this new package doesn't have any content providers 7176 // that conflict with existing packages. Only do this if the 7177 // package isn't already installed, since we don't want to break 7178 // things that are installed. 7179 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7180 final int N = pkg.providers.size(); 7181 int i; 7182 for (i=0; i<N; i++) { 7183 PackageParser.Provider p = pkg.providers.get(i); 7184 if (p.info.authority != null) { 7185 String names[] = p.info.authority.split(";"); 7186 for (int j = 0; j < names.length; j++) { 7187 if (mProvidersByAuthority.containsKey(names[j])) { 7188 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7189 final String otherPackageName = 7190 ((other != null && other.getComponentName() != null) ? 7191 other.getComponentName().getPackageName() : "?"); 7192 throw new PackageManagerException( 7193 INSTALL_FAILED_CONFLICTING_PROVIDER, 7194 "Can't install because provider name " + names[j] 7195 + " (in package " + pkg.applicationInfo.packageName 7196 + ") is already used by " + otherPackageName); 7197 } 7198 } 7199 } 7200 } 7201 } 7202 7203 if (pkg.mAdoptPermissions != null) { 7204 // This package wants to adopt ownership of permissions from 7205 // another package. 7206 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7207 final String origName = pkg.mAdoptPermissions.get(i); 7208 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7209 if (orig != null) { 7210 if (verifyPackageUpdateLPr(orig, pkg)) { 7211 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7212 + pkg.packageName); 7213 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7214 } 7215 } 7216 } 7217 } 7218 } 7219 7220 final String pkgName = pkg.packageName; 7221 7222 final long scanFileTime = scanFile.lastModified(); 7223 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7224 pkg.applicationInfo.processName = fixProcessName( 7225 pkg.applicationInfo.packageName, 7226 pkg.applicationInfo.processName, 7227 pkg.applicationInfo.uid); 7228 7229 if (pkg != mPlatformPackage) { 7230 // This is a normal package, need to make its data directory. 7231 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7232 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7233 7234 boolean uidError = false; 7235 if (dataPath.exists()) { 7236 int currentUid = 0; 7237 try { 7238 StructStat stat = Os.stat(dataPath.getPath()); 7239 currentUid = stat.st_uid; 7240 } catch (ErrnoException e) { 7241 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7242 } 7243 7244 // If we have mismatched owners for the data path, we have a problem. 7245 if (currentUid != pkg.applicationInfo.uid) { 7246 boolean recovered = false; 7247 if (currentUid == 0) { 7248 // The directory somehow became owned by root. Wow. 7249 // This is probably because the system was stopped while 7250 // installd was in the middle of messing with its libs 7251 // directory. Ask installd to fix that. 7252 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7253 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7254 if (ret >= 0) { 7255 recovered = true; 7256 String msg = "Package " + pkg.packageName 7257 + " unexpectedly changed to uid 0; recovered to " + 7258 + pkg.applicationInfo.uid; 7259 reportSettingsProblem(Log.WARN, msg); 7260 } 7261 } 7262 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7263 || (scanFlags&SCAN_BOOTING) != 0)) { 7264 // If this is a system app, we can at least delete its 7265 // current data so the application will still work. 7266 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7267 if (ret >= 0) { 7268 // TODO: Kill the processes first 7269 // Old data gone! 7270 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7271 ? "System package " : "Third party package "; 7272 String msg = prefix + pkg.packageName 7273 + " has changed from uid: " 7274 + currentUid + " to " 7275 + pkg.applicationInfo.uid + "; old data erased"; 7276 reportSettingsProblem(Log.WARN, msg); 7277 recovered = true; 7278 } 7279 if (!recovered) { 7280 mHasSystemUidErrors = true; 7281 } 7282 } else if (!recovered) { 7283 // If we allow this install to proceed, we will be broken. 7284 // Abort, abort! 7285 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7286 "scanPackageLI"); 7287 } 7288 if (!recovered) { 7289 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7290 + pkg.applicationInfo.uid + "/fs_" 7291 + currentUid; 7292 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7293 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7294 String msg = "Package " + pkg.packageName 7295 + " has mismatched uid: " 7296 + currentUid + " on disk, " 7297 + pkg.applicationInfo.uid + " in settings"; 7298 // writer 7299 synchronized (mPackages) { 7300 mSettings.mReadMessages.append(msg); 7301 mSettings.mReadMessages.append('\n'); 7302 uidError = true; 7303 if (!pkgSetting.uidError) { 7304 reportSettingsProblem(Log.ERROR, msg); 7305 } 7306 } 7307 } 7308 } 7309 7310 // Ensure that directories are prepared 7311 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7312 pkg.applicationInfo.seinfo); 7313 7314 if (mShouldRestoreconData) { 7315 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7316 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7317 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7318 } 7319 } else { 7320 if (DEBUG_PACKAGE_SCANNING) { 7321 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7322 Log.v(TAG, "Want this data dir: " + dataPath); 7323 } 7324 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7325 pkg.applicationInfo.seinfo); 7326 } 7327 7328 // Get all of our default paths setup 7329 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7330 7331 pkgSetting.uidError = uidError; 7332 } 7333 7334 final String path = scanFile.getPath(); 7335 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7336 7337 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7338 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7339 7340 // Some system apps still use directory structure for native libraries 7341 // in which case we might end up not detecting abi solely based on apk 7342 // structure. Try to detect abi based on directory structure. 7343 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7344 pkg.applicationInfo.primaryCpuAbi == null) { 7345 setBundledAppAbisAndRoots(pkg, pkgSetting); 7346 setNativeLibraryPaths(pkg); 7347 } 7348 7349 } else { 7350 if ((scanFlags & SCAN_MOVE) != 0) { 7351 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7352 // but we already have this packages package info in the PackageSetting. We just 7353 // use that and derive the native library path based on the new codepath. 7354 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7355 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7356 } 7357 7358 // Set native library paths again. For moves, the path will be updated based on the 7359 // ABIs we've determined above. For non-moves, the path will be updated based on the 7360 // ABIs we determined during compilation, but the path will depend on the final 7361 // package path (after the rename away from the stage path). 7362 setNativeLibraryPaths(pkg); 7363 } 7364 7365 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7366 final int[] userIds = sUserManager.getUserIds(); 7367 synchronized (mInstallLock) { 7368 // Make sure all user data directories are ready to roll; we're okay 7369 // if they already exist 7370 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7371 for (int userId : userIds) { 7372 if (userId != UserHandle.USER_SYSTEM) { 7373 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7374 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7375 pkg.applicationInfo.seinfo); 7376 } 7377 } 7378 } 7379 7380 // Create a native library symlink only if we have native libraries 7381 // and if the native libraries are 32 bit libraries. We do not provide 7382 // this symlink for 64 bit libraries. 7383 if (pkg.applicationInfo.primaryCpuAbi != null && 7384 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7386 try { 7387 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7388 for (int userId : userIds) { 7389 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7390 nativeLibPath, userId) < 0) { 7391 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7392 "Failed linking native library dir (user=" + userId + ")"); 7393 } 7394 } 7395 } finally { 7396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7397 } 7398 } 7399 } 7400 7401 // This is a special case for the "system" package, where the ABI is 7402 // dictated by the zygote configuration (and init.rc). We should keep track 7403 // of this ABI so that we can deal with "normal" applications that run under 7404 // the same UID correctly. 7405 if (mPlatformPackage == pkg) { 7406 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7407 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7408 } 7409 7410 // If there's a mismatch between the abi-override in the package setting 7411 // and the abiOverride specified for the install. Warn about this because we 7412 // would've already compiled the app without taking the package setting into 7413 // account. 7414 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7415 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7416 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7417 " for package " + pkg.packageName); 7418 } 7419 } 7420 7421 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7422 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7423 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7424 7425 // Copy the derived override back to the parsed package, so that we can 7426 // update the package settings accordingly. 7427 pkg.cpuAbiOverride = cpuAbiOverride; 7428 7429 if (DEBUG_ABI_SELECTION) { 7430 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7431 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7432 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7433 } 7434 7435 // Push the derived path down into PackageSettings so we know what to 7436 // clean up at uninstall time. 7437 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7438 7439 if (DEBUG_ABI_SELECTION) { 7440 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7441 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7442 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7443 } 7444 7445 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7446 // We don't do this here during boot because we can do it all 7447 // at once after scanning all existing packages. 7448 // 7449 // We also do this *before* we perform dexopt on this package, so that 7450 // we can avoid redundant dexopts, and also to make sure we've got the 7451 // code and package path correct. 7452 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7453 pkg, true /* boot complete */); 7454 } 7455 7456 if (mFactoryTest && pkg.requestedPermissions.contains( 7457 android.Manifest.permission.FACTORY_TEST)) { 7458 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7459 } 7460 7461 ArrayList<PackageParser.Package> clientLibPkgs = null; 7462 7463 // writer 7464 synchronized (mPackages) { 7465 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7466 // Only system apps can add new shared libraries. 7467 if (pkg.libraryNames != null) { 7468 for (int i=0; i<pkg.libraryNames.size(); i++) { 7469 String name = pkg.libraryNames.get(i); 7470 boolean allowed = false; 7471 if (pkg.isUpdatedSystemApp()) { 7472 // New library entries can only be added through the 7473 // system image. This is important to get rid of a lot 7474 // of nasty edge cases: for example if we allowed a non- 7475 // system update of the app to add a library, then uninstalling 7476 // the update would make the library go away, and assumptions 7477 // we made such as through app install filtering would now 7478 // have allowed apps on the device which aren't compatible 7479 // with it. Better to just have the restriction here, be 7480 // conservative, and create many fewer cases that can negatively 7481 // impact the user experience. 7482 final PackageSetting sysPs = mSettings 7483 .getDisabledSystemPkgLPr(pkg.packageName); 7484 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7485 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7486 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7487 allowed = true; 7488 break; 7489 } 7490 } 7491 } 7492 } else { 7493 allowed = true; 7494 } 7495 if (allowed) { 7496 if (!mSharedLibraries.containsKey(name)) { 7497 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7498 } else if (!name.equals(pkg.packageName)) { 7499 Slog.w(TAG, "Package " + pkg.packageName + " library " 7500 + name + " already exists; skipping"); 7501 } 7502 } else { 7503 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7504 + name + " that is not declared on system image; skipping"); 7505 } 7506 } 7507 if ((scanFlags & SCAN_BOOTING) == 0) { 7508 // If we are not booting, we need to update any applications 7509 // that are clients of our shared library. If we are booting, 7510 // this will all be done once the scan is complete. 7511 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7512 } 7513 } 7514 } 7515 } 7516 7517 // Request the ActivityManager to kill the process(only for existing packages) 7518 // so that we do not end up in a confused state while the user is still using the older 7519 // version of the application while the new one gets installed. 7520 if ((scanFlags & SCAN_REPLACING) != 0) { 7521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7522 7523 killApplication(pkg.applicationInfo.packageName, 7524 pkg.applicationInfo.uid, "replace pkg"); 7525 7526 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7527 } 7528 7529 // Also need to kill any apps that are dependent on the library. 7530 if (clientLibPkgs != null) { 7531 for (int i=0; i<clientLibPkgs.size(); i++) { 7532 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7533 killApplication(clientPkg.applicationInfo.packageName, 7534 clientPkg.applicationInfo.uid, "update lib"); 7535 } 7536 } 7537 7538 // Make sure we're not adding any bogus keyset info 7539 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7540 ksms.assertScannedPackageValid(pkg); 7541 7542 // writer 7543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7544 7545 boolean createIdmapFailed = false; 7546 synchronized (mPackages) { 7547 // We don't expect installation to fail beyond this point 7548 7549 // Add the new setting to mSettings 7550 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7551 // Add the new setting to mPackages 7552 mPackages.put(pkg.applicationInfo.packageName, pkg); 7553 // Make sure we don't accidentally delete its data. 7554 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7555 while (iter.hasNext()) { 7556 PackageCleanItem item = iter.next(); 7557 if (pkgName.equals(item.packageName)) { 7558 iter.remove(); 7559 } 7560 } 7561 7562 // Take care of first install / last update times. 7563 if (currentTime != 0) { 7564 if (pkgSetting.firstInstallTime == 0) { 7565 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7566 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7567 pkgSetting.lastUpdateTime = currentTime; 7568 } 7569 } else if (pkgSetting.firstInstallTime == 0) { 7570 // We need *something*. Take time time stamp of the file. 7571 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7572 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7573 if (scanFileTime != pkgSetting.timeStamp) { 7574 // A package on the system image has changed; consider this 7575 // to be an update. 7576 pkgSetting.lastUpdateTime = scanFileTime; 7577 } 7578 } 7579 7580 // Add the package's KeySets to the global KeySetManagerService 7581 ksms.addScannedPackageLPw(pkg); 7582 7583 int N = pkg.providers.size(); 7584 StringBuilder r = null; 7585 int i; 7586 for (i=0; i<N; i++) { 7587 PackageParser.Provider p = pkg.providers.get(i); 7588 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7589 p.info.processName, pkg.applicationInfo.uid); 7590 mProviders.addProvider(p); 7591 p.syncable = p.info.isSyncable; 7592 if (p.info.authority != null) { 7593 String names[] = p.info.authority.split(";"); 7594 p.info.authority = null; 7595 for (int j = 0; j < names.length; j++) { 7596 if (j == 1 && p.syncable) { 7597 // We only want the first authority for a provider to possibly be 7598 // syncable, so if we already added this provider using a different 7599 // authority clear the syncable flag. We copy the provider before 7600 // changing it because the mProviders object contains a reference 7601 // to a provider that we don't want to change. 7602 // Only do this for the second authority since the resulting provider 7603 // object can be the same for all future authorities for this provider. 7604 p = new PackageParser.Provider(p); 7605 p.syncable = false; 7606 } 7607 if (!mProvidersByAuthority.containsKey(names[j])) { 7608 mProvidersByAuthority.put(names[j], p); 7609 if (p.info.authority == null) { 7610 p.info.authority = names[j]; 7611 } else { 7612 p.info.authority = p.info.authority + ";" + names[j]; 7613 } 7614 if (DEBUG_PACKAGE_SCANNING) { 7615 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7616 Log.d(TAG, "Registered content provider: " + names[j] 7617 + ", className = " + p.info.name + ", isSyncable = " 7618 + p.info.isSyncable); 7619 } 7620 } else { 7621 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7622 Slog.w(TAG, "Skipping provider name " + names[j] + 7623 " (in package " + pkg.applicationInfo.packageName + 7624 "): name already used by " 7625 + ((other != null && other.getComponentName() != null) 7626 ? other.getComponentName().getPackageName() : "?")); 7627 } 7628 } 7629 } 7630 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7631 if (r == null) { 7632 r = new StringBuilder(256); 7633 } else { 7634 r.append(' '); 7635 } 7636 r.append(p.info.name); 7637 } 7638 } 7639 if (r != null) { 7640 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7641 } 7642 7643 N = pkg.services.size(); 7644 r = null; 7645 for (i=0; i<N; i++) { 7646 PackageParser.Service s = pkg.services.get(i); 7647 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7648 s.info.processName, pkg.applicationInfo.uid); 7649 mServices.addService(s); 7650 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7651 if (r == null) { 7652 r = new StringBuilder(256); 7653 } else { 7654 r.append(' '); 7655 } 7656 r.append(s.info.name); 7657 } 7658 } 7659 if (r != null) { 7660 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7661 } 7662 7663 N = pkg.receivers.size(); 7664 r = null; 7665 for (i=0; i<N; i++) { 7666 PackageParser.Activity a = pkg.receivers.get(i); 7667 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7668 a.info.processName, pkg.applicationInfo.uid); 7669 mReceivers.addActivity(a, "receiver"); 7670 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7671 if (r == null) { 7672 r = new StringBuilder(256); 7673 } else { 7674 r.append(' '); 7675 } 7676 r.append(a.info.name); 7677 } 7678 } 7679 if (r != null) { 7680 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7681 } 7682 7683 N = pkg.activities.size(); 7684 r = null; 7685 for (i=0; i<N; i++) { 7686 PackageParser.Activity a = pkg.activities.get(i); 7687 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7688 a.info.processName, pkg.applicationInfo.uid); 7689 mActivities.addActivity(a, "activity"); 7690 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7691 if (r == null) { 7692 r = new StringBuilder(256); 7693 } else { 7694 r.append(' '); 7695 } 7696 r.append(a.info.name); 7697 } 7698 } 7699 if (r != null) { 7700 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7701 } 7702 7703 N = pkg.permissionGroups.size(); 7704 r = null; 7705 for (i=0; i<N; i++) { 7706 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7707 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7708 if (cur == null) { 7709 mPermissionGroups.put(pg.info.name, pg); 7710 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7711 if (r == null) { 7712 r = new StringBuilder(256); 7713 } else { 7714 r.append(' '); 7715 } 7716 r.append(pg.info.name); 7717 } 7718 } else { 7719 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7720 + pg.info.packageName + " ignored: original from " 7721 + cur.info.packageName); 7722 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7723 if (r == null) { 7724 r = new StringBuilder(256); 7725 } else { 7726 r.append(' '); 7727 } 7728 r.append("DUP:"); 7729 r.append(pg.info.name); 7730 } 7731 } 7732 } 7733 if (r != null) { 7734 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7735 } 7736 7737 N = pkg.permissions.size(); 7738 r = null; 7739 for (i=0; i<N; i++) { 7740 PackageParser.Permission p = pkg.permissions.get(i); 7741 7742 // Assume by default that we did not install this permission into the system. 7743 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7744 7745 // Now that permission groups have a special meaning, we ignore permission 7746 // groups for legacy apps to prevent unexpected behavior. In particular, 7747 // permissions for one app being granted to someone just becuase they happen 7748 // to be in a group defined by another app (before this had no implications). 7749 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7750 p.group = mPermissionGroups.get(p.info.group); 7751 // Warn for a permission in an unknown group. 7752 if (p.info.group != null && p.group == null) { 7753 Slog.w(TAG, "Permission " + p.info.name + " from package " 7754 + p.info.packageName + " in an unknown group " + p.info.group); 7755 } 7756 } 7757 7758 ArrayMap<String, BasePermission> permissionMap = 7759 p.tree ? mSettings.mPermissionTrees 7760 : mSettings.mPermissions; 7761 BasePermission bp = permissionMap.get(p.info.name); 7762 7763 // Allow system apps to redefine non-system permissions 7764 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7765 final boolean currentOwnerIsSystem = (bp.perm != null 7766 && isSystemApp(bp.perm.owner)); 7767 if (isSystemApp(p.owner)) { 7768 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7769 // It's a built-in permission and no owner, take ownership now 7770 bp.packageSetting = pkgSetting; 7771 bp.perm = p; 7772 bp.uid = pkg.applicationInfo.uid; 7773 bp.sourcePackage = p.info.packageName; 7774 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7775 } else if (!currentOwnerIsSystem) { 7776 String msg = "New decl " + p.owner + " of permission " 7777 + p.info.name + " is system; overriding " + bp.sourcePackage; 7778 reportSettingsProblem(Log.WARN, msg); 7779 bp = null; 7780 } 7781 } 7782 } 7783 7784 if (bp == null) { 7785 bp = new BasePermission(p.info.name, p.info.packageName, 7786 BasePermission.TYPE_NORMAL); 7787 permissionMap.put(p.info.name, bp); 7788 } 7789 7790 if (bp.perm == null) { 7791 if (bp.sourcePackage == null 7792 || bp.sourcePackage.equals(p.info.packageName)) { 7793 BasePermission tree = findPermissionTreeLP(p.info.name); 7794 if (tree == null 7795 || tree.sourcePackage.equals(p.info.packageName)) { 7796 bp.packageSetting = pkgSetting; 7797 bp.perm = p; 7798 bp.uid = pkg.applicationInfo.uid; 7799 bp.sourcePackage = p.info.packageName; 7800 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7802 if (r == null) { 7803 r = new StringBuilder(256); 7804 } else { 7805 r.append(' '); 7806 } 7807 r.append(p.info.name); 7808 } 7809 } else { 7810 Slog.w(TAG, "Permission " + p.info.name + " from package " 7811 + p.info.packageName + " ignored: base tree " 7812 + tree.name + " is from package " 7813 + tree.sourcePackage); 7814 } 7815 } else { 7816 Slog.w(TAG, "Permission " + p.info.name + " from package " 7817 + p.info.packageName + " ignored: original from " 7818 + bp.sourcePackage); 7819 } 7820 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7821 if (r == null) { 7822 r = new StringBuilder(256); 7823 } else { 7824 r.append(' '); 7825 } 7826 r.append("DUP:"); 7827 r.append(p.info.name); 7828 } 7829 if (bp.perm == p) { 7830 bp.protectionLevel = p.info.protectionLevel; 7831 } 7832 } 7833 7834 if (r != null) { 7835 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7836 } 7837 7838 N = pkg.instrumentation.size(); 7839 r = null; 7840 for (i=0; i<N; i++) { 7841 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7842 a.info.packageName = pkg.applicationInfo.packageName; 7843 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7844 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7845 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7846 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7847 a.info.dataDir = pkg.applicationInfo.dataDir; 7848 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7849 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7850 7851 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7852 // need other information about the application, like the ABI and what not ? 7853 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7854 mInstrumentation.put(a.getComponentName(), a); 7855 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7856 if (r == null) { 7857 r = new StringBuilder(256); 7858 } else { 7859 r.append(' '); 7860 } 7861 r.append(a.info.name); 7862 } 7863 } 7864 if (r != null) { 7865 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7866 } 7867 7868 if (pkg.protectedBroadcasts != null) { 7869 N = pkg.protectedBroadcasts.size(); 7870 for (i=0; i<N; i++) { 7871 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7872 } 7873 } 7874 7875 pkgSetting.setTimeStamp(scanFileTime); 7876 7877 // Create idmap files for pairs of (packages, overlay packages). 7878 // Note: "android", ie framework-res.apk, is handled by native layers. 7879 if (pkg.mOverlayTarget != null) { 7880 // This is an overlay package. 7881 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7882 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7883 mOverlays.put(pkg.mOverlayTarget, 7884 new ArrayMap<String, PackageParser.Package>()); 7885 } 7886 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7887 map.put(pkg.packageName, pkg); 7888 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7889 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7890 createIdmapFailed = true; 7891 } 7892 } 7893 } else if (mOverlays.containsKey(pkg.packageName) && 7894 !pkg.packageName.equals("android")) { 7895 // This is a regular package, with one or more known overlay packages. 7896 createIdmapsForPackageLI(pkg); 7897 } 7898 } 7899 7900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7901 7902 if (createIdmapFailed) { 7903 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7904 "scanPackageLI failed to createIdmap"); 7905 } 7906 return pkg; 7907 } 7908 7909 /** 7910 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7911 * is derived purely on the basis of the contents of {@code scanFile} and 7912 * {@code cpuAbiOverride}. 7913 * 7914 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7915 */ 7916 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7917 String cpuAbiOverride, boolean extractLibs) 7918 throws PackageManagerException { 7919 // TODO: We can probably be smarter about this stuff. For installed apps, 7920 // we can calculate this information at install time once and for all. For 7921 // system apps, we can probably assume that this information doesn't change 7922 // after the first boot scan. As things stand, we do lots of unnecessary work. 7923 7924 // Give ourselves some initial paths; we'll come back for another 7925 // pass once we've determined ABI below. 7926 setNativeLibraryPaths(pkg); 7927 7928 // We would never need to extract libs for forward-locked and external packages, 7929 // since the container service will do it for us. We shouldn't attempt to 7930 // extract libs from system app when it was not updated. 7931 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7932 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7933 extractLibs = false; 7934 } 7935 7936 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7937 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7938 7939 NativeLibraryHelper.Handle handle = null; 7940 try { 7941 handle = NativeLibraryHelper.Handle.create(pkg); 7942 // TODO(multiArch): This can be null for apps that didn't go through the 7943 // usual installation process. We can calculate it again, like we 7944 // do during install time. 7945 // 7946 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7947 // unnecessary. 7948 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7949 7950 // Null out the abis so that they can be recalculated. 7951 pkg.applicationInfo.primaryCpuAbi = null; 7952 pkg.applicationInfo.secondaryCpuAbi = null; 7953 if (isMultiArch(pkg.applicationInfo)) { 7954 // Warn if we've set an abiOverride for multi-lib packages.. 7955 // By definition, we need to copy both 32 and 64 bit libraries for 7956 // such packages. 7957 if (pkg.cpuAbiOverride != null 7958 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7959 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7960 } 7961 7962 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7963 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7964 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7965 if (extractLibs) { 7966 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7967 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7968 useIsaSpecificSubdirs); 7969 } else { 7970 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7971 } 7972 } 7973 7974 maybeThrowExceptionForMultiArchCopy( 7975 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7976 7977 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7978 if (extractLibs) { 7979 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7980 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7981 useIsaSpecificSubdirs); 7982 } else { 7983 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7984 } 7985 } 7986 7987 maybeThrowExceptionForMultiArchCopy( 7988 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7989 7990 if (abi64 >= 0) { 7991 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7992 } 7993 7994 if (abi32 >= 0) { 7995 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7996 if (abi64 >= 0) { 7997 pkg.applicationInfo.secondaryCpuAbi = abi; 7998 } else { 7999 pkg.applicationInfo.primaryCpuAbi = abi; 8000 } 8001 } 8002 } else { 8003 String[] abiList = (cpuAbiOverride != null) ? 8004 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8005 8006 // Enable gross and lame hacks for apps that are built with old 8007 // SDK tools. We must scan their APKs for renderscript bitcode and 8008 // not launch them if it's present. Don't bother checking on devices 8009 // that don't have 64 bit support. 8010 boolean needsRenderScriptOverride = false; 8011 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8012 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8013 abiList = Build.SUPPORTED_32_BIT_ABIS; 8014 needsRenderScriptOverride = true; 8015 } 8016 8017 final int copyRet; 8018 if (extractLibs) { 8019 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8020 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8021 } else { 8022 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8023 } 8024 8025 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8026 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8027 "Error unpackaging native libs for app, errorCode=" + copyRet); 8028 } 8029 8030 if (copyRet >= 0) { 8031 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8032 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8033 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8034 } else if (needsRenderScriptOverride) { 8035 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8036 } 8037 } 8038 } catch (IOException ioe) { 8039 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8040 } finally { 8041 IoUtils.closeQuietly(handle); 8042 } 8043 8044 // Now that we've calculated the ABIs and determined if it's an internal app, 8045 // we will go ahead and populate the nativeLibraryPath. 8046 setNativeLibraryPaths(pkg); 8047 } 8048 8049 /** 8050 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8051 * i.e, so that all packages can be run inside a single process if required. 8052 * 8053 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8054 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8055 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8056 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8057 * updating a package that belongs to a shared user. 8058 * 8059 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8060 * adds unnecessary complexity. 8061 */ 8062 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8063 PackageParser.Package scannedPackage, boolean bootComplete) { 8064 String requiredInstructionSet = null; 8065 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8066 requiredInstructionSet = VMRuntime.getInstructionSet( 8067 scannedPackage.applicationInfo.primaryCpuAbi); 8068 } 8069 8070 PackageSetting requirer = null; 8071 for (PackageSetting ps : packagesForUser) { 8072 // If packagesForUser contains scannedPackage, we skip it. This will happen 8073 // when scannedPackage is an update of an existing package. Without this check, 8074 // we will never be able to change the ABI of any package belonging to a shared 8075 // user, even if it's compatible with other packages. 8076 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8077 if (ps.primaryCpuAbiString == null) { 8078 continue; 8079 } 8080 8081 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8082 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8083 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8084 // this but there's not much we can do. 8085 String errorMessage = "Instruction set mismatch, " 8086 + ((requirer == null) ? "[caller]" : requirer) 8087 + " requires " + requiredInstructionSet + " whereas " + ps 8088 + " requires " + instructionSet; 8089 Slog.w(TAG, errorMessage); 8090 } 8091 8092 if (requiredInstructionSet == null) { 8093 requiredInstructionSet = instructionSet; 8094 requirer = ps; 8095 } 8096 } 8097 } 8098 8099 if (requiredInstructionSet != null) { 8100 String adjustedAbi; 8101 if (requirer != null) { 8102 // requirer != null implies that either scannedPackage was null or that scannedPackage 8103 // did not require an ABI, in which case we have to adjust scannedPackage to match 8104 // the ABI of the set (which is the same as requirer's ABI) 8105 adjustedAbi = requirer.primaryCpuAbiString; 8106 if (scannedPackage != null) { 8107 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8108 } 8109 } else { 8110 // requirer == null implies that we're updating all ABIs in the set to 8111 // match scannedPackage. 8112 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8113 } 8114 8115 for (PackageSetting ps : packagesForUser) { 8116 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8117 if (ps.primaryCpuAbiString != null) { 8118 continue; 8119 } 8120 8121 ps.primaryCpuAbiString = adjustedAbi; 8122 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8123 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8124 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8125 mInstaller.rmdex(ps.codePathString, 8126 getDexCodeInstructionSet(getPreferredInstructionSet())); 8127 } 8128 } 8129 } 8130 } 8131 } 8132 8133 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8134 synchronized (mPackages) { 8135 mResolverReplaced = true; 8136 // Set up information for custom user intent resolution activity. 8137 mResolveActivity.applicationInfo = pkg.applicationInfo; 8138 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8139 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8140 mResolveActivity.processName = pkg.applicationInfo.packageName; 8141 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8142 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8143 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8144 mResolveActivity.theme = 0; 8145 mResolveActivity.exported = true; 8146 mResolveActivity.enabled = true; 8147 mResolveInfo.activityInfo = mResolveActivity; 8148 mResolveInfo.priority = 0; 8149 mResolveInfo.preferredOrder = 0; 8150 mResolveInfo.match = 0; 8151 mResolveComponentName = mCustomResolverComponentName; 8152 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8153 mResolveComponentName); 8154 } 8155 } 8156 8157 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8158 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8159 8160 // Set up information for ephemeral installer activity 8161 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8162 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8163 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8164 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8165 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8166 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8167 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8168 mEphemeralInstallerActivity.theme = 0; 8169 mEphemeralInstallerActivity.exported = true; 8170 mEphemeralInstallerActivity.enabled = true; 8171 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8172 mEphemeralInstallerInfo.priority = 0; 8173 mEphemeralInstallerInfo.preferredOrder = 0; 8174 mEphemeralInstallerInfo.match = 0; 8175 8176 if (DEBUG_EPHEMERAL) { 8177 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8178 } 8179 } 8180 8181 private static String calculateBundledApkRoot(final String codePathString) { 8182 final File codePath = new File(codePathString); 8183 final File codeRoot; 8184 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8185 codeRoot = Environment.getRootDirectory(); 8186 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8187 codeRoot = Environment.getOemDirectory(); 8188 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8189 codeRoot = Environment.getVendorDirectory(); 8190 } else { 8191 // Unrecognized code path; take its top real segment as the apk root: 8192 // e.g. /something/app/blah.apk => /something 8193 try { 8194 File f = codePath.getCanonicalFile(); 8195 File parent = f.getParentFile(); // non-null because codePath is a file 8196 File tmp; 8197 while ((tmp = parent.getParentFile()) != null) { 8198 f = parent; 8199 parent = tmp; 8200 } 8201 codeRoot = f; 8202 Slog.w(TAG, "Unrecognized code path " 8203 + codePath + " - using " + codeRoot); 8204 } catch (IOException e) { 8205 // Can't canonicalize the code path -- shenanigans? 8206 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8207 return Environment.getRootDirectory().getPath(); 8208 } 8209 } 8210 return codeRoot.getPath(); 8211 } 8212 8213 /** 8214 * Derive and set the location of native libraries for the given package, 8215 * which varies depending on where and how the package was installed. 8216 */ 8217 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8218 final ApplicationInfo info = pkg.applicationInfo; 8219 final String codePath = pkg.codePath; 8220 final File codeFile = new File(codePath); 8221 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8222 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8223 8224 info.nativeLibraryRootDir = null; 8225 info.nativeLibraryRootRequiresIsa = false; 8226 info.nativeLibraryDir = null; 8227 info.secondaryNativeLibraryDir = null; 8228 8229 if (isApkFile(codeFile)) { 8230 // Monolithic install 8231 if (bundledApp) { 8232 // If "/system/lib64/apkname" exists, assume that is the per-package 8233 // native library directory to use; otherwise use "/system/lib/apkname". 8234 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8235 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8236 getPrimaryInstructionSet(info)); 8237 8238 // This is a bundled system app so choose the path based on the ABI. 8239 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8240 // is just the default path. 8241 final String apkName = deriveCodePathName(codePath); 8242 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8243 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8244 apkName).getAbsolutePath(); 8245 8246 if (info.secondaryCpuAbi != null) { 8247 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8248 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8249 secondaryLibDir, apkName).getAbsolutePath(); 8250 } 8251 } else if (asecApp) { 8252 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8253 .getAbsolutePath(); 8254 } else { 8255 final String apkName = deriveCodePathName(codePath); 8256 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8257 .getAbsolutePath(); 8258 } 8259 8260 info.nativeLibraryRootRequiresIsa = false; 8261 info.nativeLibraryDir = info.nativeLibraryRootDir; 8262 } else { 8263 // Cluster install 8264 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8265 info.nativeLibraryRootRequiresIsa = true; 8266 8267 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8268 getPrimaryInstructionSet(info)).getAbsolutePath(); 8269 8270 if (info.secondaryCpuAbi != null) { 8271 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8272 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8273 } 8274 } 8275 } 8276 8277 /** 8278 * Calculate the abis and roots for a bundled app. These can uniquely 8279 * be determined from the contents of the system partition, i.e whether 8280 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8281 * of this information, and instead assume that the system was built 8282 * sensibly. 8283 */ 8284 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8285 PackageSetting pkgSetting) { 8286 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8287 8288 // If "/system/lib64/apkname" exists, assume that is the per-package 8289 // native library directory to use; otherwise use "/system/lib/apkname". 8290 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8291 setBundledAppAbi(pkg, apkRoot, apkName); 8292 // pkgSetting might be null during rescan following uninstall of updates 8293 // to a bundled app, so accommodate that possibility. The settings in 8294 // that case will be established later from the parsed package. 8295 // 8296 // If the settings aren't null, sync them up with what we've just derived. 8297 // note that apkRoot isn't stored in the package settings. 8298 if (pkgSetting != null) { 8299 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8300 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8301 } 8302 } 8303 8304 /** 8305 * Deduces the ABI of a bundled app and sets the relevant fields on the 8306 * parsed pkg object. 8307 * 8308 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8309 * under which system libraries are installed. 8310 * @param apkName the name of the installed package. 8311 */ 8312 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8313 final File codeFile = new File(pkg.codePath); 8314 8315 final boolean has64BitLibs; 8316 final boolean has32BitLibs; 8317 if (isApkFile(codeFile)) { 8318 // Monolithic install 8319 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8320 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8321 } else { 8322 // Cluster install 8323 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8324 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8325 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8326 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8327 has64BitLibs = (new File(rootDir, isa)).exists(); 8328 } else { 8329 has64BitLibs = false; 8330 } 8331 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8332 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8333 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8334 has32BitLibs = (new File(rootDir, isa)).exists(); 8335 } else { 8336 has32BitLibs = false; 8337 } 8338 } 8339 8340 if (has64BitLibs && !has32BitLibs) { 8341 // The package has 64 bit libs, but not 32 bit libs. Its primary 8342 // ABI should be 64 bit. We can safely assume here that the bundled 8343 // native libraries correspond to the most preferred ABI in the list. 8344 8345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8346 pkg.applicationInfo.secondaryCpuAbi = null; 8347 } else if (has32BitLibs && !has64BitLibs) { 8348 // The package has 32 bit libs but not 64 bit libs. Its primary 8349 // ABI should be 32 bit. 8350 8351 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8352 pkg.applicationInfo.secondaryCpuAbi = null; 8353 } else if (has32BitLibs && has64BitLibs) { 8354 // The application has both 64 and 32 bit bundled libraries. We check 8355 // here that the app declares multiArch support, and warn if it doesn't. 8356 // 8357 // We will be lenient here and record both ABIs. The primary will be the 8358 // ABI that's higher on the list, i.e, a device that's configured to prefer 8359 // 64 bit apps will see a 64 bit primary ABI, 8360 8361 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8362 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8363 } 8364 8365 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8366 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8367 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8368 } else { 8369 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8370 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8371 } 8372 } else { 8373 pkg.applicationInfo.primaryCpuAbi = null; 8374 pkg.applicationInfo.secondaryCpuAbi = null; 8375 } 8376 } 8377 8378 private void killApplication(String pkgName, int appId, String reason) { 8379 // Request the ActivityManager to kill the process(only for existing packages) 8380 // so that we do not end up in a confused state while the user is still using the older 8381 // version of the application while the new one gets installed. 8382 IActivityManager am = ActivityManagerNative.getDefault(); 8383 if (am != null) { 8384 try { 8385 am.killApplicationWithAppId(pkgName, appId, reason); 8386 } catch (RemoteException e) { 8387 } 8388 } 8389 } 8390 8391 void removePackageLI(PackageSetting ps, boolean chatty) { 8392 if (DEBUG_INSTALL) { 8393 if (chatty) 8394 Log.d(TAG, "Removing package " + ps.name); 8395 } 8396 8397 // writer 8398 synchronized (mPackages) { 8399 mPackages.remove(ps.name); 8400 final PackageParser.Package pkg = ps.pkg; 8401 if (pkg != null) { 8402 cleanPackageDataStructuresLILPw(pkg, chatty); 8403 } 8404 } 8405 } 8406 8407 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8408 if (DEBUG_INSTALL) { 8409 if (chatty) 8410 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8411 } 8412 8413 // writer 8414 synchronized (mPackages) { 8415 mPackages.remove(pkg.applicationInfo.packageName); 8416 cleanPackageDataStructuresLILPw(pkg, chatty); 8417 } 8418 } 8419 8420 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8421 int N = pkg.providers.size(); 8422 StringBuilder r = null; 8423 int i; 8424 for (i=0; i<N; i++) { 8425 PackageParser.Provider p = pkg.providers.get(i); 8426 mProviders.removeProvider(p); 8427 if (p.info.authority == null) { 8428 8429 /* There was another ContentProvider with this authority when 8430 * this app was installed so this authority is null, 8431 * Ignore it as we don't have to unregister the provider. 8432 */ 8433 continue; 8434 } 8435 String names[] = p.info.authority.split(";"); 8436 for (int j = 0; j < names.length; j++) { 8437 if (mProvidersByAuthority.get(names[j]) == p) { 8438 mProvidersByAuthority.remove(names[j]); 8439 if (DEBUG_REMOVE) { 8440 if (chatty) 8441 Log.d(TAG, "Unregistered content provider: " + names[j] 8442 + ", className = " + p.info.name + ", isSyncable = " 8443 + p.info.isSyncable); 8444 } 8445 } 8446 } 8447 if (DEBUG_REMOVE && chatty) { 8448 if (r == null) { 8449 r = new StringBuilder(256); 8450 } else { 8451 r.append(' '); 8452 } 8453 r.append(p.info.name); 8454 } 8455 } 8456 if (r != null) { 8457 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8458 } 8459 8460 N = pkg.services.size(); 8461 r = null; 8462 for (i=0; i<N; i++) { 8463 PackageParser.Service s = pkg.services.get(i); 8464 mServices.removeService(s); 8465 if (chatty) { 8466 if (r == null) { 8467 r = new StringBuilder(256); 8468 } else { 8469 r.append(' '); 8470 } 8471 r.append(s.info.name); 8472 } 8473 } 8474 if (r != null) { 8475 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8476 } 8477 8478 N = pkg.receivers.size(); 8479 r = null; 8480 for (i=0; i<N; i++) { 8481 PackageParser.Activity a = pkg.receivers.get(i); 8482 mReceivers.removeActivity(a, "receiver"); 8483 if (DEBUG_REMOVE && chatty) { 8484 if (r == null) { 8485 r = new StringBuilder(256); 8486 } else { 8487 r.append(' '); 8488 } 8489 r.append(a.info.name); 8490 } 8491 } 8492 if (r != null) { 8493 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8494 } 8495 8496 N = pkg.activities.size(); 8497 r = null; 8498 for (i=0; i<N; i++) { 8499 PackageParser.Activity a = pkg.activities.get(i); 8500 mActivities.removeActivity(a, "activity"); 8501 if (DEBUG_REMOVE && chatty) { 8502 if (r == null) { 8503 r = new StringBuilder(256); 8504 } else { 8505 r.append(' '); 8506 } 8507 r.append(a.info.name); 8508 } 8509 } 8510 if (r != null) { 8511 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8512 } 8513 8514 N = pkg.permissions.size(); 8515 r = null; 8516 for (i=0; i<N; i++) { 8517 PackageParser.Permission p = pkg.permissions.get(i); 8518 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8519 if (bp == null) { 8520 bp = mSettings.mPermissionTrees.get(p.info.name); 8521 } 8522 if (bp != null && bp.perm == p) { 8523 bp.perm = null; 8524 if (DEBUG_REMOVE && chatty) { 8525 if (r == null) { 8526 r = new StringBuilder(256); 8527 } else { 8528 r.append(' '); 8529 } 8530 r.append(p.info.name); 8531 } 8532 } 8533 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8534 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8535 if (appOpPkgs != null) { 8536 appOpPkgs.remove(pkg.packageName); 8537 } 8538 } 8539 } 8540 if (r != null) { 8541 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8542 } 8543 8544 N = pkg.requestedPermissions.size(); 8545 r = null; 8546 for (i=0; i<N; i++) { 8547 String perm = pkg.requestedPermissions.get(i); 8548 BasePermission bp = mSettings.mPermissions.get(perm); 8549 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8550 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8551 if (appOpPkgs != null) { 8552 appOpPkgs.remove(pkg.packageName); 8553 if (appOpPkgs.isEmpty()) { 8554 mAppOpPermissionPackages.remove(perm); 8555 } 8556 } 8557 } 8558 } 8559 if (r != null) { 8560 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8561 } 8562 8563 N = pkg.instrumentation.size(); 8564 r = null; 8565 for (i=0; i<N; i++) { 8566 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8567 mInstrumentation.remove(a.getComponentName()); 8568 if (DEBUG_REMOVE && chatty) { 8569 if (r == null) { 8570 r = new StringBuilder(256); 8571 } else { 8572 r.append(' '); 8573 } 8574 r.append(a.info.name); 8575 } 8576 } 8577 if (r != null) { 8578 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8579 } 8580 8581 r = null; 8582 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8583 // Only system apps can hold shared libraries. 8584 if (pkg.libraryNames != null) { 8585 for (i=0; i<pkg.libraryNames.size(); i++) { 8586 String name = pkg.libraryNames.get(i); 8587 SharedLibraryEntry cur = mSharedLibraries.get(name); 8588 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8589 mSharedLibraries.remove(name); 8590 if (DEBUG_REMOVE && chatty) { 8591 if (r == null) { 8592 r = new StringBuilder(256); 8593 } else { 8594 r.append(' '); 8595 } 8596 r.append(name); 8597 } 8598 } 8599 } 8600 } 8601 } 8602 if (r != null) { 8603 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8604 } 8605 } 8606 8607 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8608 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8609 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8610 return true; 8611 } 8612 } 8613 return false; 8614 } 8615 8616 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8617 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8618 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8619 8620 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8621 int flags) { 8622 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8623 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8624 } 8625 8626 private void updatePermissionsLPw(String changingPkg, 8627 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8628 // Make sure there are no dangling permission trees. 8629 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8630 while (it.hasNext()) { 8631 final BasePermission bp = it.next(); 8632 if (bp.packageSetting == null) { 8633 // We may not yet have parsed the package, so just see if 8634 // we still know about its settings. 8635 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8636 } 8637 if (bp.packageSetting == null) { 8638 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8639 + " from package " + bp.sourcePackage); 8640 it.remove(); 8641 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8642 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8643 Slog.i(TAG, "Removing old permission tree: " + bp.name 8644 + " from package " + bp.sourcePackage); 8645 flags |= UPDATE_PERMISSIONS_ALL; 8646 it.remove(); 8647 } 8648 } 8649 } 8650 8651 // Make sure all dynamic permissions have been assigned to a package, 8652 // and make sure there are no dangling permissions. 8653 it = mSettings.mPermissions.values().iterator(); 8654 while (it.hasNext()) { 8655 final BasePermission bp = it.next(); 8656 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8657 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8658 + bp.name + " pkg=" + bp.sourcePackage 8659 + " info=" + bp.pendingInfo); 8660 if (bp.packageSetting == null && bp.pendingInfo != null) { 8661 final BasePermission tree = findPermissionTreeLP(bp.name); 8662 if (tree != null && tree.perm != null) { 8663 bp.packageSetting = tree.packageSetting; 8664 bp.perm = new PackageParser.Permission(tree.perm.owner, 8665 new PermissionInfo(bp.pendingInfo)); 8666 bp.perm.info.packageName = tree.perm.info.packageName; 8667 bp.perm.info.name = bp.name; 8668 bp.uid = tree.uid; 8669 } 8670 } 8671 } 8672 if (bp.packageSetting == null) { 8673 // We may not yet have parsed the package, so just see if 8674 // we still know about its settings. 8675 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8676 } 8677 if (bp.packageSetting == null) { 8678 Slog.w(TAG, "Removing dangling permission: " + bp.name 8679 + " from package " + bp.sourcePackage); 8680 it.remove(); 8681 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8682 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8683 Slog.i(TAG, "Removing old permission: " + bp.name 8684 + " from package " + bp.sourcePackage); 8685 flags |= UPDATE_PERMISSIONS_ALL; 8686 it.remove(); 8687 } 8688 } 8689 } 8690 8691 // Now update the permissions for all packages, in particular 8692 // replace the granted permissions of the system packages. 8693 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8694 for (PackageParser.Package pkg : mPackages.values()) { 8695 if (pkg != pkgInfo) { 8696 // Only replace for packages on requested volume 8697 final String volumeUuid = getVolumeUuidForPackage(pkg); 8698 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8699 && Objects.equals(replaceVolumeUuid, volumeUuid); 8700 grantPermissionsLPw(pkg, replace, changingPkg); 8701 } 8702 } 8703 } 8704 8705 if (pkgInfo != null) { 8706 // Only replace for packages on requested volume 8707 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8708 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8709 && Objects.equals(replaceVolumeUuid, volumeUuid); 8710 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8711 } 8712 } 8713 8714 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8715 String packageOfInterest) { 8716 // IMPORTANT: There are two types of permissions: install and runtime. 8717 // Install time permissions are granted when the app is installed to 8718 // all device users and users added in the future. Runtime permissions 8719 // are granted at runtime explicitly to specific users. Normal and signature 8720 // protected permissions are install time permissions. Dangerous permissions 8721 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8722 // otherwise they are runtime permissions. This function does not manage 8723 // runtime permissions except for the case an app targeting Lollipop MR1 8724 // being upgraded to target a newer SDK, in which case dangerous permissions 8725 // are transformed from install time to runtime ones. 8726 8727 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8728 if (ps == null) { 8729 return; 8730 } 8731 8732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8733 8734 PermissionsState permissionsState = ps.getPermissionsState(); 8735 PermissionsState origPermissions = permissionsState; 8736 8737 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8738 8739 boolean runtimePermissionsRevoked = false; 8740 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8741 8742 boolean changedInstallPermission = false; 8743 8744 if (replace) { 8745 ps.installPermissionsFixed = false; 8746 if (!ps.isSharedUser()) { 8747 origPermissions = new PermissionsState(permissionsState); 8748 permissionsState.reset(); 8749 } else { 8750 // We need to know only about runtime permission changes since the 8751 // calling code always writes the install permissions state but 8752 // the runtime ones are written only if changed. The only cases of 8753 // changed runtime permissions here are promotion of an install to 8754 // runtime and revocation of a runtime from a shared user. 8755 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8756 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8757 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8758 runtimePermissionsRevoked = true; 8759 } 8760 } 8761 } 8762 8763 permissionsState.setGlobalGids(mGlobalGids); 8764 8765 final int N = pkg.requestedPermissions.size(); 8766 for (int i=0; i<N; i++) { 8767 final String name = pkg.requestedPermissions.get(i); 8768 final BasePermission bp = mSettings.mPermissions.get(name); 8769 8770 if (DEBUG_INSTALL) { 8771 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8772 } 8773 8774 if (bp == null || bp.packageSetting == null) { 8775 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8776 Slog.w(TAG, "Unknown permission " + name 8777 + " in package " + pkg.packageName); 8778 } 8779 continue; 8780 } 8781 8782 final String perm = bp.name; 8783 boolean allowedSig = false; 8784 int grant = GRANT_DENIED; 8785 8786 // Keep track of app op permissions. 8787 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8788 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8789 if (pkgs == null) { 8790 pkgs = new ArraySet<>(); 8791 mAppOpPermissionPackages.put(bp.name, pkgs); 8792 } 8793 pkgs.add(pkg.packageName); 8794 } 8795 8796 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8797 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8798 >= Build.VERSION_CODES.M; 8799 switch (level) { 8800 case PermissionInfo.PROTECTION_NORMAL: { 8801 // For all apps normal permissions are install time ones. 8802 grant = GRANT_INSTALL; 8803 } break; 8804 8805 case PermissionInfo.PROTECTION_DANGEROUS: { 8806 // If a permission review is required for legacy apps we represent 8807 // their permissions as always granted runtime ones since we need 8808 // to keep the review required permission flag per user while an 8809 // install permission's state is shared across all users. 8810 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8811 // For legacy apps dangerous permissions are install time ones. 8812 grant = GRANT_INSTALL; 8813 } else if (origPermissions.hasInstallPermission(bp.name)) { 8814 // For legacy apps that became modern, install becomes runtime. 8815 grant = GRANT_UPGRADE; 8816 } else if (mPromoteSystemApps 8817 && isSystemApp(ps) 8818 && mExistingSystemPackages.contains(ps.name)) { 8819 // For legacy system apps, install becomes runtime. 8820 // We cannot check hasInstallPermission() for system apps since those 8821 // permissions were granted implicitly and not persisted pre-M. 8822 grant = GRANT_UPGRADE; 8823 } else { 8824 // For modern apps keep runtime permissions unchanged. 8825 grant = GRANT_RUNTIME; 8826 } 8827 } break; 8828 8829 case PermissionInfo.PROTECTION_SIGNATURE: { 8830 // For all apps signature permissions are install time ones. 8831 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8832 if (allowedSig) { 8833 grant = GRANT_INSTALL; 8834 } 8835 } break; 8836 } 8837 8838 if (DEBUG_INSTALL) { 8839 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8840 } 8841 8842 if (grant != GRANT_DENIED) { 8843 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8844 // If this is an existing, non-system package, then 8845 // we can't add any new permissions to it. 8846 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8847 // Except... if this is a permission that was added 8848 // to the platform (note: need to only do this when 8849 // updating the platform). 8850 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8851 grant = GRANT_DENIED; 8852 } 8853 } 8854 } 8855 8856 switch (grant) { 8857 case GRANT_INSTALL: { 8858 // Revoke this as runtime permission to handle the case of 8859 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8860 for (int userId : UserManagerService.getInstance().getUserIds()) { 8861 if (origPermissions.getRuntimePermissionState( 8862 bp.name, userId) != null) { 8863 // Revoke the runtime permission and clear the flags. 8864 origPermissions.revokeRuntimePermission(bp, userId); 8865 origPermissions.updatePermissionFlags(bp, userId, 8866 PackageManager.MASK_PERMISSION_FLAGS, 0); 8867 // If we revoked a permission permission, we have to write. 8868 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8869 changedRuntimePermissionUserIds, userId); 8870 } 8871 } 8872 // Grant an install permission. 8873 if (permissionsState.grantInstallPermission(bp) != 8874 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8875 changedInstallPermission = true; 8876 } 8877 } break; 8878 8879 case GRANT_RUNTIME: { 8880 // Grant previously granted runtime permissions. 8881 for (int userId : UserManagerService.getInstance().getUserIds()) { 8882 PermissionState permissionState = origPermissions 8883 .getRuntimePermissionState(bp.name, userId); 8884 int flags = permissionState != null 8885 ? permissionState.getFlags() : 0; 8886 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8887 if (permissionsState.grantRuntimePermission(bp, userId) == 8888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8889 // If we cannot put the permission as it was, we have to write. 8890 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8891 changedRuntimePermissionUserIds, userId); 8892 } 8893 // If the app supports runtime permissions no need for a review. 8894 if (Build.PERMISSIONS_REVIEW_REQUIRED 8895 && appSupportsRuntimePermissions 8896 && (flags & PackageManager 8897 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8898 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8899 // Since we changed the flags, we have to write. 8900 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8901 changedRuntimePermissionUserIds, userId); 8902 } 8903 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8904 && !appSupportsRuntimePermissions) { 8905 // For legacy apps that need a permission review, every new 8906 // runtime permission is granted but it is pending a review. 8907 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8908 permissionsState.grantRuntimePermission(bp, userId); 8909 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8910 // We changed the permission and flags, hence have to write. 8911 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8912 changedRuntimePermissionUserIds, userId); 8913 } 8914 } 8915 // Propagate the permission flags. 8916 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8917 } 8918 } break; 8919 8920 case GRANT_UPGRADE: { 8921 // Grant runtime permissions for a previously held install permission. 8922 PermissionState permissionState = origPermissions 8923 .getInstallPermissionState(bp.name); 8924 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8925 8926 if (origPermissions.revokeInstallPermission(bp) 8927 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8928 // We will be transferring the permission flags, so clear them. 8929 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8930 PackageManager.MASK_PERMISSION_FLAGS, 0); 8931 changedInstallPermission = true; 8932 } 8933 8934 // If the permission is not to be promoted to runtime we ignore it and 8935 // also its other flags as they are not applicable to install permissions. 8936 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8937 for (int userId : currentUserIds) { 8938 if (permissionsState.grantRuntimePermission(bp, userId) != 8939 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8940 // Transfer the permission flags. 8941 permissionsState.updatePermissionFlags(bp, userId, 8942 flags, flags); 8943 // If we granted the permission, we have to write. 8944 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8945 changedRuntimePermissionUserIds, userId); 8946 } 8947 } 8948 } 8949 } break; 8950 8951 default: { 8952 if (packageOfInterest == null 8953 || packageOfInterest.equals(pkg.packageName)) { 8954 Slog.w(TAG, "Not granting permission " + perm 8955 + " to package " + pkg.packageName 8956 + " because it was previously installed without"); 8957 } 8958 } break; 8959 } 8960 } else { 8961 if (permissionsState.revokeInstallPermission(bp) != 8962 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8963 // Also drop the permission flags. 8964 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8965 PackageManager.MASK_PERMISSION_FLAGS, 0); 8966 changedInstallPermission = true; 8967 Slog.i(TAG, "Un-granting permission " + perm 8968 + " from package " + pkg.packageName 8969 + " (protectionLevel=" + bp.protectionLevel 8970 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8971 + ")"); 8972 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8973 // Don't print warning for app op permissions, since it is fine for them 8974 // not to be granted, there is a UI for the user to decide. 8975 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8976 Slog.w(TAG, "Not granting permission " + perm 8977 + " to package " + pkg.packageName 8978 + " (protectionLevel=" + bp.protectionLevel 8979 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8980 + ")"); 8981 } 8982 } 8983 } 8984 } 8985 8986 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8987 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8988 // This is the first that we have heard about this package, so the 8989 // permissions we have now selected are fixed until explicitly 8990 // changed. 8991 ps.installPermissionsFixed = true; 8992 } 8993 8994 // Persist the runtime permissions state for users with changes. If permissions 8995 // were revoked because no app in the shared user declares them we have to 8996 // write synchronously to avoid losing runtime permissions state. 8997 for (int userId : changedRuntimePermissionUserIds) { 8998 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8999 } 9000 9001 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9002 } 9003 9004 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9005 boolean allowed = false; 9006 final int NP = PackageParser.NEW_PERMISSIONS.length; 9007 for (int ip=0; ip<NP; ip++) { 9008 final PackageParser.NewPermissionInfo npi 9009 = PackageParser.NEW_PERMISSIONS[ip]; 9010 if (npi.name.equals(perm) 9011 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9012 allowed = true; 9013 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9014 + pkg.packageName); 9015 break; 9016 } 9017 } 9018 return allowed; 9019 } 9020 9021 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9022 BasePermission bp, PermissionsState origPermissions) { 9023 boolean allowed; 9024 allowed = (compareSignatures( 9025 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9026 == PackageManager.SIGNATURE_MATCH) 9027 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9028 == PackageManager.SIGNATURE_MATCH); 9029 if (!allowed && (bp.protectionLevel 9030 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9031 if (isSystemApp(pkg)) { 9032 // For updated system applications, a system permission 9033 // is granted only if it had been defined by the original application. 9034 if (pkg.isUpdatedSystemApp()) { 9035 final PackageSetting sysPs = mSettings 9036 .getDisabledSystemPkgLPr(pkg.packageName); 9037 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9038 // If the original was granted this permission, we take 9039 // that grant decision as read and propagate it to the 9040 // update. 9041 if (sysPs.isPrivileged()) { 9042 allowed = true; 9043 } 9044 } else { 9045 // The system apk may have been updated with an older 9046 // version of the one on the data partition, but which 9047 // granted a new system permission that it didn't have 9048 // before. In this case we do want to allow the app to 9049 // now get the new permission if the ancestral apk is 9050 // privileged to get it. 9051 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9052 for (int j=0; 9053 j<sysPs.pkg.requestedPermissions.size(); j++) { 9054 if (perm.equals( 9055 sysPs.pkg.requestedPermissions.get(j))) { 9056 allowed = true; 9057 break; 9058 } 9059 } 9060 } 9061 } 9062 } else { 9063 allowed = isPrivilegedApp(pkg); 9064 } 9065 } 9066 } 9067 if (!allowed) { 9068 if (!allowed && (bp.protectionLevel 9069 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9070 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9071 // If this was a previously normal/dangerous permission that got moved 9072 // to a system permission as part of the runtime permission redesign, then 9073 // we still want to blindly grant it to old apps. 9074 allowed = true; 9075 } 9076 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9077 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9078 // If this permission is to be granted to the system installer and 9079 // this app is an installer, then it gets the permission. 9080 allowed = true; 9081 } 9082 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9083 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9084 // If this permission is to be granted to the system verifier and 9085 // this app is a verifier, then it gets the permission. 9086 allowed = true; 9087 } 9088 if (!allowed && (bp.protectionLevel 9089 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9090 && isSystemApp(pkg)) { 9091 // Any pre-installed system app is allowed to get this permission. 9092 allowed = true; 9093 } 9094 if (!allowed && (bp.protectionLevel 9095 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9096 // For development permissions, a development permission 9097 // is granted only if it was already granted. 9098 allowed = origPermissions.hasInstallPermission(perm); 9099 } 9100 } 9101 return allowed; 9102 } 9103 9104 final class ActivityIntentResolver 9105 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9106 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9107 boolean defaultOnly, int userId) { 9108 if (!sUserManager.exists(userId)) return null; 9109 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9110 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9111 } 9112 9113 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9114 int userId) { 9115 if (!sUserManager.exists(userId)) return null; 9116 mFlags = flags; 9117 return super.queryIntent(intent, resolvedType, 9118 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9119 } 9120 9121 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9122 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9123 if (!sUserManager.exists(userId)) return null; 9124 if (packageActivities == null) { 9125 return null; 9126 } 9127 mFlags = flags; 9128 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9129 final int N = packageActivities.size(); 9130 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9131 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9132 9133 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9134 for (int i = 0; i < N; ++i) { 9135 intentFilters = packageActivities.get(i).intents; 9136 if (intentFilters != null && intentFilters.size() > 0) { 9137 PackageParser.ActivityIntentInfo[] array = 9138 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9139 intentFilters.toArray(array); 9140 listCut.add(array); 9141 } 9142 } 9143 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9144 } 9145 9146 public final void addActivity(PackageParser.Activity a, String type) { 9147 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9148 mActivities.put(a.getComponentName(), a); 9149 if (DEBUG_SHOW_INFO) 9150 Log.v( 9151 TAG, " " + type + " " + 9152 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9153 if (DEBUG_SHOW_INFO) 9154 Log.v(TAG, " Class=" + a.info.name); 9155 final int NI = a.intents.size(); 9156 for (int j=0; j<NI; j++) { 9157 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9158 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9159 intent.setPriority(0); 9160 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9161 + a.className + " with priority > 0, forcing to 0"); 9162 } 9163 if (DEBUG_SHOW_INFO) { 9164 Log.v(TAG, " IntentFilter:"); 9165 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9166 } 9167 if (!intent.debugCheck()) { 9168 Log.w(TAG, "==> For Activity " + a.info.name); 9169 } 9170 addFilter(intent); 9171 } 9172 } 9173 9174 public final void removeActivity(PackageParser.Activity a, String type) { 9175 mActivities.remove(a.getComponentName()); 9176 if (DEBUG_SHOW_INFO) { 9177 Log.v(TAG, " " + type + " " 9178 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9179 : a.info.name) + ":"); 9180 Log.v(TAG, " Class=" + a.info.name); 9181 } 9182 final int NI = a.intents.size(); 9183 for (int j=0; j<NI; j++) { 9184 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9185 if (DEBUG_SHOW_INFO) { 9186 Log.v(TAG, " IntentFilter:"); 9187 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9188 } 9189 removeFilter(intent); 9190 } 9191 } 9192 9193 @Override 9194 protected boolean allowFilterResult( 9195 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9196 ActivityInfo filterAi = filter.activity.info; 9197 for (int i=dest.size()-1; i>=0; i--) { 9198 ActivityInfo destAi = dest.get(i).activityInfo; 9199 if (destAi.name == filterAi.name 9200 && destAi.packageName == filterAi.packageName) { 9201 return false; 9202 } 9203 } 9204 return true; 9205 } 9206 9207 @Override 9208 protected ActivityIntentInfo[] newArray(int size) { 9209 return new ActivityIntentInfo[size]; 9210 } 9211 9212 @Override 9213 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9214 if (!sUserManager.exists(userId)) return true; 9215 PackageParser.Package p = filter.activity.owner; 9216 if (p != null) { 9217 PackageSetting ps = (PackageSetting)p.mExtras; 9218 if (ps != null) { 9219 // System apps are never considered stopped for purposes of 9220 // filtering, because there may be no way for the user to 9221 // actually re-launch them. 9222 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9223 && ps.getStopped(userId); 9224 } 9225 } 9226 return false; 9227 } 9228 9229 @Override 9230 protected boolean isPackageForFilter(String packageName, 9231 PackageParser.ActivityIntentInfo info) { 9232 return packageName.equals(info.activity.owner.packageName); 9233 } 9234 9235 @Override 9236 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9237 int match, int userId) { 9238 if (!sUserManager.exists(userId)) return null; 9239 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9240 return null; 9241 } 9242 final PackageParser.Activity activity = info.activity; 9243 if (mSafeMode && (activity.info.applicationInfo.flags 9244 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9245 return null; 9246 } 9247 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9248 if (ps == null) { 9249 return null; 9250 } 9251 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9252 ps.readUserState(userId), userId); 9253 if (ai == null) { 9254 return null; 9255 } 9256 final ResolveInfo res = new ResolveInfo(); 9257 res.activityInfo = ai; 9258 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9259 res.filter = info; 9260 } 9261 if (info != null) { 9262 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9263 } 9264 res.priority = info.getPriority(); 9265 res.preferredOrder = activity.owner.mPreferredOrder; 9266 //System.out.println("Result: " + res.activityInfo.className + 9267 // " = " + res.priority); 9268 res.match = match; 9269 res.isDefault = info.hasDefault; 9270 res.labelRes = info.labelRes; 9271 res.nonLocalizedLabel = info.nonLocalizedLabel; 9272 if (userNeedsBadging(userId)) { 9273 res.noResourceId = true; 9274 } else { 9275 res.icon = info.icon; 9276 } 9277 res.iconResourceId = info.icon; 9278 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9279 return res; 9280 } 9281 9282 @Override 9283 protected void sortResults(List<ResolveInfo> results) { 9284 Collections.sort(results, mResolvePrioritySorter); 9285 } 9286 9287 @Override 9288 protected void dumpFilter(PrintWriter out, String prefix, 9289 PackageParser.ActivityIntentInfo filter) { 9290 out.print(prefix); out.print( 9291 Integer.toHexString(System.identityHashCode(filter.activity))); 9292 out.print(' '); 9293 filter.activity.printComponentShortName(out); 9294 out.print(" filter "); 9295 out.println(Integer.toHexString(System.identityHashCode(filter))); 9296 } 9297 9298 @Override 9299 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9300 return filter.activity; 9301 } 9302 9303 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9304 PackageParser.Activity activity = (PackageParser.Activity)label; 9305 out.print(prefix); out.print( 9306 Integer.toHexString(System.identityHashCode(activity))); 9307 out.print(' '); 9308 activity.printComponentShortName(out); 9309 if (count > 1) { 9310 out.print(" ("); out.print(count); out.print(" filters)"); 9311 } 9312 out.println(); 9313 } 9314 9315// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9316// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9317// final List<ResolveInfo> retList = Lists.newArrayList(); 9318// while (i.hasNext()) { 9319// final ResolveInfo resolveInfo = i.next(); 9320// if (isEnabledLP(resolveInfo.activityInfo)) { 9321// retList.add(resolveInfo); 9322// } 9323// } 9324// return retList; 9325// } 9326 9327 // Keys are String (activity class name), values are Activity. 9328 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9329 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9330 private int mFlags; 9331 } 9332 9333 private final class ServiceIntentResolver 9334 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9335 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9336 boolean defaultOnly, int userId) { 9337 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9338 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9339 } 9340 9341 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9342 int userId) { 9343 if (!sUserManager.exists(userId)) return null; 9344 mFlags = flags; 9345 return super.queryIntent(intent, resolvedType, 9346 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9347 } 9348 9349 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9350 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9351 if (!sUserManager.exists(userId)) return null; 9352 if (packageServices == null) { 9353 return null; 9354 } 9355 mFlags = flags; 9356 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9357 final int N = packageServices.size(); 9358 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9359 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9360 9361 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9362 for (int i = 0; i < N; ++i) { 9363 intentFilters = packageServices.get(i).intents; 9364 if (intentFilters != null && intentFilters.size() > 0) { 9365 PackageParser.ServiceIntentInfo[] array = 9366 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9367 intentFilters.toArray(array); 9368 listCut.add(array); 9369 } 9370 } 9371 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9372 } 9373 9374 public final void addService(PackageParser.Service s) { 9375 mServices.put(s.getComponentName(), s); 9376 if (DEBUG_SHOW_INFO) { 9377 Log.v(TAG, " " 9378 + (s.info.nonLocalizedLabel != null 9379 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9380 Log.v(TAG, " Class=" + s.info.name); 9381 } 9382 final int NI = s.intents.size(); 9383 int j; 9384 for (j=0; j<NI; j++) { 9385 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9386 if (DEBUG_SHOW_INFO) { 9387 Log.v(TAG, " IntentFilter:"); 9388 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9389 } 9390 if (!intent.debugCheck()) { 9391 Log.w(TAG, "==> For Service " + s.info.name); 9392 } 9393 addFilter(intent); 9394 } 9395 } 9396 9397 public final void removeService(PackageParser.Service s) { 9398 mServices.remove(s.getComponentName()); 9399 if (DEBUG_SHOW_INFO) { 9400 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9401 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9402 Log.v(TAG, " Class=" + s.info.name); 9403 } 9404 final int NI = s.intents.size(); 9405 int j; 9406 for (j=0; j<NI; j++) { 9407 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9408 if (DEBUG_SHOW_INFO) { 9409 Log.v(TAG, " IntentFilter:"); 9410 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9411 } 9412 removeFilter(intent); 9413 } 9414 } 9415 9416 @Override 9417 protected boolean allowFilterResult( 9418 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9419 ServiceInfo filterSi = filter.service.info; 9420 for (int i=dest.size()-1; i>=0; i--) { 9421 ServiceInfo destAi = dest.get(i).serviceInfo; 9422 if (destAi.name == filterSi.name 9423 && destAi.packageName == filterSi.packageName) { 9424 return false; 9425 } 9426 } 9427 return true; 9428 } 9429 9430 @Override 9431 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9432 return new PackageParser.ServiceIntentInfo[size]; 9433 } 9434 9435 @Override 9436 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9437 if (!sUserManager.exists(userId)) return true; 9438 PackageParser.Package p = filter.service.owner; 9439 if (p != null) { 9440 PackageSetting ps = (PackageSetting)p.mExtras; 9441 if (ps != null) { 9442 // System apps are never considered stopped for purposes of 9443 // filtering, because there may be no way for the user to 9444 // actually re-launch them. 9445 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9446 && ps.getStopped(userId); 9447 } 9448 } 9449 return false; 9450 } 9451 9452 @Override 9453 protected boolean isPackageForFilter(String packageName, 9454 PackageParser.ServiceIntentInfo info) { 9455 return packageName.equals(info.service.owner.packageName); 9456 } 9457 9458 @Override 9459 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9460 int match, int userId) { 9461 if (!sUserManager.exists(userId)) return null; 9462 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9463 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9464 return null; 9465 } 9466 final PackageParser.Service service = info.service; 9467 if (mSafeMode && (service.info.applicationInfo.flags 9468 &ApplicationInfo.FLAG_SYSTEM) == 0) { 9469 return null; 9470 } 9471 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9472 if (ps == null) { 9473 return null; 9474 } 9475 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9476 ps.readUserState(userId), userId); 9477 if (si == null) { 9478 return null; 9479 } 9480 final ResolveInfo res = new ResolveInfo(); 9481 res.serviceInfo = si; 9482 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9483 res.filter = filter; 9484 } 9485 res.priority = info.getPriority(); 9486 res.preferredOrder = service.owner.mPreferredOrder; 9487 res.match = match; 9488 res.isDefault = info.hasDefault; 9489 res.labelRes = info.labelRes; 9490 res.nonLocalizedLabel = info.nonLocalizedLabel; 9491 res.icon = info.icon; 9492 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9493 return res; 9494 } 9495 9496 @Override 9497 protected void sortResults(List<ResolveInfo> results) { 9498 Collections.sort(results, mResolvePrioritySorter); 9499 } 9500 9501 @Override 9502 protected void dumpFilter(PrintWriter out, String prefix, 9503 PackageParser.ServiceIntentInfo filter) { 9504 out.print(prefix); out.print( 9505 Integer.toHexString(System.identityHashCode(filter.service))); 9506 out.print(' '); 9507 filter.service.printComponentShortName(out); 9508 out.print(" filter "); 9509 out.println(Integer.toHexString(System.identityHashCode(filter))); 9510 } 9511 9512 @Override 9513 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9514 return filter.service; 9515 } 9516 9517 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9518 PackageParser.Service service = (PackageParser.Service)label; 9519 out.print(prefix); out.print( 9520 Integer.toHexString(System.identityHashCode(service))); 9521 out.print(' '); 9522 service.printComponentShortName(out); 9523 if (count > 1) { 9524 out.print(" ("); out.print(count); out.print(" filters)"); 9525 } 9526 out.println(); 9527 } 9528 9529// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9530// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9531// final List<ResolveInfo> retList = Lists.newArrayList(); 9532// while (i.hasNext()) { 9533// final ResolveInfo resolveInfo = (ResolveInfo) i; 9534// if (isEnabledLP(resolveInfo.serviceInfo)) { 9535// retList.add(resolveInfo); 9536// } 9537// } 9538// return retList; 9539// } 9540 9541 // Keys are String (activity class name), values are Activity. 9542 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9543 = new ArrayMap<ComponentName, PackageParser.Service>(); 9544 private int mFlags; 9545 }; 9546 9547 private final class ProviderIntentResolver 9548 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9549 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9550 boolean defaultOnly, int userId) { 9551 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9552 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9553 } 9554 9555 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9556 int userId) { 9557 if (!sUserManager.exists(userId)) 9558 return null; 9559 mFlags = flags; 9560 return super.queryIntent(intent, resolvedType, 9561 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9562 } 9563 9564 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9565 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9566 if (!sUserManager.exists(userId)) 9567 return null; 9568 if (packageProviders == null) { 9569 return null; 9570 } 9571 mFlags = flags; 9572 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9573 final int N = packageProviders.size(); 9574 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9575 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9576 9577 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9578 for (int i = 0; i < N; ++i) { 9579 intentFilters = packageProviders.get(i).intents; 9580 if (intentFilters != null && intentFilters.size() > 0) { 9581 PackageParser.ProviderIntentInfo[] array = 9582 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9583 intentFilters.toArray(array); 9584 listCut.add(array); 9585 } 9586 } 9587 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9588 } 9589 9590 public final void addProvider(PackageParser.Provider p) { 9591 if (mProviders.containsKey(p.getComponentName())) { 9592 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9593 return; 9594 } 9595 9596 mProviders.put(p.getComponentName(), p); 9597 if (DEBUG_SHOW_INFO) { 9598 Log.v(TAG, " " 9599 + (p.info.nonLocalizedLabel != null 9600 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9601 Log.v(TAG, " Class=" + p.info.name); 9602 } 9603 final int NI = p.intents.size(); 9604 int j; 9605 for (j = 0; j < NI; j++) { 9606 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9607 if (DEBUG_SHOW_INFO) { 9608 Log.v(TAG, " IntentFilter:"); 9609 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9610 } 9611 if (!intent.debugCheck()) { 9612 Log.w(TAG, "==> For Provider " + p.info.name); 9613 } 9614 addFilter(intent); 9615 } 9616 } 9617 9618 public final void removeProvider(PackageParser.Provider p) { 9619 mProviders.remove(p.getComponentName()); 9620 if (DEBUG_SHOW_INFO) { 9621 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9622 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9623 Log.v(TAG, " Class=" + p.info.name); 9624 } 9625 final int NI = p.intents.size(); 9626 int j; 9627 for (j = 0; j < NI; j++) { 9628 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9629 if (DEBUG_SHOW_INFO) { 9630 Log.v(TAG, " IntentFilter:"); 9631 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9632 } 9633 removeFilter(intent); 9634 } 9635 } 9636 9637 @Override 9638 protected boolean allowFilterResult( 9639 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9640 ProviderInfo filterPi = filter.provider.info; 9641 for (int i = dest.size() - 1; i >= 0; i--) { 9642 ProviderInfo destPi = dest.get(i).providerInfo; 9643 if (destPi.name == filterPi.name 9644 && destPi.packageName == filterPi.packageName) { 9645 return false; 9646 } 9647 } 9648 return true; 9649 } 9650 9651 @Override 9652 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9653 return new PackageParser.ProviderIntentInfo[size]; 9654 } 9655 9656 @Override 9657 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9658 if (!sUserManager.exists(userId)) 9659 return true; 9660 PackageParser.Package p = filter.provider.owner; 9661 if (p != null) { 9662 PackageSetting ps = (PackageSetting) p.mExtras; 9663 if (ps != null) { 9664 // System apps are never considered stopped for purposes of 9665 // filtering, because there may be no way for the user to 9666 // actually re-launch them. 9667 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9668 && ps.getStopped(userId); 9669 } 9670 } 9671 return false; 9672 } 9673 9674 @Override 9675 protected boolean isPackageForFilter(String packageName, 9676 PackageParser.ProviderIntentInfo info) { 9677 return packageName.equals(info.provider.owner.packageName); 9678 } 9679 9680 @Override 9681 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9682 int match, int userId) { 9683 if (!sUserManager.exists(userId)) 9684 return null; 9685 final PackageParser.ProviderIntentInfo info = filter; 9686 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9687 return null; 9688 } 9689 final PackageParser.Provider provider = info.provider; 9690 if (mSafeMode && (provider.info.applicationInfo.flags 9691 & ApplicationInfo.FLAG_SYSTEM) == 0) { 9692 return null; 9693 } 9694 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9695 if (ps == null) { 9696 return null; 9697 } 9698 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9699 ps.readUserState(userId), userId); 9700 if (pi == null) { 9701 return null; 9702 } 9703 final ResolveInfo res = new ResolveInfo(); 9704 res.providerInfo = pi; 9705 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9706 res.filter = filter; 9707 } 9708 res.priority = info.getPriority(); 9709 res.preferredOrder = provider.owner.mPreferredOrder; 9710 res.match = match; 9711 res.isDefault = info.hasDefault; 9712 res.labelRes = info.labelRes; 9713 res.nonLocalizedLabel = info.nonLocalizedLabel; 9714 res.icon = info.icon; 9715 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9716 return res; 9717 } 9718 9719 @Override 9720 protected void sortResults(List<ResolveInfo> results) { 9721 Collections.sort(results, mResolvePrioritySorter); 9722 } 9723 9724 @Override 9725 protected void dumpFilter(PrintWriter out, String prefix, 9726 PackageParser.ProviderIntentInfo filter) { 9727 out.print(prefix); 9728 out.print( 9729 Integer.toHexString(System.identityHashCode(filter.provider))); 9730 out.print(' '); 9731 filter.provider.printComponentShortName(out); 9732 out.print(" filter "); 9733 out.println(Integer.toHexString(System.identityHashCode(filter))); 9734 } 9735 9736 @Override 9737 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9738 return filter.provider; 9739 } 9740 9741 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9742 PackageParser.Provider provider = (PackageParser.Provider)label; 9743 out.print(prefix); out.print( 9744 Integer.toHexString(System.identityHashCode(provider))); 9745 out.print(' '); 9746 provider.printComponentShortName(out); 9747 if (count > 1) { 9748 out.print(" ("); out.print(count); out.print(" filters)"); 9749 } 9750 out.println(); 9751 } 9752 9753 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9754 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9755 private int mFlags; 9756 } 9757 9758 private static final class EphemeralIntentResolver 9759 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9760 @Override 9761 protected EphemeralResolveIntentInfo[] newArray(int size) { 9762 return new EphemeralResolveIntentInfo[size]; 9763 } 9764 9765 @Override 9766 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9767 return true; 9768 } 9769 9770 @Override 9771 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9772 int userId) { 9773 if (!sUserManager.exists(userId)) { 9774 return null; 9775 } 9776 return info.getEphemeralResolveInfo(); 9777 } 9778 } 9779 9780 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9781 new Comparator<ResolveInfo>() { 9782 public int compare(ResolveInfo r1, ResolveInfo r2) { 9783 int v1 = r1.priority; 9784 int v2 = r2.priority; 9785 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9786 if (v1 != v2) { 9787 return (v1 > v2) ? -1 : 1; 9788 } 9789 v1 = r1.preferredOrder; 9790 v2 = r2.preferredOrder; 9791 if (v1 != v2) { 9792 return (v1 > v2) ? -1 : 1; 9793 } 9794 if (r1.isDefault != r2.isDefault) { 9795 return r1.isDefault ? -1 : 1; 9796 } 9797 v1 = r1.match; 9798 v2 = r2.match; 9799 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9800 if (v1 != v2) { 9801 return (v1 > v2) ? -1 : 1; 9802 } 9803 if (r1.system != r2.system) { 9804 return r1.system ? -1 : 1; 9805 } 9806 if (r1.activityInfo != null) { 9807 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9808 } 9809 if (r1.serviceInfo != null) { 9810 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9811 } 9812 if (r1.providerInfo != null) { 9813 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9814 } 9815 return 0; 9816 } 9817 }; 9818 9819 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9820 new Comparator<ProviderInfo>() { 9821 public int compare(ProviderInfo p1, ProviderInfo p2) { 9822 final int v1 = p1.initOrder; 9823 final int v2 = p2.initOrder; 9824 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9825 } 9826 }; 9827 9828 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9829 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9830 final int[] userIds) { 9831 mHandler.post(new Runnable() { 9832 @Override 9833 public void run() { 9834 try { 9835 final IActivityManager am = ActivityManagerNative.getDefault(); 9836 if (am == null) return; 9837 final int[] resolvedUserIds; 9838 if (userIds == null) { 9839 resolvedUserIds = am.getRunningUserIds(); 9840 } else { 9841 resolvedUserIds = userIds; 9842 } 9843 for (int id : resolvedUserIds) { 9844 final Intent intent = new Intent(action, 9845 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9846 if (extras != null) { 9847 intent.putExtras(extras); 9848 } 9849 if (targetPkg != null) { 9850 intent.setPackage(targetPkg); 9851 } 9852 // Modify the UID when posting to other users 9853 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9854 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9855 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9856 intent.putExtra(Intent.EXTRA_UID, uid); 9857 } 9858 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9859 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9860 if (DEBUG_BROADCASTS) { 9861 RuntimeException here = new RuntimeException("here"); 9862 here.fillInStackTrace(); 9863 Slog.d(TAG, "Sending to user " + id + ": " 9864 + intent.toShortString(false, true, false, false) 9865 + " " + intent.getExtras(), here); 9866 } 9867 am.broadcastIntent(null, intent, null, finishedReceiver, 9868 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9869 null, finishedReceiver != null, false, id); 9870 } 9871 } catch (RemoteException ex) { 9872 } 9873 } 9874 }); 9875 } 9876 9877 /** 9878 * Check if the external storage media is available. This is true if there 9879 * is a mounted external storage medium or if the external storage is 9880 * emulated. 9881 */ 9882 private boolean isExternalMediaAvailable() { 9883 return mMediaMounted || Environment.isExternalStorageEmulated(); 9884 } 9885 9886 @Override 9887 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9888 // writer 9889 synchronized (mPackages) { 9890 if (!isExternalMediaAvailable()) { 9891 // If the external storage is no longer mounted at this point, 9892 // the caller may not have been able to delete all of this 9893 // packages files and can not delete any more. Bail. 9894 return null; 9895 } 9896 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9897 if (lastPackage != null) { 9898 pkgs.remove(lastPackage); 9899 } 9900 if (pkgs.size() > 0) { 9901 return pkgs.get(0); 9902 } 9903 } 9904 return null; 9905 } 9906 9907 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9908 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9909 userId, andCode ? 1 : 0, packageName); 9910 if (mSystemReady) { 9911 msg.sendToTarget(); 9912 } else { 9913 if (mPostSystemReadyMessages == null) { 9914 mPostSystemReadyMessages = new ArrayList<>(); 9915 } 9916 mPostSystemReadyMessages.add(msg); 9917 } 9918 } 9919 9920 void startCleaningPackages() { 9921 // reader 9922 synchronized (mPackages) { 9923 if (!isExternalMediaAvailable()) { 9924 return; 9925 } 9926 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9927 return; 9928 } 9929 } 9930 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9931 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9932 IActivityManager am = ActivityManagerNative.getDefault(); 9933 if (am != null) { 9934 try { 9935 am.startService(null, intent, null, mContext.getOpPackageName(), 9936 UserHandle.USER_SYSTEM); 9937 } catch (RemoteException e) { 9938 } 9939 } 9940 } 9941 9942 @Override 9943 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9944 int installFlags, String installerPackageName, VerificationParams verificationParams, 9945 String packageAbiOverride) { 9946 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9947 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9948 } 9949 9950 @Override 9951 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9952 int installFlags, String installerPackageName, VerificationParams verificationParams, 9953 String packageAbiOverride, int userId) { 9954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9955 9956 final int callingUid = Binder.getCallingUid(); 9957 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9958 9959 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9960 try { 9961 if (observer != null) { 9962 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9963 } 9964 } catch (RemoteException re) { 9965 } 9966 return; 9967 } 9968 9969 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9970 installFlags |= PackageManager.INSTALL_FROM_ADB; 9971 9972 } else { 9973 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9974 // about installerPackageName. 9975 9976 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9977 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9978 } 9979 9980 UserHandle user; 9981 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9982 user = UserHandle.ALL; 9983 } else { 9984 user = new UserHandle(userId); 9985 } 9986 9987 // Only system components can circumvent runtime permissions when installing. 9988 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9989 && mContext.checkCallingOrSelfPermission(Manifest.permission 9990 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9991 throw new SecurityException("You need the " 9992 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9993 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9994 } 9995 9996 verificationParams.setInstallerUid(callingUid); 9997 9998 final File originFile = new File(originPath); 9999 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10000 10001 final Message msg = mHandler.obtainMessage(INIT_COPY); 10002 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 10003 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 10004 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10005 msg.obj = params; 10006 10007 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10008 System.identityHashCode(msg.obj)); 10009 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10010 System.identityHashCode(msg.obj)); 10011 10012 mHandler.sendMessage(msg); 10013 } 10014 10015 void installStage(String packageName, File stagedDir, String stagedCid, 10016 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10017 String installerPackageName, int installerUid, UserHandle user) { 10018 if (DEBUG_EPHEMERAL) { 10019 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10020 Slog.d(TAG, "Ephemeral install of " + packageName); 10021 } 10022 } 10023 final VerificationParams verifParams = new VerificationParams( 10024 null, sessionParams.originatingUri, sessionParams.referrerUri, 10025 sessionParams.originatingUid); 10026 verifParams.setInstallerUid(installerUid); 10027 10028 final OriginInfo origin; 10029 if (stagedDir != null) { 10030 origin = OriginInfo.fromStagedFile(stagedDir); 10031 } else { 10032 origin = OriginInfo.fromStagedContainer(stagedCid); 10033 } 10034 10035 final Message msg = mHandler.obtainMessage(INIT_COPY); 10036 final InstallParams params = new InstallParams(origin, null, observer, 10037 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10038 verifParams, user, sessionParams.abiOverride, 10039 sessionParams.grantedRuntimePermissions); 10040 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10041 msg.obj = params; 10042 10043 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10044 System.identityHashCode(msg.obj)); 10045 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10046 System.identityHashCode(msg.obj)); 10047 10048 mHandler.sendMessage(msg); 10049 } 10050 10051 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10052 Bundle extras = new Bundle(1); 10053 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10054 10055 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10056 packageName, extras, 0, null, null, new int[] {userId}); 10057 try { 10058 IActivityManager am = ActivityManagerNative.getDefault(); 10059 final boolean isSystem = 10060 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10061 if (isSystem && am.isUserRunning(userId, 0)) { 10062 // The just-installed/enabled app is bundled on the system, so presumed 10063 // to be able to run automatically without needing an explicit launch. 10064 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10065 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10066 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10067 .setPackage(packageName); 10068 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10069 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10070 } 10071 } catch (RemoteException e) { 10072 // shouldn't happen 10073 Slog.w(TAG, "Unable to bootstrap installed package", e); 10074 } 10075 } 10076 10077 @Override 10078 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10079 int userId) { 10080 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10081 PackageSetting pkgSetting; 10082 final int uid = Binder.getCallingUid(); 10083 enforceCrossUserPermission(uid, userId, true, true, 10084 "setApplicationHiddenSetting for user " + userId); 10085 10086 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10087 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10088 return false; 10089 } 10090 10091 long callingId = Binder.clearCallingIdentity(); 10092 try { 10093 boolean sendAdded = false; 10094 boolean sendRemoved = false; 10095 // writer 10096 synchronized (mPackages) { 10097 pkgSetting = mSettings.mPackages.get(packageName); 10098 if (pkgSetting == null) { 10099 return false; 10100 } 10101 if (pkgSetting.getHidden(userId) != hidden) { 10102 pkgSetting.setHidden(hidden, userId); 10103 mSettings.writePackageRestrictionsLPr(userId); 10104 if (hidden) { 10105 sendRemoved = true; 10106 } else { 10107 sendAdded = true; 10108 } 10109 } 10110 } 10111 if (sendAdded) { 10112 sendPackageAddedForUser(packageName, pkgSetting, userId); 10113 return true; 10114 } 10115 if (sendRemoved) { 10116 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10117 "hiding pkg"); 10118 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10119 return true; 10120 } 10121 } finally { 10122 Binder.restoreCallingIdentity(callingId); 10123 } 10124 return false; 10125 } 10126 10127 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10128 int userId) { 10129 final PackageRemovedInfo info = new PackageRemovedInfo(); 10130 info.removedPackage = packageName; 10131 info.removedUsers = new int[] {userId}; 10132 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10133 info.sendBroadcast(false, false, false); 10134 } 10135 10136 /** 10137 * Returns true if application is not found or there was an error. Otherwise it returns 10138 * the hidden state of the package for the given user. 10139 */ 10140 @Override 10141 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10142 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10143 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10144 false, "getApplicationHidden for user " + userId); 10145 PackageSetting pkgSetting; 10146 long callingId = Binder.clearCallingIdentity(); 10147 try { 10148 // writer 10149 synchronized (mPackages) { 10150 pkgSetting = mSettings.mPackages.get(packageName); 10151 if (pkgSetting == null) { 10152 return true; 10153 } 10154 return pkgSetting.getHidden(userId); 10155 } 10156 } finally { 10157 Binder.restoreCallingIdentity(callingId); 10158 } 10159 } 10160 10161 /** 10162 * @hide 10163 */ 10164 @Override 10165 public int installExistingPackageAsUser(String packageName, int userId) { 10166 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10167 null); 10168 PackageSetting pkgSetting; 10169 final int uid = Binder.getCallingUid(); 10170 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10171 + userId); 10172 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10173 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10174 } 10175 10176 long callingId = Binder.clearCallingIdentity(); 10177 try { 10178 boolean sendAdded = false; 10179 10180 // writer 10181 synchronized (mPackages) { 10182 pkgSetting = mSettings.mPackages.get(packageName); 10183 if (pkgSetting == null) { 10184 return PackageManager.INSTALL_FAILED_INVALID_URI; 10185 } 10186 if (!pkgSetting.getInstalled(userId)) { 10187 pkgSetting.setInstalled(true, userId); 10188 pkgSetting.setHidden(false, userId); 10189 mSettings.writePackageRestrictionsLPr(userId); 10190 sendAdded = true; 10191 } 10192 } 10193 10194 if (sendAdded) { 10195 sendPackageAddedForUser(packageName, pkgSetting, userId); 10196 } 10197 } finally { 10198 Binder.restoreCallingIdentity(callingId); 10199 } 10200 10201 return PackageManager.INSTALL_SUCCEEDED; 10202 } 10203 10204 boolean isUserRestricted(int userId, String restrictionKey) { 10205 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10206 if (restrictions.getBoolean(restrictionKey, false)) { 10207 Log.w(TAG, "User is restricted: " + restrictionKey); 10208 return true; 10209 } 10210 return false; 10211 } 10212 10213 @Override 10214 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10215 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10216 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10217 "setPackageSuspended for user " + userId); 10218 10219 long callingId = Binder.clearCallingIdentity(); 10220 try { 10221 synchronized (mPackages) { 10222 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10223 if (pkgSetting != null) { 10224 if (pkgSetting.getSuspended(userId) != suspended) { 10225 pkgSetting.setSuspended(suspended, userId); 10226 mSettings.writePackageRestrictionsLPr(userId); 10227 } 10228 10229 // TODO: 10230 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10231 // * remove app from recents (kill app it if it is running) 10232 // * erase existing notifications for this app 10233 return true; 10234 } 10235 10236 return false; 10237 } 10238 } finally { 10239 Binder.restoreCallingIdentity(callingId); 10240 } 10241 } 10242 10243 @Override 10244 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10245 mContext.enforceCallingOrSelfPermission( 10246 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10247 "Only package verification agents can verify applications"); 10248 10249 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10250 final PackageVerificationResponse response = new PackageVerificationResponse( 10251 verificationCode, Binder.getCallingUid()); 10252 msg.arg1 = id; 10253 msg.obj = response; 10254 mHandler.sendMessage(msg); 10255 } 10256 10257 @Override 10258 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10259 long millisecondsToDelay) { 10260 mContext.enforceCallingOrSelfPermission( 10261 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10262 "Only package verification agents can extend verification timeouts"); 10263 10264 final PackageVerificationState state = mPendingVerification.get(id); 10265 final PackageVerificationResponse response = new PackageVerificationResponse( 10266 verificationCodeAtTimeout, Binder.getCallingUid()); 10267 10268 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10269 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10270 } 10271 if (millisecondsToDelay < 0) { 10272 millisecondsToDelay = 0; 10273 } 10274 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10275 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10276 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10277 } 10278 10279 if ((state != null) && !state.timeoutExtended()) { 10280 state.extendTimeout(); 10281 10282 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10283 msg.arg1 = id; 10284 msg.obj = response; 10285 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10286 } 10287 } 10288 10289 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10290 int verificationCode, UserHandle user) { 10291 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10292 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10293 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10294 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10295 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10296 10297 mContext.sendBroadcastAsUser(intent, user, 10298 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10299 } 10300 10301 private ComponentName matchComponentForVerifier(String packageName, 10302 List<ResolveInfo> receivers) { 10303 ActivityInfo targetReceiver = null; 10304 10305 final int NR = receivers.size(); 10306 for (int i = 0; i < NR; i++) { 10307 final ResolveInfo info = receivers.get(i); 10308 if (info.activityInfo == null) { 10309 continue; 10310 } 10311 10312 if (packageName.equals(info.activityInfo.packageName)) { 10313 targetReceiver = info.activityInfo; 10314 break; 10315 } 10316 } 10317 10318 if (targetReceiver == null) { 10319 return null; 10320 } 10321 10322 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10323 } 10324 10325 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10326 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10327 if (pkgInfo.verifiers.length == 0) { 10328 return null; 10329 } 10330 10331 final int N = pkgInfo.verifiers.length; 10332 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10333 for (int i = 0; i < N; i++) { 10334 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10335 10336 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10337 receivers); 10338 if (comp == null) { 10339 continue; 10340 } 10341 10342 final int verifierUid = getUidForVerifier(verifierInfo); 10343 if (verifierUid == -1) { 10344 continue; 10345 } 10346 10347 if (DEBUG_VERIFY) { 10348 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10349 + " with the correct signature"); 10350 } 10351 sufficientVerifiers.add(comp); 10352 verificationState.addSufficientVerifier(verifierUid); 10353 } 10354 10355 return sufficientVerifiers; 10356 } 10357 10358 private int getUidForVerifier(VerifierInfo verifierInfo) { 10359 synchronized (mPackages) { 10360 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10361 if (pkg == null) { 10362 return -1; 10363 } else if (pkg.mSignatures.length != 1) { 10364 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10365 + " has more than one signature; ignoring"); 10366 return -1; 10367 } 10368 10369 /* 10370 * If the public key of the package's signature does not match 10371 * our expected public key, then this is a different package and 10372 * we should skip. 10373 */ 10374 10375 final byte[] expectedPublicKey; 10376 try { 10377 final Signature verifierSig = pkg.mSignatures[0]; 10378 final PublicKey publicKey = verifierSig.getPublicKey(); 10379 expectedPublicKey = publicKey.getEncoded(); 10380 } catch (CertificateException e) { 10381 return -1; 10382 } 10383 10384 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10385 10386 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10387 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10388 + " does not have the expected public key; ignoring"); 10389 return -1; 10390 } 10391 10392 return pkg.applicationInfo.uid; 10393 } 10394 } 10395 10396 @Override 10397 public void finishPackageInstall(int token) { 10398 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10399 10400 if (DEBUG_INSTALL) { 10401 Slog.v(TAG, "BM finishing package install for " + token); 10402 } 10403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10404 10405 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10406 mHandler.sendMessage(msg); 10407 } 10408 10409 /** 10410 * Get the verification agent timeout. 10411 * 10412 * @return verification timeout in milliseconds 10413 */ 10414 private long getVerificationTimeout() { 10415 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10416 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10417 DEFAULT_VERIFICATION_TIMEOUT); 10418 } 10419 10420 /** 10421 * Get the default verification agent response code. 10422 * 10423 * @return default verification response code 10424 */ 10425 private int getDefaultVerificationResponse() { 10426 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10427 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10428 DEFAULT_VERIFICATION_RESPONSE); 10429 } 10430 10431 /** 10432 * Check whether or not package verification has been enabled. 10433 * 10434 * @return true if verification should be performed 10435 */ 10436 private boolean isVerificationEnabled(int userId, int installFlags) { 10437 if (!DEFAULT_VERIFY_ENABLE) { 10438 return false; 10439 } 10440 // Ephemeral apps don't get the full verification treatment 10441 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10442 if (DEBUG_EPHEMERAL) { 10443 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10444 } 10445 return false; 10446 } 10447 10448 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10449 10450 // Check if installing from ADB 10451 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10452 // Do not run verification in a test harness environment 10453 if (ActivityManager.isRunningInTestHarness()) { 10454 return false; 10455 } 10456 if (ensureVerifyAppsEnabled) { 10457 return true; 10458 } 10459 // Check if the developer does not want package verification for ADB installs 10460 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10461 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10462 return false; 10463 } 10464 } 10465 10466 if (ensureVerifyAppsEnabled) { 10467 return true; 10468 } 10469 10470 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10471 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10472 } 10473 10474 @Override 10475 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10476 throws RemoteException { 10477 mContext.enforceCallingOrSelfPermission( 10478 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10479 "Only intentfilter verification agents can verify applications"); 10480 10481 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10482 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10483 Binder.getCallingUid(), verificationCode, failedDomains); 10484 msg.arg1 = id; 10485 msg.obj = response; 10486 mHandler.sendMessage(msg); 10487 } 10488 10489 @Override 10490 public int getIntentVerificationStatus(String packageName, int userId) { 10491 synchronized (mPackages) { 10492 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10493 } 10494 } 10495 10496 @Override 10497 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10498 mContext.enforceCallingOrSelfPermission( 10499 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10500 10501 boolean result = false; 10502 synchronized (mPackages) { 10503 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10504 } 10505 if (result) { 10506 scheduleWritePackageRestrictionsLocked(userId); 10507 } 10508 return result; 10509 } 10510 10511 @Override 10512 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10513 synchronized (mPackages) { 10514 return mSettings.getIntentFilterVerificationsLPr(packageName); 10515 } 10516 } 10517 10518 @Override 10519 public List<IntentFilter> getAllIntentFilters(String packageName) { 10520 if (TextUtils.isEmpty(packageName)) { 10521 return Collections.<IntentFilter>emptyList(); 10522 } 10523 synchronized (mPackages) { 10524 PackageParser.Package pkg = mPackages.get(packageName); 10525 if (pkg == null || pkg.activities == null) { 10526 return Collections.<IntentFilter>emptyList(); 10527 } 10528 final int count = pkg.activities.size(); 10529 ArrayList<IntentFilter> result = new ArrayList<>(); 10530 for (int n=0; n<count; n++) { 10531 PackageParser.Activity activity = pkg.activities.get(n); 10532 if (activity.intents != null && activity.intents.size() > 0) { 10533 result.addAll(activity.intents); 10534 } 10535 } 10536 return result; 10537 } 10538 } 10539 10540 @Override 10541 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10542 mContext.enforceCallingOrSelfPermission( 10543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10544 10545 synchronized (mPackages) { 10546 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10547 if (packageName != null) { 10548 result |= updateIntentVerificationStatus(packageName, 10549 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10550 userId); 10551 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10552 packageName, userId); 10553 } 10554 return result; 10555 } 10556 } 10557 10558 @Override 10559 public String getDefaultBrowserPackageName(int userId) { 10560 synchronized (mPackages) { 10561 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10562 } 10563 } 10564 10565 /** 10566 * Get the "allow unknown sources" setting. 10567 * 10568 * @return the current "allow unknown sources" setting 10569 */ 10570 private int getUnknownSourcesSettings() { 10571 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10572 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10573 -1); 10574 } 10575 10576 @Override 10577 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10578 final int uid = Binder.getCallingUid(); 10579 // writer 10580 synchronized (mPackages) { 10581 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10582 if (targetPackageSetting == null) { 10583 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10584 } 10585 10586 PackageSetting installerPackageSetting; 10587 if (installerPackageName != null) { 10588 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10589 if (installerPackageSetting == null) { 10590 throw new IllegalArgumentException("Unknown installer package: " 10591 + installerPackageName); 10592 } 10593 } else { 10594 installerPackageSetting = null; 10595 } 10596 10597 Signature[] callerSignature; 10598 Object obj = mSettings.getUserIdLPr(uid); 10599 if (obj != null) { 10600 if (obj instanceof SharedUserSetting) { 10601 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10602 } else if (obj instanceof PackageSetting) { 10603 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10604 } else { 10605 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10606 } 10607 } else { 10608 throw new SecurityException("Unknown calling UID: " + uid); 10609 } 10610 10611 // Verify: can't set installerPackageName to a package that is 10612 // not signed with the same cert as the caller. 10613 if (installerPackageSetting != null) { 10614 if (compareSignatures(callerSignature, 10615 installerPackageSetting.signatures.mSignatures) 10616 != PackageManager.SIGNATURE_MATCH) { 10617 throw new SecurityException( 10618 "Caller does not have same cert as new installer package " 10619 + installerPackageName); 10620 } 10621 } 10622 10623 // Verify: if target already has an installer package, it must 10624 // be signed with the same cert as the caller. 10625 if (targetPackageSetting.installerPackageName != null) { 10626 PackageSetting setting = mSettings.mPackages.get( 10627 targetPackageSetting.installerPackageName); 10628 // If the currently set package isn't valid, then it's always 10629 // okay to change it. 10630 if (setting != null) { 10631 if (compareSignatures(callerSignature, 10632 setting.signatures.mSignatures) 10633 != PackageManager.SIGNATURE_MATCH) { 10634 throw new SecurityException( 10635 "Caller does not have same cert as old installer package " 10636 + targetPackageSetting.installerPackageName); 10637 } 10638 } 10639 } 10640 10641 // Okay! 10642 targetPackageSetting.installerPackageName = installerPackageName; 10643 scheduleWriteSettingsLocked(); 10644 } 10645 } 10646 10647 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10648 // Queue up an async operation since the package installation may take a little while. 10649 mHandler.post(new Runnable() { 10650 public void run() { 10651 mHandler.removeCallbacks(this); 10652 // Result object to be returned 10653 PackageInstalledInfo res = new PackageInstalledInfo(); 10654 res.returnCode = currentStatus; 10655 res.uid = -1; 10656 res.pkg = null; 10657 res.removedInfo = new PackageRemovedInfo(); 10658 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10659 args.doPreInstall(res.returnCode); 10660 synchronized (mInstallLock) { 10661 installPackageTracedLI(args, res); 10662 } 10663 args.doPostInstall(res.returnCode, res.uid); 10664 } 10665 10666 // A restore should be performed at this point if (a) the install 10667 // succeeded, (b) the operation is not an update, and (c) the new 10668 // package has not opted out of backup participation. 10669 final boolean update = res.removedInfo.removedPackage != null; 10670 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10671 boolean doRestore = !update 10672 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10673 10674 // Set up the post-install work request bookkeeping. This will be used 10675 // and cleaned up by the post-install event handling regardless of whether 10676 // there's a restore pass performed. Token values are >= 1. 10677 int token; 10678 if (mNextInstallToken < 0) mNextInstallToken = 1; 10679 token = mNextInstallToken++; 10680 10681 PostInstallData data = new PostInstallData(args, res); 10682 mRunningInstalls.put(token, data); 10683 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10684 10685 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10686 // Pass responsibility to the Backup Manager. It will perform a 10687 // restore if appropriate, then pass responsibility back to the 10688 // Package Manager to run the post-install observer callbacks 10689 // and broadcasts. 10690 IBackupManager bm = IBackupManager.Stub.asInterface( 10691 ServiceManager.getService(Context.BACKUP_SERVICE)); 10692 if (bm != null) { 10693 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10694 + " to BM for possible restore"); 10695 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10696 try { 10697 // TODO: http://b/22388012 10698 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10699 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10700 } else { 10701 doRestore = false; 10702 } 10703 } catch (RemoteException e) { 10704 // can't happen; the backup manager is local 10705 } catch (Exception e) { 10706 Slog.e(TAG, "Exception trying to enqueue restore", e); 10707 doRestore = false; 10708 } 10709 } else { 10710 Slog.e(TAG, "Backup Manager not found!"); 10711 doRestore = false; 10712 } 10713 } 10714 10715 if (!doRestore) { 10716 // No restore possible, or the Backup Manager was mysteriously not 10717 // available -- just fire the post-install work request directly. 10718 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10719 10720 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10721 10722 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10723 mHandler.sendMessage(msg); 10724 } 10725 } 10726 }); 10727 } 10728 10729 private abstract class HandlerParams { 10730 private static final int MAX_RETRIES = 4; 10731 10732 /** 10733 * Number of times startCopy() has been attempted and had a non-fatal 10734 * error. 10735 */ 10736 private int mRetries = 0; 10737 10738 /** User handle for the user requesting the information or installation. */ 10739 private final UserHandle mUser; 10740 String traceMethod; 10741 int traceCookie; 10742 10743 HandlerParams(UserHandle user) { 10744 mUser = user; 10745 } 10746 10747 UserHandle getUser() { 10748 return mUser; 10749 } 10750 10751 HandlerParams setTraceMethod(String traceMethod) { 10752 this.traceMethod = traceMethod; 10753 return this; 10754 } 10755 10756 HandlerParams setTraceCookie(int traceCookie) { 10757 this.traceCookie = traceCookie; 10758 return this; 10759 } 10760 10761 final boolean startCopy() { 10762 boolean res; 10763 try { 10764 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10765 10766 if (++mRetries > MAX_RETRIES) { 10767 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10768 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10769 handleServiceError(); 10770 return false; 10771 } else { 10772 handleStartCopy(); 10773 res = true; 10774 } 10775 } catch (RemoteException e) { 10776 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10777 mHandler.sendEmptyMessage(MCS_RECONNECT); 10778 res = false; 10779 } 10780 handleReturnCode(); 10781 return res; 10782 } 10783 10784 final void serviceError() { 10785 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10786 handleServiceError(); 10787 handleReturnCode(); 10788 } 10789 10790 abstract void handleStartCopy() throws RemoteException; 10791 abstract void handleServiceError(); 10792 abstract void handleReturnCode(); 10793 } 10794 10795 class MeasureParams extends HandlerParams { 10796 private final PackageStats mStats; 10797 private boolean mSuccess; 10798 10799 private final IPackageStatsObserver mObserver; 10800 10801 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10802 super(new UserHandle(stats.userHandle)); 10803 mObserver = observer; 10804 mStats = stats; 10805 } 10806 10807 @Override 10808 public String toString() { 10809 return "MeasureParams{" 10810 + Integer.toHexString(System.identityHashCode(this)) 10811 + " " + mStats.packageName + "}"; 10812 } 10813 10814 @Override 10815 void handleStartCopy() throws RemoteException { 10816 synchronized (mInstallLock) { 10817 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10818 } 10819 10820 if (mSuccess) { 10821 final boolean mounted; 10822 if (Environment.isExternalStorageEmulated()) { 10823 mounted = true; 10824 } else { 10825 final String status = Environment.getExternalStorageState(); 10826 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10827 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10828 } 10829 10830 if (mounted) { 10831 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10832 10833 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10834 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10835 10836 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10837 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10838 10839 // Always subtract cache size, since it's a subdirectory 10840 mStats.externalDataSize -= mStats.externalCacheSize; 10841 10842 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10843 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10844 10845 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10846 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10847 } 10848 } 10849 } 10850 10851 @Override 10852 void handleReturnCode() { 10853 if (mObserver != null) { 10854 try { 10855 mObserver.onGetStatsCompleted(mStats, mSuccess); 10856 } catch (RemoteException e) { 10857 Slog.i(TAG, "Observer no longer exists."); 10858 } 10859 } 10860 } 10861 10862 @Override 10863 void handleServiceError() { 10864 Slog.e(TAG, "Could not measure application " + mStats.packageName 10865 + " external storage"); 10866 } 10867 } 10868 10869 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10870 throws RemoteException { 10871 long result = 0; 10872 for (File path : paths) { 10873 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10874 } 10875 return result; 10876 } 10877 10878 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10879 for (File path : paths) { 10880 try { 10881 mcs.clearDirectory(path.getAbsolutePath()); 10882 } catch (RemoteException e) { 10883 } 10884 } 10885 } 10886 10887 static class OriginInfo { 10888 /** 10889 * Location where install is coming from, before it has been 10890 * copied/renamed into place. This could be a single monolithic APK 10891 * file, or a cluster directory. This location may be untrusted. 10892 */ 10893 final File file; 10894 final String cid; 10895 10896 /** 10897 * Flag indicating that {@link #file} or {@link #cid} has already been 10898 * staged, meaning downstream users don't need to defensively copy the 10899 * contents. 10900 */ 10901 final boolean staged; 10902 10903 /** 10904 * Flag indicating that {@link #file} or {@link #cid} is an already 10905 * installed app that is being moved. 10906 */ 10907 final boolean existing; 10908 10909 final String resolvedPath; 10910 final File resolvedFile; 10911 10912 static OriginInfo fromNothing() { 10913 return new OriginInfo(null, null, false, false); 10914 } 10915 10916 static OriginInfo fromUntrustedFile(File file) { 10917 return new OriginInfo(file, null, false, false); 10918 } 10919 10920 static OriginInfo fromExistingFile(File file) { 10921 return new OriginInfo(file, null, false, true); 10922 } 10923 10924 static OriginInfo fromStagedFile(File file) { 10925 return new OriginInfo(file, null, true, false); 10926 } 10927 10928 static OriginInfo fromStagedContainer(String cid) { 10929 return new OriginInfo(null, cid, true, false); 10930 } 10931 10932 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10933 this.file = file; 10934 this.cid = cid; 10935 this.staged = staged; 10936 this.existing = existing; 10937 10938 if (cid != null) { 10939 resolvedPath = PackageHelper.getSdDir(cid); 10940 resolvedFile = new File(resolvedPath); 10941 } else if (file != null) { 10942 resolvedPath = file.getAbsolutePath(); 10943 resolvedFile = file; 10944 } else { 10945 resolvedPath = null; 10946 resolvedFile = null; 10947 } 10948 } 10949 } 10950 10951 static class MoveInfo { 10952 final int moveId; 10953 final String fromUuid; 10954 final String toUuid; 10955 final String packageName; 10956 final String dataAppName; 10957 final int appId; 10958 final String seinfo; 10959 10960 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10961 String dataAppName, int appId, String seinfo) { 10962 this.moveId = moveId; 10963 this.fromUuid = fromUuid; 10964 this.toUuid = toUuid; 10965 this.packageName = packageName; 10966 this.dataAppName = dataAppName; 10967 this.appId = appId; 10968 this.seinfo = seinfo; 10969 } 10970 } 10971 10972 class InstallParams extends HandlerParams { 10973 final OriginInfo origin; 10974 final MoveInfo move; 10975 final IPackageInstallObserver2 observer; 10976 int installFlags; 10977 final String installerPackageName; 10978 final String volumeUuid; 10979 final VerificationParams verificationParams; 10980 private InstallArgs mArgs; 10981 private int mRet; 10982 final String packageAbiOverride; 10983 final String[] grantedRuntimePermissions; 10984 10985 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10986 int installFlags, String installerPackageName, String volumeUuid, 10987 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10988 String[] grantedPermissions) { 10989 super(user); 10990 this.origin = origin; 10991 this.move = move; 10992 this.observer = observer; 10993 this.installFlags = installFlags; 10994 this.installerPackageName = installerPackageName; 10995 this.volumeUuid = volumeUuid; 10996 this.verificationParams = verificationParams; 10997 this.packageAbiOverride = packageAbiOverride; 10998 this.grantedRuntimePermissions = grantedPermissions; 10999 } 11000 11001 @Override 11002 public String toString() { 11003 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11004 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11005 } 11006 11007 private int installLocationPolicy(PackageInfoLite pkgLite) { 11008 String packageName = pkgLite.packageName; 11009 int installLocation = pkgLite.installLocation; 11010 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11011 // reader 11012 synchronized (mPackages) { 11013 PackageParser.Package pkg = mPackages.get(packageName); 11014 if (pkg != null) { 11015 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11016 // Check for downgrading. 11017 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11018 try { 11019 checkDowngrade(pkg, pkgLite); 11020 } catch (PackageManagerException e) { 11021 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11022 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11023 } 11024 } 11025 // Check for updated system application. 11026 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11027 if (onSd) { 11028 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11029 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11030 } 11031 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11032 } else { 11033 if (onSd) { 11034 // Install flag overrides everything. 11035 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11036 } 11037 // If current upgrade specifies particular preference 11038 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11039 // Application explicitly specified internal. 11040 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11041 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11042 // App explictly prefers external. Let policy decide 11043 } else { 11044 // Prefer previous location 11045 if (isExternal(pkg)) { 11046 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11047 } 11048 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11049 } 11050 } 11051 } else { 11052 // Invalid install. Return error code 11053 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11054 } 11055 } 11056 } 11057 // All the special cases have been taken care of. 11058 // Return result based on recommended install location. 11059 if (onSd) { 11060 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11061 } 11062 return pkgLite.recommendedInstallLocation; 11063 } 11064 11065 /* 11066 * Invoke remote method to get package information and install 11067 * location values. Override install location based on default 11068 * policy if needed and then create install arguments based 11069 * on the install location. 11070 */ 11071 public void handleStartCopy() throws RemoteException { 11072 int ret = PackageManager.INSTALL_SUCCEEDED; 11073 11074 // If we're already staged, we've firmly committed to an install location 11075 if (origin.staged) { 11076 if (origin.file != null) { 11077 installFlags |= PackageManager.INSTALL_INTERNAL; 11078 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11079 } else if (origin.cid != null) { 11080 installFlags |= PackageManager.INSTALL_EXTERNAL; 11081 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11082 } else { 11083 throw new IllegalStateException("Invalid stage location"); 11084 } 11085 } 11086 11087 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11088 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11089 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11090 PackageInfoLite pkgLite = null; 11091 11092 if (onInt && onSd) { 11093 // Check if both bits are set. 11094 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11095 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11096 } else if (onSd && ephemeral) { 11097 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11098 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11099 } else { 11100 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11101 packageAbiOverride); 11102 11103 if (DEBUG_EPHEMERAL && ephemeral) { 11104 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11105 } 11106 11107 /* 11108 * If we have too little free space, try to free cache 11109 * before giving up. 11110 */ 11111 if (!origin.staged && pkgLite.recommendedInstallLocation 11112 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11113 // TODO: focus freeing disk space on the target device 11114 final StorageManager storage = StorageManager.from(mContext); 11115 final long lowThreshold = storage.getStorageLowBytes( 11116 Environment.getDataDirectory()); 11117 11118 final long sizeBytes = mContainerService.calculateInstalledSize( 11119 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11120 11121 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11122 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11123 installFlags, packageAbiOverride); 11124 } 11125 11126 /* 11127 * The cache free must have deleted the file we 11128 * downloaded to install. 11129 * 11130 * TODO: fix the "freeCache" call to not delete 11131 * the file we care about. 11132 */ 11133 if (pkgLite.recommendedInstallLocation 11134 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11135 pkgLite.recommendedInstallLocation 11136 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11137 } 11138 } 11139 } 11140 11141 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11142 int loc = pkgLite.recommendedInstallLocation; 11143 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11144 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11145 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11146 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11147 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11148 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11149 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11150 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11151 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11152 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11153 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11154 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11155 } else { 11156 // Override with defaults if needed. 11157 loc = installLocationPolicy(pkgLite); 11158 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11159 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11160 } else if (!onSd && !onInt) { 11161 // Override install location with flags 11162 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11163 // Set the flag to install on external media. 11164 installFlags |= PackageManager.INSTALL_EXTERNAL; 11165 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11166 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11167 if (DEBUG_EPHEMERAL) { 11168 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11169 } 11170 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11171 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11172 |PackageManager.INSTALL_INTERNAL); 11173 } else { 11174 // Make sure the flag for installing on external 11175 // media is unset 11176 installFlags |= PackageManager.INSTALL_INTERNAL; 11177 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11178 } 11179 } 11180 } 11181 } 11182 11183 final InstallArgs args = createInstallArgs(this); 11184 mArgs = args; 11185 11186 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11187 // TODO: http://b/22976637 11188 // Apps installed for "all" users use the device owner to verify the app 11189 UserHandle verifierUser = getUser(); 11190 if (verifierUser == UserHandle.ALL) { 11191 verifierUser = UserHandle.SYSTEM; 11192 } 11193 11194 /* 11195 * Determine if we have any installed package verifiers. If we 11196 * do, then we'll defer to them to verify the packages. 11197 */ 11198 final int requiredUid = mRequiredVerifierPackage == null ? -1 11199 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11200 verifierUser.getIdentifier()); 11201 if (!origin.existing && requiredUid != -1 11202 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11203 final Intent verification = new Intent( 11204 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11205 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11206 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11207 PACKAGE_MIME_TYPE); 11208 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11209 11210 // Query all live verifiers based on current user state 11211 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11212 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11213 11214 if (DEBUG_VERIFY) { 11215 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11216 + verification.toString() + " with " + pkgLite.verifiers.length 11217 + " optional verifiers"); 11218 } 11219 11220 final int verificationId = mPendingVerificationToken++; 11221 11222 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11223 11224 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11225 installerPackageName); 11226 11227 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11228 installFlags); 11229 11230 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11231 pkgLite.packageName); 11232 11233 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11234 pkgLite.versionCode); 11235 11236 if (verificationParams != null) { 11237 if (verificationParams.getVerificationURI() != null) { 11238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11239 verificationParams.getVerificationURI()); 11240 } 11241 if (verificationParams.getOriginatingURI() != null) { 11242 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11243 verificationParams.getOriginatingURI()); 11244 } 11245 if (verificationParams.getReferrer() != null) { 11246 verification.putExtra(Intent.EXTRA_REFERRER, 11247 verificationParams.getReferrer()); 11248 } 11249 if (verificationParams.getOriginatingUid() >= 0) { 11250 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11251 verificationParams.getOriginatingUid()); 11252 } 11253 if (verificationParams.getInstallerUid() >= 0) { 11254 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11255 verificationParams.getInstallerUid()); 11256 } 11257 } 11258 11259 final PackageVerificationState verificationState = new PackageVerificationState( 11260 requiredUid, args); 11261 11262 mPendingVerification.append(verificationId, verificationState); 11263 11264 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11265 receivers, verificationState); 11266 11267 /* 11268 * If any sufficient verifiers were listed in the package 11269 * manifest, attempt to ask them. 11270 */ 11271 if (sufficientVerifiers != null) { 11272 final int N = sufficientVerifiers.size(); 11273 if (N == 0) { 11274 Slog.i(TAG, "Additional verifiers required, but none installed."); 11275 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11276 } else { 11277 for (int i = 0; i < N; i++) { 11278 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11279 11280 final Intent sufficientIntent = new Intent(verification); 11281 sufficientIntent.setComponent(verifierComponent); 11282 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11283 } 11284 } 11285 } 11286 11287 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11288 mRequiredVerifierPackage, receivers); 11289 if (ret == PackageManager.INSTALL_SUCCEEDED 11290 && mRequiredVerifierPackage != null) { 11291 Trace.asyncTraceBegin( 11292 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11293 /* 11294 * Send the intent to the required verification agent, 11295 * but only start the verification timeout after the 11296 * target BroadcastReceivers have run. 11297 */ 11298 verification.setComponent(requiredVerifierComponent); 11299 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11300 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11301 new BroadcastReceiver() { 11302 @Override 11303 public void onReceive(Context context, Intent intent) { 11304 final Message msg = mHandler 11305 .obtainMessage(CHECK_PENDING_VERIFICATION); 11306 msg.arg1 = verificationId; 11307 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11308 } 11309 }, null, 0, null, null); 11310 11311 /* 11312 * We don't want the copy to proceed until verification 11313 * succeeds, so null out this field. 11314 */ 11315 mArgs = null; 11316 } 11317 } else { 11318 /* 11319 * No package verification is enabled, so immediately start 11320 * the remote call to initiate copy using temporary file. 11321 */ 11322 ret = args.copyApk(mContainerService, true); 11323 } 11324 } 11325 11326 mRet = ret; 11327 } 11328 11329 @Override 11330 void handleReturnCode() { 11331 // If mArgs is null, then MCS couldn't be reached. When it 11332 // reconnects, it will try again to install. At that point, this 11333 // will succeed. 11334 if (mArgs != null) { 11335 processPendingInstall(mArgs, mRet); 11336 } 11337 } 11338 11339 @Override 11340 void handleServiceError() { 11341 mArgs = createInstallArgs(this); 11342 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11343 } 11344 11345 public boolean isForwardLocked() { 11346 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11347 } 11348 } 11349 11350 /** 11351 * Used during creation of InstallArgs 11352 * 11353 * @param installFlags package installation flags 11354 * @return true if should be installed on external storage 11355 */ 11356 private static boolean installOnExternalAsec(int installFlags) { 11357 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11358 return false; 11359 } 11360 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11361 return true; 11362 } 11363 return false; 11364 } 11365 11366 /** 11367 * Used during creation of InstallArgs 11368 * 11369 * @param installFlags package installation flags 11370 * @return true if should be installed as forward locked 11371 */ 11372 private static boolean installForwardLocked(int installFlags) { 11373 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11374 } 11375 11376 private InstallArgs createInstallArgs(InstallParams params) { 11377 if (params.move != null) { 11378 return new MoveInstallArgs(params); 11379 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11380 return new AsecInstallArgs(params); 11381 } else { 11382 return new FileInstallArgs(params); 11383 } 11384 } 11385 11386 /** 11387 * Create args that describe an existing installed package. Typically used 11388 * when cleaning up old installs, or used as a move source. 11389 */ 11390 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11391 String resourcePath, String[] instructionSets) { 11392 final boolean isInAsec; 11393 if (installOnExternalAsec(installFlags)) { 11394 /* Apps on SD card are always in ASEC containers. */ 11395 isInAsec = true; 11396 } else if (installForwardLocked(installFlags) 11397 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11398 /* 11399 * Forward-locked apps are only in ASEC containers if they're the 11400 * new style 11401 */ 11402 isInAsec = true; 11403 } else { 11404 isInAsec = false; 11405 } 11406 11407 if (isInAsec) { 11408 return new AsecInstallArgs(codePath, instructionSets, 11409 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11410 } else { 11411 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11412 } 11413 } 11414 11415 static abstract class InstallArgs { 11416 /** @see InstallParams#origin */ 11417 final OriginInfo origin; 11418 /** @see InstallParams#move */ 11419 final MoveInfo move; 11420 11421 final IPackageInstallObserver2 observer; 11422 // Always refers to PackageManager flags only 11423 final int installFlags; 11424 final String installerPackageName; 11425 final String volumeUuid; 11426 final UserHandle user; 11427 final String abiOverride; 11428 final String[] installGrantPermissions; 11429 /** If non-null, drop an async trace when the install completes */ 11430 final String traceMethod; 11431 final int traceCookie; 11432 11433 // The list of instruction sets supported by this app. This is currently 11434 // only used during the rmdex() phase to clean up resources. We can get rid of this 11435 // if we move dex files under the common app path. 11436 /* nullable */ String[] instructionSets; 11437 11438 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11439 int installFlags, String installerPackageName, String volumeUuid, 11440 UserHandle user, String[] instructionSets, 11441 String abiOverride, String[] installGrantPermissions, 11442 String traceMethod, int traceCookie) { 11443 this.origin = origin; 11444 this.move = move; 11445 this.installFlags = installFlags; 11446 this.observer = observer; 11447 this.installerPackageName = installerPackageName; 11448 this.volumeUuid = volumeUuid; 11449 this.user = user; 11450 this.instructionSets = instructionSets; 11451 this.abiOverride = abiOverride; 11452 this.installGrantPermissions = installGrantPermissions; 11453 this.traceMethod = traceMethod; 11454 this.traceCookie = traceCookie; 11455 } 11456 11457 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11458 abstract int doPreInstall(int status); 11459 11460 /** 11461 * Rename package into final resting place. All paths on the given 11462 * scanned package should be updated to reflect the rename. 11463 */ 11464 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11465 abstract int doPostInstall(int status, int uid); 11466 11467 /** @see PackageSettingBase#codePathString */ 11468 abstract String getCodePath(); 11469 /** @see PackageSettingBase#resourcePathString */ 11470 abstract String getResourcePath(); 11471 11472 // Need installer lock especially for dex file removal. 11473 abstract void cleanUpResourcesLI(); 11474 abstract boolean doPostDeleteLI(boolean delete); 11475 11476 /** 11477 * Called before the source arguments are copied. This is used mostly 11478 * for MoveParams when it needs to read the source file to put it in the 11479 * destination. 11480 */ 11481 int doPreCopy() { 11482 return PackageManager.INSTALL_SUCCEEDED; 11483 } 11484 11485 /** 11486 * Called after the source arguments are copied. This is used mostly for 11487 * MoveParams when it needs to read the source file to put it in the 11488 * destination. 11489 * 11490 * @return 11491 */ 11492 int doPostCopy(int uid) { 11493 return PackageManager.INSTALL_SUCCEEDED; 11494 } 11495 11496 protected boolean isFwdLocked() { 11497 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11498 } 11499 11500 protected boolean isExternalAsec() { 11501 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11502 } 11503 11504 protected boolean isEphemeral() { 11505 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11506 } 11507 11508 UserHandle getUser() { 11509 return user; 11510 } 11511 } 11512 11513 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11514 if (!allCodePaths.isEmpty()) { 11515 if (instructionSets == null) { 11516 throw new IllegalStateException("instructionSet == null"); 11517 } 11518 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11519 for (String codePath : allCodePaths) { 11520 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11521 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11522 if (retCode < 0) { 11523 Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath 11524 + ", retcode=" + retCode); 11525 // we don't consider this to be a failure of the core package deletion 11526 } 11527 } 11528 } 11529 } 11530 } 11531 11532 /** 11533 * Logic to handle installation of non-ASEC applications, including copying 11534 * and renaming logic. 11535 */ 11536 class FileInstallArgs extends InstallArgs { 11537 private File codeFile; 11538 private File resourceFile; 11539 11540 // Example topology: 11541 // /data/app/com.example/base.apk 11542 // /data/app/com.example/split_foo.apk 11543 // /data/app/com.example/lib/arm/libfoo.so 11544 // /data/app/com.example/lib/arm64/libfoo.so 11545 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11546 11547 /** New install */ 11548 FileInstallArgs(InstallParams params) { 11549 super(params.origin, params.move, params.observer, params.installFlags, 11550 params.installerPackageName, params.volumeUuid, 11551 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11552 params.grantedRuntimePermissions, 11553 params.traceMethod, params.traceCookie); 11554 if (isFwdLocked()) { 11555 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11556 } 11557 } 11558 11559 /** Existing install */ 11560 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11561 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11562 null, null, null, 0); 11563 this.codeFile = (codePath != null) ? new File(codePath) : null; 11564 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11565 } 11566 11567 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11569 try { 11570 return doCopyApk(imcs, temp); 11571 } finally { 11572 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11573 } 11574 } 11575 11576 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11577 if (origin.staged) { 11578 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11579 codeFile = origin.file; 11580 resourceFile = origin.file; 11581 return PackageManager.INSTALL_SUCCEEDED; 11582 } 11583 11584 try { 11585 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11586 final File tempDir = 11587 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11588 codeFile = tempDir; 11589 resourceFile = tempDir; 11590 } catch (IOException e) { 11591 Slog.w(TAG, "Failed to create copy file: " + e); 11592 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11593 } 11594 11595 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11596 @Override 11597 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11598 if (!FileUtils.isValidExtFilename(name)) { 11599 throw new IllegalArgumentException("Invalid filename: " + name); 11600 } 11601 try { 11602 final File file = new File(codeFile, name); 11603 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11604 O_RDWR | O_CREAT, 0644); 11605 Os.chmod(file.getAbsolutePath(), 0644); 11606 return new ParcelFileDescriptor(fd); 11607 } catch (ErrnoException e) { 11608 throw new RemoteException("Failed to open: " + e.getMessage()); 11609 } 11610 } 11611 }; 11612 11613 int ret = PackageManager.INSTALL_SUCCEEDED; 11614 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11615 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11616 Slog.e(TAG, "Failed to copy package"); 11617 return ret; 11618 } 11619 11620 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11621 NativeLibraryHelper.Handle handle = null; 11622 try { 11623 handle = NativeLibraryHelper.Handle.create(codeFile); 11624 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11625 abiOverride); 11626 } catch (IOException e) { 11627 Slog.e(TAG, "Copying native libraries failed", e); 11628 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11629 } finally { 11630 IoUtils.closeQuietly(handle); 11631 } 11632 11633 return ret; 11634 } 11635 11636 int doPreInstall(int status) { 11637 if (status != PackageManager.INSTALL_SUCCEEDED) { 11638 cleanUp(); 11639 } 11640 return status; 11641 } 11642 11643 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11644 if (status != PackageManager.INSTALL_SUCCEEDED) { 11645 cleanUp(); 11646 return false; 11647 } 11648 11649 final File targetDir = codeFile.getParentFile(); 11650 final File beforeCodeFile = codeFile; 11651 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11652 11653 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11654 try { 11655 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11656 } catch (ErrnoException e) { 11657 Slog.w(TAG, "Failed to rename", e); 11658 return false; 11659 } 11660 11661 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11662 Slog.w(TAG, "Failed to restorecon"); 11663 return false; 11664 } 11665 11666 // Reflect the rename internally 11667 codeFile = afterCodeFile; 11668 resourceFile = afterCodeFile; 11669 11670 // Reflect the rename in scanned details 11671 pkg.codePath = afterCodeFile.getAbsolutePath(); 11672 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11673 pkg.baseCodePath); 11674 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11675 pkg.splitCodePaths); 11676 11677 // Reflect the rename in app info 11678 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11679 pkg.applicationInfo.setCodePath(pkg.codePath); 11680 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11681 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11682 pkg.applicationInfo.setResourcePath(pkg.codePath); 11683 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11684 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11685 11686 return true; 11687 } 11688 11689 int doPostInstall(int status, int uid) { 11690 if (status != PackageManager.INSTALL_SUCCEEDED) { 11691 cleanUp(); 11692 } 11693 return status; 11694 } 11695 11696 @Override 11697 String getCodePath() { 11698 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11699 } 11700 11701 @Override 11702 String getResourcePath() { 11703 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11704 } 11705 11706 private boolean cleanUp() { 11707 if (codeFile == null || !codeFile.exists()) { 11708 return false; 11709 } 11710 11711 if (codeFile.isDirectory()) { 11712 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11713 } else { 11714 codeFile.delete(); 11715 } 11716 11717 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11718 resourceFile.delete(); 11719 } 11720 11721 return true; 11722 } 11723 11724 void cleanUpResourcesLI() { 11725 // Try enumerating all code paths before deleting 11726 List<String> allCodePaths = Collections.EMPTY_LIST; 11727 if (codeFile != null && codeFile.exists()) { 11728 try { 11729 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11730 allCodePaths = pkg.getAllCodePaths(); 11731 } catch (PackageParserException e) { 11732 // Ignored; we tried our best 11733 } 11734 } 11735 11736 cleanUp(); 11737 removeDexFiles(allCodePaths, instructionSets); 11738 } 11739 11740 boolean doPostDeleteLI(boolean delete) { 11741 // XXX err, shouldn't we respect the delete flag? 11742 cleanUpResourcesLI(); 11743 return true; 11744 } 11745 } 11746 11747 private boolean isAsecExternal(String cid) { 11748 final String asecPath = PackageHelper.getSdFilesystem(cid); 11749 return !asecPath.startsWith(mAsecInternalPath); 11750 } 11751 11752 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11753 PackageManagerException { 11754 if (copyRet < 0) { 11755 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11756 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11757 throw new PackageManagerException(copyRet, message); 11758 } 11759 } 11760 } 11761 11762 /** 11763 * Extract the MountService "container ID" from the full code path of an 11764 * .apk. 11765 */ 11766 static String cidFromCodePath(String fullCodePath) { 11767 int eidx = fullCodePath.lastIndexOf("/"); 11768 String subStr1 = fullCodePath.substring(0, eidx); 11769 int sidx = subStr1.lastIndexOf("/"); 11770 return subStr1.substring(sidx+1, eidx); 11771 } 11772 11773 /** 11774 * Logic to handle installation of ASEC applications, including copying and 11775 * renaming logic. 11776 */ 11777 class AsecInstallArgs extends InstallArgs { 11778 static final String RES_FILE_NAME = "pkg.apk"; 11779 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11780 11781 String cid; 11782 String packagePath; 11783 String resourcePath; 11784 11785 /** New install */ 11786 AsecInstallArgs(InstallParams params) { 11787 super(params.origin, params.move, params.observer, params.installFlags, 11788 params.installerPackageName, params.volumeUuid, 11789 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11790 params.grantedRuntimePermissions, 11791 params.traceMethod, params.traceCookie); 11792 } 11793 11794 /** Existing install */ 11795 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11796 boolean isExternal, boolean isForwardLocked) { 11797 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11798 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11799 instructionSets, null, null, null, 0); 11800 // Hackily pretend we're still looking at a full code path 11801 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11802 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11803 } 11804 11805 // Extract cid from fullCodePath 11806 int eidx = fullCodePath.lastIndexOf("/"); 11807 String subStr1 = fullCodePath.substring(0, eidx); 11808 int sidx = subStr1.lastIndexOf("/"); 11809 cid = subStr1.substring(sidx+1, eidx); 11810 setMountPath(subStr1); 11811 } 11812 11813 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11814 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11815 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11816 instructionSets, null, null, null, 0); 11817 this.cid = cid; 11818 setMountPath(PackageHelper.getSdDir(cid)); 11819 } 11820 11821 void createCopyFile() { 11822 cid = mInstallerService.allocateExternalStageCidLegacy(); 11823 } 11824 11825 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11826 if (origin.staged && origin.cid != null) { 11827 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11828 cid = origin.cid; 11829 setMountPath(PackageHelper.getSdDir(cid)); 11830 return PackageManager.INSTALL_SUCCEEDED; 11831 } 11832 11833 if (temp) { 11834 createCopyFile(); 11835 } else { 11836 /* 11837 * Pre-emptively destroy the container since it's destroyed if 11838 * copying fails due to it existing anyway. 11839 */ 11840 PackageHelper.destroySdDir(cid); 11841 } 11842 11843 final String newMountPath = imcs.copyPackageToContainer( 11844 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11845 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11846 11847 if (newMountPath != null) { 11848 setMountPath(newMountPath); 11849 return PackageManager.INSTALL_SUCCEEDED; 11850 } else { 11851 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11852 } 11853 } 11854 11855 @Override 11856 String getCodePath() { 11857 return packagePath; 11858 } 11859 11860 @Override 11861 String getResourcePath() { 11862 return resourcePath; 11863 } 11864 11865 int doPreInstall(int status) { 11866 if (status != PackageManager.INSTALL_SUCCEEDED) { 11867 // Destroy container 11868 PackageHelper.destroySdDir(cid); 11869 } else { 11870 boolean mounted = PackageHelper.isContainerMounted(cid); 11871 if (!mounted) { 11872 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11873 Process.SYSTEM_UID); 11874 if (newMountPath != null) { 11875 setMountPath(newMountPath); 11876 } else { 11877 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11878 } 11879 } 11880 } 11881 return status; 11882 } 11883 11884 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11885 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11886 String newMountPath = null; 11887 if (PackageHelper.isContainerMounted(cid)) { 11888 // Unmount the container 11889 if (!PackageHelper.unMountSdDir(cid)) { 11890 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11891 return false; 11892 } 11893 } 11894 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11895 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11896 " which might be stale. Will try to clean up."); 11897 // Clean up the stale container and proceed to recreate. 11898 if (!PackageHelper.destroySdDir(newCacheId)) { 11899 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11900 return false; 11901 } 11902 // Successfully cleaned up stale container. Try to rename again. 11903 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11904 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11905 + " inspite of cleaning it up."); 11906 return false; 11907 } 11908 } 11909 if (!PackageHelper.isContainerMounted(newCacheId)) { 11910 Slog.w(TAG, "Mounting container " + newCacheId); 11911 newMountPath = PackageHelper.mountSdDir(newCacheId, 11912 getEncryptKey(), Process.SYSTEM_UID); 11913 } else { 11914 newMountPath = PackageHelper.getSdDir(newCacheId); 11915 } 11916 if (newMountPath == null) { 11917 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11918 return false; 11919 } 11920 Log.i(TAG, "Succesfully renamed " + cid + 11921 " to " + newCacheId + 11922 " at new path: " + newMountPath); 11923 cid = newCacheId; 11924 11925 final File beforeCodeFile = new File(packagePath); 11926 setMountPath(newMountPath); 11927 final File afterCodeFile = new File(packagePath); 11928 11929 // Reflect the rename in scanned details 11930 pkg.codePath = afterCodeFile.getAbsolutePath(); 11931 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11932 pkg.baseCodePath); 11933 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11934 pkg.splitCodePaths); 11935 11936 // Reflect the rename in app info 11937 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11938 pkg.applicationInfo.setCodePath(pkg.codePath); 11939 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11940 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11941 pkg.applicationInfo.setResourcePath(pkg.codePath); 11942 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11943 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11944 11945 return true; 11946 } 11947 11948 private void setMountPath(String mountPath) { 11949 final File mountFile = new File(mountPath); 11950 11951 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11952 if (monolithicFile.exists()) { 11953 packagePath = monolithicFile.getAbsolutePath(); 11954 if (isFwdLocked()) { 11955 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11956 } else { 11957 resourcePath = packagePath; 11958 } 11959 } else { 11960 packagePath = mountFile.getAbsolutePath(); 11961 resourcePath = packagePath; 11962 } 11963 } 11964 11965 int doPostInstall(int status, int uid) { 11966 if (status != PackageManager.INSTALL_SUCCEEDED) { 11967 cleanUp(); 11968 } else { 11969 final int groupOwner; 11970 final String protectedFile; 11971 if (isFwdLocked()) { 11972 groupOwner = UserHandle.getSharedAppGid(uid); 11973 protectedFile = RES_FILE_NAME; 11974 } else { 11975 groupOwner = -1; 11976 protectedFile = null; 11977 } 11978 11979 if (uid < Process.FIRST_APPLICATION_UID 11980 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11981 Slog.e(TAG, "Failed to finalize " + cid); 11982 PackageHelper.destroySdDir(cid); 11983 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11984 } 11985 11986 boolean mounted = PackageHelper.isContainerMounted(cid); 11987 if (!mounted) { 11988 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11989 } 11990 } 11991 return status; 11992 } 11993 11994 private void cleanUp() { 11995 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11996 11997 // Destroy secure container 11998 PackageHelper.destroySdDir(cid); 11999 } 12000 12001 private List<String> getAllCodePaths() { 12002 final File codeFile = new File(getCodePath()); 12003 if (codeFile != null && codeFile.exists()) { 12004 try { 12005 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12006 return pkg.getAllCodePaths(); 12007 } catch (PackageParserException e) { 12008 // Ignored; we tried our best 12009 } 12010 } 12011 return Collections.EMPTY_LIST; 12012 } 12013 12014 void cleanUpResourcesLI() { 12015 // Enumerate all code paths before deleting 12016 cleanUpResourcesLI(getAllCodePaths()); 12017 } 12018 12019 private void cleanUpResourcesLI(List<String> allCodePaths) { 12020 cleanUp(); 12021 removeDexFiles(allCodePaths, instructionSets); 12022 } 12023 12024 String getPackageName() { 12025 return getAsecPackageName(cid); 12026 } 12027 12028 boolean doPostDeleteLI(boolean delete) { 12029 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12030 final List<String> allCodePaths = getAllCodePaths(); 12031 boolean mounted = PackageHelper.isContainerMounted(cid); 12032 if (mounted) { 12033 // Unmount first 12034 if (PackageHelper.unMountSdDir(cid)) { 12035 mounted = false; 12036 } 12037 } 12038 if (!mounted && delete) { 12039 cleanUpResourcesLI(allCodePaths); 12040 } 12041 return !mounted; 12042 } 12043 12044 @Override 12045 int doPreCopy() { 12046 if (isFwdLocked()) { 12047 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12048 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12049 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12050 } 12051 } 12052 12053 return PackageManager.INSTALL_SUCCEEDED; 12054 } 12055 12056 @Override 12057 int doPostCopy(int uid) { 12058 if (isFwdLocked()) { 12059 if (uid < Process.FIRST_APPLICATION_UID 12060 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12061 RES_FILE_NAME)) { 12062 Slog.e(TAG, "Failed to finalize " + cid); 12063 PackageHelper.destroySdDir(cid); 12064 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12065 } 12066 } 12067 12068 return PackageManager.INSTALL_SUCCEEDED; 12069 } 12070 } 12071 12072 /** 12073 * Logic to handle movement of existing installed applications. 12074 */ 12075 class MoveInstallArgs extends InstallArgs { 12076 private File codeFile; 12077 private File resourceFile; 12078 12079 /** New install */ 12080 MoveInstallArgs(InstallParams params) { 12081 super(params.origin, params.move, params.observer, params.installFlags, 12082 params.installerPackageName, params.volumeUuid, 12083 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12084 params.grantedRuntimePermissions, 12085 params.traceMethod, params.traceCookie); 12086 } 12087 12088 int copyApk(IMediaContainerService imcs, boolean temp) { 12089 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12090 + move.fromUuid + " to " + move.toUuid); 12091 synchronized (mInstaller) { 12092 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12093 move.dataAppName, move.appId, move.seinfo) != 0) { 12094 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12095 } 12096 } 12097 12098 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12099 resourceFile = codeFile; 12100 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12101 12102 return PackageManager.INSTALL_SUCCEEDED; 12103 } 12104 12105 int doPreInstall(int status) { 12106 if (status != PackageManager.INSTALL_SUCCEEDED) { 12107 cleanUp(move.toUuid); 12108 } 12109 return status; 12110 } 12111 12112 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12113 if (status != PackageManager.INSTALL_SUCCEEDED) { 12114 cleanUp(move.toUuid); 12115 return false; 12116 } 12117 12118 // Reflect the move in app info 12119 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12120 pkg.applicationInfo.setCodePath(pkg.codePath); 12121 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12122 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12123 pkg.applicationInfo.setResourcePath(pkg.codePath); 12124 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12125 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12126 12127 return true; 12128 } 12129 12130 int doPostInstall(int status, int uid) { 12131 if (status == PackageManager.INSTALL_SUCCEEDED) { 12132 cleanUp(move.fromUuid); 12133 } else { 12134 cleanUp(move.toUuid); 12135 } 12136 return status; 12137 } 12138 12139 @Override 12140 String getCodePath() { 12141 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12142 } 12143 12144 @Override 12145 String getResourcePath() { 12146 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12147 } 12148 12149 private boolean cleanUp(String volumeUuid) { 12150 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12151 move.dataAppName); 12152 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12153 synchronized (mInstallLock) { 12154 // Clean up both app data and code 12155 removeDataDirsLI(volumeUuid, move.packageName); 12156 if (codeFile.isDirectory()) { 12157 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12158 } else { 12159 codeFile.delete(); 12160 } 12161 } 12162 return true; 12163 } 12164 12165 void cleanUpResourcesLI() { 12166 throw new UnsupportedOperationException(); 12167 } 12168 12169 boolean doPostDeleteLI(boolean delete) { 12170 throw new UnsupportedOperationException(); 12171 } 12172 } 12173 12174 static String getAsecPackageName(String packageCid) { 12175 int idx = packageCid.lastIndexOf("-"); 12176 if (idx == -1) { 12177 return packageCid; 12178 } 12179 return packageCid.substring(0, idx); 12180 } 12181 12182 // Utility method used to create code paths based on package name and available index. 12183 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12184 String idxStr = ""; 12185 int idx = 1; 12186 // Fall back to default value of idx=1 if prefix is not 12187 // part of oldCodePath 12188 if (oldCodePath != null) { 12189 String subStr = oldCodePath; 12190 // Drop the suffix right away 12191 if (suffix != null && subStr.endsWith(suffix)) { 12192 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12193 } 12194 // If oldCodePath already contains prefix find out the 12195 // ending index to either increment or decrement. 12196 int sidx = subStr.lastIndexOf(prefix); 12197 if (sidx != -1) { 12198 subStr = subStr.substring(sidx + prefix.length()); 12199 if (subStr != null) { 12200 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12201 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12202 } 12203 try { 12204 idx = Integer.parseInt(subStr); 12205 if (idx <= 1) { 12206 idx++; 12207 } else { 12208 idx--; 12209 } 12210 } catch(NumberFormatException e) { 12211 } 12212 } 12213 } 12214 } 12215 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12216 return prefix + idxStr; 12217 } 12218 12219 private File getNextCodePath(File targetDir, String packageName) { 12220 int suffix = 1; 12221 File result; 12222 do { 12223 result = new File(targetDir, packageName + "-" + suffix); 12224 suffix++; 12225 } while (result.exists()); 12226 return result; 12227 } 12228 12229 // Utility method that returns the relative package path with respect 12230 // to the installation directory. Like say for /data/data/com.test-1.apk 12231 // string com.test-1 is returned. 12232 static String deriveCodePathName(String codePath) { 12233 if (codePath == null) { 12234 return null; 12235 } 12236 final File codeFile = new File(codePath); 12237 final String name = codeFile.getName(); 12238 if (codeFile.isDirectory()) { 12239 return name; 12240 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12241 final int lastDot = name.lastIndexOf('.'); 12242 return name.substring(0, lastDot); 12243 } else { 12244 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12245 return null; 12246 } 12247 } 12248 12249 static class PackageInstalledInfo { 12250 String name; 12251 int uid; 12252 // The set of users that originally had this package installed. 12253 int[] origUsers; 12254 // The set of users that now have this package installed. 12255 int[] newUsers; 12256 PackageParser.Package pkg; 12257 int returnCode; 12258 String returnMsg; 12259 PackageRemovedInfo removedInfo; 12260 12261 public void setError(int code, String msg) { 12262 returnCode = code; 12263 returnMsg = msg; 12264 Slog.w(TAG, msg); 12265 } 12266 12267 public void setError(String msg, PackageParserException e) { 12268 returnCode = e.error; 12269 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12270 Slog.w(TAG, msg, e); 12271 } 12272 12273 public void setError(String msg, PackageManagerException e) { 12274 returnCode = e.error; 12275 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12276 Slog.w(TAG, msg, e); 12277 } 12278 12279 // In some error cases we want to convey more info back to the observer 12280 String origPackage; 12281 String origPermission; 12282 } 12283 12284 /* 12285 * Install a non-existing package. 12286 */ 12287 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12288 UserHandle user, String installerPackageName, String volumeUuid, 12289 PackageInstalledInfo res) { 12290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12291 12292 // Remember this for later, in case we need to rollback this install 12293 String pkgName = pkg.packageName; 12294 12295 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12296 // TODO: b/23350563 12297 final boolean dataDirExists = Environment 12298 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12299 12300 synchronized(mPackages) { 12301 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12302 // A package with the same name is already installed, though 12303 // it has been renamed to an older name. The package we 12304 // are trying to install should be installed as an update to 12305 // the existing one, but that has not been requested, so bail. 12306 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12307 + " without first uninstalling package running as " 12308 + mSettings.mRenamedPackages.get(pkgName)); 12309 return; 12310 } 12311 if (mPackages.containsKey(pkgName)) { 12312 // Don't allow installation over an existing package with the same name. 12313 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12314 + " without first uninstalling."); 12315 return; 12316 } 12317 } 12318 12319 try { 12320 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12321 System.currentTimeMillis(), user); 12322 12323 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12324 // delete the partially installed application. the data directory will have to be 12325 // restored if it was already existing 12326 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12327 // remove package from internal structures. Note that we want deletePackageX to 12328 // delete the package data and cache directories that it created in 12329 // scanPackageLocked, unless those directories existed before we even tried to 12330 // install. 12331 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12332 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12333 res.removedInfo, true); 12334 } 12335 12336 } catch (PackageManagerException e) { 12337 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12338 } 12339 12340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12341 } 12342 12343 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12344 // Can't rotate keys during boot or if sharedUser. 12345 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12346 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12347 return false; 12348 } 12349 // app is using upgradeKeySets; make sure all are valid 12350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12351 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12352 for (int i = 0; i < upgradeKeySets.length; i++) { 12353 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12354 Slog.wtf(TAG, "Package " 12355 + (oldPs.name != null ? oldPs.name : "<null>") 12356 + " contains upgrade-key-set reference to unknown key-set: " 12357 + upgradeKeySets[i] 12358 + " reverting to signatures check."); 12359 return false; 12360 } 12361 } 12362 return true; 12363 } 12364 12365 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12366 // Upgrade keysets are being used. Determine if new package has a superset of the 12367 // required keys. 12368 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12369 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12370 for (int i = 0; i < upgradeKeySets.length; i++) { 12371 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12372 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12373 return true; 12374 } 12375 } 12376 return false; 12377 } 12378 12379 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12380 UserHandle user, String installerPackageName, String volumeUuid, 12381 PackageInstalledInfo res) { 12382 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12383 12384 final PackageParser.Package oldPackage; 12385 final String pkgName = pkg.packageName; 12386 final int[] allUsers; 12387 final boolean[] perUserInstalled; 12388 12389 // First find the old package info and check signatures 12390 synchronized(mPackages) { 12391 oldPackage = mPackages.get(pkgName); 12392 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12393 if (isEphemeral && !oldIsEphemeral) { 12394 // can't downgrade from full to ephemeral 12395 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12396 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12397 return; 12398 } 12399 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12400 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12401 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12402 if(!checkUpgradeKeySetLP(ps, pkg)) { 12403 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12404 "New package not signed by keys specified by upgrade-keysets: " 12405 + pkgName); 12406 return; 12407 } 12408 } else { 12409 // default to original signature matching 12410 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12411 != PackageManager.SIGNATURE_MATCH) { 12412 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12413 "New package has a different signature: " + pkgName); 12414 return; 12415 } 12416 } 12417 12418 // In case of rollback, remember per-user/profile install state 12419 allUsers = sUserManager.getUserIds(); 12420 perUserInstalled = new boolean[allUsers.length]; 12421 for (int i = 0; i < allUsers.length; i++) { 12422 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12423 } 12424 } 12425 12426 boolean sysPkg = (isSystemApp(oldPackage)); 12427 if (sysPkg) { 12428 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12429 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12430 } else { 12431 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12432 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12433 } 12434 } 12435 12436 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12437 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12438 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12439 String volumeUuid, PackageInstalledInfo res) { 12440 String pkgName = deletedPackage.packageName; 12441 boolean deletedPkg = true; 12442 boolean updatedSettings = false; 12443 12444 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12445 + deletedPackage); 12446 long origUpdateTime; 12447 if (pkg.mExtras != null) { 12448 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12449 } else { 12450 origUpdateTime = 0; 12451 } 12452 12453 // First delete the existing package while retaining the data directory 12454 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12455 res.removedInfo, true)) { 12456 // If the existing package wasn't successfully deleted 12457 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12458 deletedPkg = false; 12459 } else { 12460 // Successfully deleted the old package; proceed with replace. 12461 12462 // If deleted package lived in a container, give users a chance to 12463 // relinquish resources before killing. 12464 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12465 if (DEBUG_INSTALL) { 12466 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12467 } 12468 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12469 final ArrayList<String> pkgList = new ArrayList<String>(1); 12470 pkgList.add(deletedPackage.applicationInfo.packageName); 12471 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12472 } 12473 12474 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12475 try { 12476 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12477 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12478 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12479 perUserInstalled, res, user); 12480 updatedSettings = true; 12481 } catch (PackageManagerException e) { 12482 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12483 } 12484 } 12485 12486 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12487 // remove package from internal structures. Note that we want deletePackageX to 12488 // delete the package data and cache directories that it created in 12489 // scanPackageLocked, unless those directories existed before we even tried to 12490 // install. 12491 if(updatedSettings) { 12492 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12493 deletePackageLI( 12494 pkgName, null, true, allUsers, perUserInstalled, 12495 PackageManager.DELETE_KEEP_DATA, 12496 res.removedInfo, true); 12497 } 12498 // Since we failed to install the new package we need to restore the old 12499 // package that we deleted. 12500 if (deletedPkg) { 12501 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12502 File restoreFile = new File(deletedPackage.codePath); 12503 // Parse old package 12504 boolean oldExternal = isExternal(deletedPackage); 12505 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12506 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12507 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12508 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12509 try { 12510 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12511 null); 12512 } catch (PackageManagerException e) { 12513 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12514 + e.getMessage()); 12515 return; 12516 } 12517 // Restore of old package succeeded. Update permissions. 12518 // writer 12519 synchronized (mPackages) { 12520 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12521 UPDATE_PERMISSIONS_ALL); 12522 // can downgrade to reader 12523 mSettings.writeLPr(); 12524 } 12525 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12526 } 12527 } 12528 } 12529 12530 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12531 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12532 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12533 String volumeUuid, PackageInstalledInfo res) { 12534 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12535 + ", old=" + deletedPackage); 12536 boolean disabledSystem = false; 12537 boolean updatedSettings = false; 12538 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12539 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12540 != 0) { 12541 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12542 } 12543 String packageName = deletedPackage.packageName; 12544 if (packageName == null) { 12545 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12546 "Attempt to delete null packageName."); 12547 return; 12548 } 12549 PackageParser.Package oldPkg; 12550 PackageSetting oldPkgSetting; 12551 // reader 12552 synchronized (mPackages) { 12553 oldPkg = mPackages.get(packageName); 12554 oldPkgSetting = mSettings.mPackages.get(packageName); 12555 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12556 (oldPkgSetting == null)) { 12557 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12558 "Couldn't find package " + packageName + " information"); 12559 return; 12560 } 12561 } 12562 12563 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12564 12565 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12566 res.removedInfo.removedPackage = packageName; 12567 // Remove existing system package 12568 removePackageLI(oldPkgSetting, true); 12569 // writer 12570 synchronized (mPackages) { 12571 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12572 if (!disabledSystem && deletedPackage != null) { 12573 // We didn't need to disable the .apk as a current system package, 12574 // which means we are replacing another update that is already 12575 // installed. We need to make sure to delete the older one's .apk. 12576 res.removedInfo.args = createInstallArgsForExisting(0, 12577 deletedPackage.applicationInfo.getCodePath(), 12578 deletedPackage.applicationInfo.getResourcePath(), 12579 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12580 } else { 12581 res.removedInfo.args = null; 12582 } 12583 } 12584 12585 // Successfully disabled the old package. Now proceed with re-installation 12586 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12587 12588 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12589 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12590 12591 PackageParser.Package newPackage = null; 12592 try { 12593 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12594 if (newPackage.mExtras != null) { 12595 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12596 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12597 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12598 12599 // is the update attempting to change shared user? that isn't going to work... 12600 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12601 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12602 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12603 + " to " + newPkgSetting.sharedUser); 12604 updatedSettings = true; 12605 } 12606 } 12607 12608 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12609 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12610 perUserInstalled, res, user); 12611 updatedSettings = true; 12612 } 12613 12614 } catch (PackageManagerException e) { 12615 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12616 } 12617 12618 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12619 // Re installation failed. Restore old information 12620 // Remove new pkg information 12621 if (newPackage != null) { 12622 removeInstalledPackageLI(newPackage, true); 12623 } 12624 // Add back the old system package 12625 try { 12626 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12627 } catch (PackageManagerException e) { 12628 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12629 } 12630 // Restore the old system information in Settings 12631 synchronized (mPackages) { 12632 if (disabledSystem) { 12633 mSettings.enableSystemPackageLPw(packageName); 12634 } 12635 if (updatedSettings) { 12636 mSettings.setInstallerPackageName(packageName, 12637 oldPkgSetting.installerPackageName); 12638 } 12639 mSettings.writeLPr(); 12640 } 12641 } 12642 } 12643 12644 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12645 // Collect all used permissions in the UID 12646 ArraySet<String> usedPermissions = new ArraySet<>(); 12647 final int packageCount = su.packages.size(); 12648 for (int i = 0; i < packageCount; i++) { 12649 PackageSetting ps = su.packages.valueAt(i); 12650 if (ps.pkg == null) { 12651 continue; 12652 } 12653 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12654 for (int j = 0; j < requestedPermCount; j++) { 12655 String permission = ps.pkg.requestedPermissions.get(j); 12656 BasePermission bp = mSettings.mPermissions.get(permission); 12657 if (bp != null) { 12658 usedPermissions.add(permission); 12659 } 12660 } 12661 } 12662 12663 PermissionsState permissionsState = su.getPermissionsState(); 12664 // Prune install permissions 12665 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12666 final int installPermCount = installPermStates.size(); 12667 for (int i = installPermCount - 1; i >= 0; i--) { 12668 PermissionState permissionState = installPermStates.get(i); 12669 if (!usedPermissions.contains(permissionState.getName())) { 12670 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12671 if (bp != null) { 12672 permissionsState.revokeInstallPermission(bp); 12673 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12674 PackageManager.MASK_PERMISSION_FLAGS, 0); 12675 } 12676 } 12677 } 12678 12679 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12680 12681 // Prune runtime permissions 12682 for (int userId : allUserIds) { 12683 List<PermissionState> runtimePermStates = permissionsState 12684 .getRuntimePermissionStates(userId); 12685 final int runtimePermCount = runtimePermStates.size(); 12686 for (int i = runtimePermCount - 1; i >= 0; i--) { 12687 PermissionState permissionState = runtimePermStates.get(i); 12688 if (!usedPermissions.contains(permissionState.getName())) { 12689 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12690 if (bp != null) { 12691 permissionsState.revokeRuntimePermission(bp, userId); 12692 permissionsState.updatePermissionFlags(bp, userId, 12693 PackageManager.MASK_PERMISSION_FLAGS, 0); 12694 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12695 runtimePermissionChangedUserIds, userId); 12696 } 12697 } 12698 } 12699 } 12700 12701 return runtimePermissionChangedUserIds; 12702 } 12703 12704 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12705 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12706 UserHandle user) { 12707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12708 12709 String pkgName = newPackage.packageName; 12710 synchronized (mPackages) { 12711 //write settings. the installStatus will be incomplete at this stage. 12712 //note that the new package setting would have already been 12713 //added to mPackages. It hasn't been persisted yet. 12714 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12716 mSettings.writeLPr(); 12717 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12718 } 12719 12720 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12721 synchronized (mPackages) { 12722 updatePermissionsLPw(newPackage.packageName, newPackage, 12723 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12724 ? UPDATE_PERMISSIONS_ALL : 0)); 12725 // For system-bundled packages, we assume that installing an upgraded version 12726 // of the package implies that the user actually wants to run that new code, 12727 // so we enable the package. 12728 PackageSetting ps = mSettings.mPackages.get(pkgName); 12729 if (ps != null) { 12730 if (isSystemApp(newPackage)) { 12731 // NB: implicit assumption that system package upgrades apply to all users 12732 if (DEBUG_INSTALL) { 12733 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12734 } 12735 if (res.origUsers != null) { 12736 for (int userHandle : res.origUsers) { 12737 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12738 userHandle, installerPackageName); 12739 } 12740 } 12741 // Also convey the prior install/uninstall state 12742 if (allUsers != null && perUserInstalled != null) { 12743 for (int i = 0; i < allUsers.length; i++) { 12744 if (DEBUG_INSTALL) { 12745 Slog.d(TAG, " user " + allUsers[i] 12746 + " => " + perUserInstalled[i]); 12747 } 12748 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12749 } 12750 // these install state changes will be persisted in the 12751 // upcoming call to mSettings.writeLPr(). 12752 } 12753 } 12754 // It's implied that when a user requests installation, they want the app to be 12755 // installed and enabled. 12756 int userId = user.getIdentifier(); 12757 if (userId != UserHandle.USER_ALL) { 12758 ps.setInstalled(true, userId); 12759 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12760 } 12761 } 12762 res.name = pkgName; 12763 res.uid = newPackage.applicationInfo.uid; 12764 res.pkg = newPackage; 12765 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12766 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12767 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12768 //to update install status 12769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12770 mSettings.writeLPr(); 12771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12772 } 12773 12774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12775 } 12776 12777 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12778 try { 12779 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12780 installPackageLI(args, res); 12781 } finally { 12782 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12783 } 12784 } 12785 12786 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12787 final int installFlags = args.installFlags; 12788 final String installerPackageName = args.installerPackageName; 12789 final String volumeUuid = args.volumeUuid; 12790 final File tmpPackageFile = new File(args.getCodePath()); 12791 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12792 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12793 || (args.volumeUuid != null)); 12794 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12795 boolean replace = false; 12796 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12797 if (args.move != null) { 12798 // moving a complete application; perfom an initial scan on the new install location 12799 scanFlags |= SCAN_INITIAL; 12800 } 12801 // Result object to be returned 12802 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12803 12804 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12805 12806 // Sanity check 12807 if (ephemeral && (forwardLocked || onExternal)) { 12808 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12809 + " external=" + onExternal); 12810 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12811 return; 12812 } 12813 12814 // Retrieve PackageSettings and parse package 12815 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12816 | PackageParser.PARSE_ENFORCE_CODE 12817 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12818 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12819 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12820 PackageParser pp = new PackageParser(); 12821 pp.setSeparateProcesses(mSeparateProcesses); 12822 pp.setDisplayMetrics(mMetrics); 12823 12824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12825 final PackageParser.Package pkg; 12826 try { 12827 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12828 } catch (PackageParserException e) { 12829 res.setError("Failed parse during installPackageLI", e); 12830 return; 12831 } finally { 12832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12833 } 12834 12835 // Mark that we have an install time CPU ABI override. 12836 pkg.cpuAbiOverride = args.abiOverride; 12837 12838 String pkgName = res.name = pkg.packageName; 12839 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12840 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12841 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12842 return; 12843 } 12844 } 12845 12846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12847 try { 12848 pp.collectCertificates(pkg, parseFlags); 12849 } catch (PackageParserException e) { 12850 res.setError("Failed collect during installPackageLI", e); 12851 return; 12852 } finally { 12853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12854 } 12855 12856 // Get rid of all references to package scan path via parser. 12857 pp = null; 12858 String oldCodePath = null; 12859 boolean systemApp = false; 12860 synchronized (mPackages) { 12861 // Check if installing already existing package 12862 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12863 String oldName = mSettings.mRenamedPackages.get(pkgName); 12864 if (pkg.mOriginalPackages != null 12865 && pkg.mOriginalPackages.contains(oldName) 12866 && mPackages.containsKey(oldName)) { 12867 // This package is derived from an original package, 12868 // and this device has been updating from that original 12869 // name. We must continue using the original name, so 12870 // rename the new package here. 12871 pkg.setPackageName(oldName); 12872 pkgName = pkg.packageName; 12873 replace = true; 12874 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12875 + oldName + " pkgName=" + pkgName); 12876 } else if (mPackages.containsKey(pkgName)) { 12877 // This package, under its official name, already exists 12878 // on the device; we should replace it. 12879 replace = true; 12880 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12881 } 12882 12883 // Prevent apps opting out from runtime permissions 12884 if (replace) { 12885 PackageParser.Package oldPackage = mPackages.get(pkgName); 12886 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12887 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12888 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12889 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12890 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12891 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12892 + " doesn't support runtime permissions but the old" 12893 + " target SDK " + oldTargetSdk + " does."); 12894 return; 12895 } 12896 } 12897 } 12898 12899 PackageSetting ps = mSettings.mPackages.get(pkgName); 12900 if (ps != null) { 12901 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12902 12903 // Quick sanity check that we're signed correctly if updating; 12904 // we'll check this again later when scanning, but we want to 12905 // bail early here before tripping over redefined permissions. 12906 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12907 if (!checkUpgradeKeySetLP(ps, pkg)) { 12908 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12909 + pkg.packageName + " upgrade keys do not match the " 12910 + "previously installed version"); 12911 return; 12912 } 12913 } else { 12914 try { 12915 verifySignaturesLP(ps, pkg); 12916 } catch (PackageManagerException e) { 12917 res.setError(e.error, e.getMessage()); 12918 return; 12919 } 12920 } 12921 12922 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12923 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12924 systemApp = (ps.pkg.applicationInfo.flags & 12925 ApplicationInfo.FLAG_SYSTEM) != 0; 12926 } 12927 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12928 } 12929 12930 // Check whether the newly-scanned package wants to define an already-defined perm 12931 int N = pkg.permissions.size(); 12932 for (int i = N-1; i >= 0; i--) { 12933 PackageParser.Permission perm = pkg.permissions.get(i); 12934 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12935 if (bp != null) { 12936 // If the defining package is signed with our cert, it's okay. This 12937 // also includes the "updating the same package" case, of course. 12938 // "updating same package" could also involve key-rotation. 12939 final boolean sigsOk; 12940 if (bp.sourcePackage.equals(pkg.packageName) 12941 && (bp.packageSetting instanceof PackageSetting) 12942 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12943 scanFlags))) { 12944 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12945 } else { 12946 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12947 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12948 } 12949 if (!sigsOk) { 12950 // If the owning package is the system itself, we log but allow 12951 // install to proceed; we fail the install on all other permission 12952 // redefinitions. 12953 if (!bp.sourcePackage.equals("android")) { 12954 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12955 + pkg.packageName + " attempting to redeclare permission " 12956 + perm.info.name + " already owned by " + bp.sourcePackage); 12957 res.origPermission = perm.info.name; 12958 res.origPackage = bp.sourcePackage; 12959 return; 12960 } else { 12961 Slog.w(TAG, "Package " + pkg.packageName 12962 + " attempting to redeclare system permission " 12963 + perm.info.name + "; ignoring new declaration"); 12964 pkg.permissions.remove(i); 12965 } 12966 } 12967 } 12968 } 12969 12970 } 12971 12972 if (systemApp) { 12973 if (onExternal) { 12974 // Abort update; system app can't be replaced with app on sdcard 12975 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12976 "Cannot install updates to system apps on sdcard"); 12977 return; 12978 } else if (ephemeral) { 12979 // Abort update; system app can't be replaced with an ephemeral app 12980 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12981 "Cannot update a system app with an ephemeral app"); 12982 return; 12983 } 12984 } 12985 12986 if (args.move != null) { 12987 // We did an in-place move, so dex is ready to roll 12988 scanFlags |= SCAN_NO_DEX; 12989 scanFlags |= SCAN_MOVE; 12990 12991 synchronized (mPackages) { 12992 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12993 if (ps == null) { 12994 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12995 "Missing settings for moved package " + pkgName); 12996 } 12997 12998 // We moved the entire application as-is, so bring over the 12999 // previously derived ABI information. 13000 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13001 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13002 } 13003 13004 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13005 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13006 scanFlags |= SCAN_NO_DEX; 13007 13008 try { 13009 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13010 true /* extract libs */); 13011 } catch (PackageManagerException pme) { 13012 Slog.e(TAG, "Error deriving application ABI", pme); 13013 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13014 return; 13015 } 13016 } 13017 13018 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13019 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13020 return; 13021 } 13022 13023 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13024 13025 if (replace) { 13026 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13027 installerPackageName, volumeUuid, res); 13028 } else { 13029 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13030 args.user, installerPackageName, volumeUuid, res); 13031 } 13032 synchronized (mPackages) { 13033 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13034 if (ps != null) { 13035 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13036 } 13037 } 13038 } 13039 13040 private void startIntentFilterVerifications(int userId, boolean replacing, 13041 PackageParser.Package pkg) { 13042 if (mIntentFilterVerifierComponent == null) { 13043 Slog.w(TAG, "No IntentFilter verification will not be done as " 13044 + "there is no IntentFilterVerifier available!"); 13045 return; 13046 } 13047 13048 final int verifierUid = getPackageUid( 13049 mIntentFilterVerifierComponent.getPackageName(), 13050 MATCH_DEBUG_TRIAGED_MISSING, 13051 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13052 13053 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13054 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13055 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13056 mHandler.sendMessage(msg); 13057 } 13058 13059 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13060 PackageParser.Package pkg) { 13061 int size = pkg.activities.size(); 13062 if (size == 0) { 13063 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13064 "No activity, so no need to verify any IntentFilter!"); 13065 return; 13066 } 13067 13068 final boolean hasDomainURLs = hasDomainURLs(pkg); 13069 if (!hasDomainURLs) { 13070 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13071 "No domain URLs, so no need to verify any IntentFilter!"); 13072 return; 13073 } 13074 13075 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13076 + " if any IntentFilter from the " + size 13077 + " Activities needs verification ..."); 13078 13079 int count = 0; 13080 final String packageName = pkg.packageName; 13081 13082 synchronized (mPackages) { 13083 // If this is a new install and we see that we've already run verification for this 13084 // package, we have nothing to do: it means the state was restored from backup. 13085 if (!replacing) { 13086 IntentFilterVerificationInfo ivi = 13087 mSettings.getIntentFilterVerificationLPr(packageName); 13088 if (ivi != null) { 13089 if (DEBUG_DOMAIN_VERIFICATION) { 13090 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13091 + ivi.getStatusString()); 13092 } 13093 return; 13094 } 13095 } 13096 13097 // If any filters need to be verified, then all need to be. 13098 boolean needToVerify = false; 13099 for (PackageParser.Activity a : pkg.activities) { 13100 for (ActivityIntentInfo filter : a.intents) { 13101 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13102 if (DEBUG_DOMAIN_VERIFICATION) { 13103 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13104 } 13105 needToVerify = true; 13106 break; 13107 } 13108 } 13109 } 13110 13111 if (needToVerify) { 13112 final int verificationId = mIntentFilterVerificationToken++; 13113 for (PackageParser.Activity a : pkg.activities) { 13114 for (ActivityIntentInfo filter : a.intents) { 13115 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13117 "Verification needed for IntentFilter:" + filter.toString()); 13118 mIntentFilterVerifier.addOneIntentFilterVerification( 13119 verifierUid, userId, verificationId, filter, packageName); 13120 count++; 13121 } 13122 } 13123 } 13124 } 13125 } 13126 13127 if (count > 0) { 13128 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13129 + " IntentFilter verification" + (count > 1 ? "s" : "") 13130 + " for userId:" + userId); 13131 mIntentFilterVerifier.startVerifications(userId); 13132 } else { 13133 if (DEBUG_DOMAIN_VERIFICATION) { 13134 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13135 } 13136 } 13137 } 13138 13139 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13140 final ComponentName cn = filter.activity.getComponentName(); 13141 final String packageName = cn.getPackageName(); 13142 13143 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13144 packageName); 13145 if (ivi == null) { 13146 return true; 13147 } 13148 int status = ivi.getStatus(); 13149 switch (status) { 13150 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13151 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13152 return true; 13153 13154 default: 13155 // Nothing to do 13156 return false; 13157 } 13158 } 13159 13160 private static boolean isMultiArch(ApplicationInfo info) { 13161 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13162 } 13163 13164 private static boolean isExternal(PackageParser.Package pkg) { 13165 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13166 } 13167 13168 private static boolean isExternal(PackageSetting ps) { 13169 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13170 } 13171 13172 private static boolean isEphemeral(PackageParser.Package pkg) { 13173 return pkg.applicationInfo.isEphemeralApp(); 13174 } 13175 13176 private static boolean isEphemeral(PackageSetting ps) { 13177 return ps.pkg != null && isEphemeral(ps.pkg); 13178 } 13179 13180 private static boolean isSystemApp(PackageParser.Package pkg) { 13181 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13182 } 13183 13184 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13185 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13186 } 13187 13188 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13189 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13190 } 13191 13192 private static boolean isSystemApp(PackageSetting ps) { 13193 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13194 } 13195 13196 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13197 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13198 } 13199 13200 private int packageFlagsToInstallFlags(PackageSetting ps) { 13201 int installFlags = 0; 13202 if (isEphemeral(ps)) { 13203 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13204 } 13205 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13206 // This existing package was an external ASEC install when we have 13207 // the external flag without a UUID 13208 installFlags |= PackageManager.INSTALL_EXTERNAL; 13209 } 13210 if (ps.isForwardLocked()) { 13211 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13212 } 13213 return installFlags; 13214 } 13215 13216 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13217 if (isExternal(pkg)) { 13218 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13219 return StorageManager.UUID_PRIMARY_PHYSICAL; 13220 } else { 13221 return pkg.volumeUuid; 13222 } 13223 } else { 13224 return StorageManager.UUID_PRIVATE_INTERNAL; 13225 } 13226 } 13227 13228 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13229 if (isExternal(pkg)) { 13230 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13231 return mSettings.getExternalVersion(); 13232 } else { 13233 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13234 } 13235 } else { 13236 return mSettings.getInternalVersion(); 13237 } 13238 } 13239 13240 private void deleteTempPackageFiles() { 13241 final FilenameFilter filter = new FilenameFilter() { 13242 public boolean accept(File dir, String name) { 13243 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13244 } 13245 }; 13246 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13247 file.delete(); 13248 } 13249 } 13250 13251 @Override 13252 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13253 int flags) { 13254 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13255 flags); 13256 } 13257 13258 @Override 13259 public void deletePackage(final String packageName, 13260 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13261 mContext.enforceCallingOrSelfPermission( 13262 android.Manifest.permission.DELETE_PACKAGES, null); 13263 Preconditions.checkNotNull(packageName); 13264 Preconditions.checkNotNull(observer); 13265 final int uid = Binder.getCallingUid(); 13266 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13267 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13268 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13269 mContext.enforceCallingOrSelfPermission( 13270 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13271 "deletePackage for user " + userId); 13272 } 13273 13274 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13275 try { 13276 observer.onPackageDeleted(packageName, 13277 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13278 } catch (RemoteException re) { 13279 } 13280 return; 13281 } 13282 13283 for (int currentUserId : users) { 13284 if (getBlockUninstallForUser(packageName, currentUserId)) { 13285 try { 13286 observer.onPackageDeleted(packageName, 13287 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13288 } catch (RemoteException re) { 13289 } 13290 return; 13291 } 13292 } 13293 13294 if (DEBUG_REMOVE) { 13295 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13296 } 13297 // Queue up an async operation since the package deletion may take a little while. 13298 mHandler.post(new Runnable() { 13299 public void run() { 13300 mHandler.removeCallbacks(this); 13301 final int returnCode = deletePackageX(packageName, userId, flags); 13302 try { 13303 observer.onPackageDeleted(packageName, returnCode, null); 13304 } catch (RemoteException e) { 13305 Log.i(TAG, "Observer no longer exists."); 13306 } //end catch 13307 } //end run 13308 }); 13309 } 13310 13311 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13312 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13313 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13314 try { 13315 if (dpm != null) { 13316 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13317 /* callingUserOnly =*/ false); 13318 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13319 : deviceOwnerComponentName.getPackageName(); 13320 // Does the package contains the device owner? 13321 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13322 // this check is probably not needed, since DO should be registered as a device 13323 // admin on some user too. (Original bug for this: b/17657954) 13324 if (packageName.equals(deviceOwnerPackageName)) { 13325 return true; 13326 } 13327 // Does it contain a device admin for any user? 13328 int[] users; 13329 if (userId == UserHandle.USER_ALL) { 13330 users = sUserManager.getUserIds(); 13331 } else { 13332 users = new int[]{userId}; 13333 } 13334 for (int i = 0; i < users.length; ++i) { 13335 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13336 return true; 13337 } 13338 } 13339 } 13340 } catch (RemoteException e) { 13341 } 13342 return false; 13343 } 13344 13345 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13346 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13347 } 13348 13349 /** 13350 * This method is an internal method that could be get invoked either 13351 * to delete an installed package or to clean up a failed installation. 13352 * After deleting an installed package, a broadcast is sent to notify any 13353 * listeners that the package has been installed. For cleaning up a failed 13354 * installation, the broadcast is not necessary since the package's 13355 * installation wouldn't have sent the initial broadcast either 13356 * The key steps in deleting a package are 13357 * deleting the package information in internal structures like mPackages, 13358 * deleting the packages base directories through installd 13359 * updating mSettings to reflect current status 13360 * persisting settings for later use 13361 * sending a broadcast if necessary 13362 */ 13363 private int deletePackageX(String packageName, int userId, int flags) { 13364 final PackageRemovedInfo info = new PackageRemovedInfo(); 13365 final boolean res; 13366 13367 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13368 ? UserHandle.ALL : new UserHandle(userId); 13369 13370 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13371 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13372 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13373 } 13374 13375 boolean removedForAllUsers = false; 13376 boolean systemUpdate = false; 13377 13378 PackageParser.Package uninstalledPkg; 13379 13380 // for the uninstall-updates case and restricted profiles, remember the per- 13381 // userhandle installed state 13382 int[] allUsers; 13383 boolean[] perUserInstalled; 13384 synchronized (mPackages) { 13385 uninstalledPkg = mPackages.get(packageName); 13386 PackageSetting ps = mSettings.mPackages.get(packageName); 13387 allUsers = sUserManager.getUserIds(); 13388 perUserInstalled = new boolean[allUsers.length]; 13389 for (int i = 0; i < allUsers.length; i++) { 13390 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13391 } 13392 } 13393 13394 synchronized (mInstallLock) { 13395 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13396 res = deletePackageLI(packageName, removeForUser, 13397 true, allUsers, perUserInstalled, 13398 flags | REMOVE_CHATTY, info, true); 13399 systemUpdate = info.isRemovedPackageSystemUpdate; 13400 synchronized (mPackages) { 13401 if (res) { 13402 if (!systemUpdate && mPackages.get(packageName) == null) { 13403 removedForAllUsers = true; 13404 } 13405 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13406 } 13407 } 13408 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13409 + " removedForAllUsers=" + removedForAllUsers); 13410 } 13411 13412 if (res) { 13413 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13414 13415 // If the removed package was a system update, the old system package 13416 // was re-enabled; we need to broadcast this information 13417 if (systemUpdate) { 13418 Bundle extras = new Bundle(1); 13419 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13420 ? info.removedAppId : info.uid); 13421 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13422 13423 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13424 extras, 0, null, null, null); 13425 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13426 extras, 0, null, null, null); 13427 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13428 null, 0, packageName, null, null); 13429 } 13430 } 13431 // Force a gc here. 13432 Runtime.getRuntime().gc(); 13433 // Delete the resources here after sending the broadcast to let 13434 // other processes clean up before deleting resources. 13435 if (info.args != null) { 13436 synchronized (mInstallLock) { 13437 info.args.doPostDeleteLI(true); 13438 } 13439 } 13440 13441 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13442 } 13443 13444 class PackageRemovedInfo { 13445 String removedPackage; 13446 int uid = -1; 13447 int removedAppId = -1; 13448 int[] removedUsers = null; 13449 boolean isRemovedPackageSystemUpdate = false; 13450 // Clean up resources deleted packages. 13451 InstallArgs args = null; 13452 13453 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13454 Bundle extras = new Bundle(1); 13455 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13456 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13457 if (replacing) { 13458 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13459 } 13460 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13461 if (removedPackage != null) { 13462 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13463 extras, 0, null, null, removedUsers); 13464 if (fullRemove && !replacing) { 13465 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13466 extras, 0, null, null, removedUsers); 13467 } 13468 } 13469 if (removedAppId >= 0) { 13470 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13471 removedUsers); 13472 } 13473 } 13474 } 13475 13476 /* 13477 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13478 * flag is not set, the data directory is removed as well. 13479 * make sure this flag is set for partially installed apps. If not its meaningless to 13480 * delete a partially installed application. 13481 */ 13482 private void removePackageDataLI(PackageSetting ps, 13483 int[] allUserHandles, boolean[] perUserInstalled, 13484 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13485 String packageName = ps.name; 13486 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13487 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13488 // Retrieve object to delete permissions for shared user later on 13489 final PackageSetting deletedPs; 13490 // reader 13491 synchronized (mPackages) { 13492 deletedPs = mSettings.mPackages.get(packageName); 13493 if (outInfo != null) { 13494 outInfo.removedPackage = packageName; 13495 outInfo.removedUsers = deletedPs != null 13496 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13497 : null; 13498 } 13499 } 13500 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13501 removeDataDirsLI(ps.volumeUuid, packageName); 13502 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13503 } 13504 // writer 13505 synchronized (mPackages) { 13506 if (deletedPs != null) { 13507 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13508 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13509 clearDefaultBrowserIfNeeded(packageName); 13510 if (outInfo != null) { 13511 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13512 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13513 } 13514 updatePermissionsLPw(deletedPs.name, null, 0); 13515 if (deletedPs.sharedUser != null) { 13516 // Remove permissions associated with package. Since runtime 13517 // permissions are per user we have to kill the removed package 13518 // or packages running under the shared user of the removed 13519 // package if revoking the permissions requested only by the removed 13520 // package is successful and this causes a change in gids. 13521 for (int userId : UserManagerService.getInstance().getUserIds()) { 13522 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13523 userId); 13524 if (userIdToKill == UserHandle.USER_ALL 13525 || userIdToKill >= UserHandle.USER_SYSTEM) { 13526 // If gids changed for this user, kill all affected packages. 13527 mHandler.post(new Runnable() { 13528 @Override 13529 public void run() { 13530 // This has to happen with no lock held. 13531 killApplication(deletedPs.name, deletedPs.appId, 13532 KILL_APP_REASON_GIDS_CHANGED); 13533 } 13534 }); 13535 break; 13536 } 13537 } 13538 } 13539 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13540 } 13541 // make sure to preserve per-user disabled state if this removal was just 13542 // a downgrade of a system app to the factory package 13543 if (allUserHandles != null && perUserInstalled != null) { 13544 if (DEBUG_REMOVE) { 13545 Slog.d(TAG, "Propagating install state across downgrade"); 13546 } 13547 for (int i = 0; i < allUserHandles.length; i++) { 13548 if (DEBUG_REMOVE) { 13549 Slog.d(TAG, " user " + allUserHandles[i] 13550 + " => " + perUserInstalled[i]); 13551 } 13552 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13553 } 13554 } 13555 } 13556 // can downgrade to reader 13557 if (writeSettings) { 13558 // Save settings now 13559 mSettings.writeLPr(); 13560 } 13561 } 13562 if (outInfo != null) { 13563 // A user ID was deleted here. Go through all users and remove it 13564 // from KeyStore. 13565 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13566 } 13567 } 13568 13569 static boolean locationIsPrivileged(File path) { 13570 try { 13571 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13572 .getCanonicalPath(); 13573 return path.getCanonicalPath().startsWith(privilegedAppDir); 13574 } catch (IOException e) { 13575 Slog.e(TAG, "Unable to access code path " + path); 13576 } 13577 return false; 13578 } 13579 13580 /* 13581 * Tries to delete system package. 13582 */ 13583 private boolean deleteSystemPackageLI(PackageSetting newPs, 13584 int[] allUserHandles, boolean[] perUserInstalled, 13585 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13586 final boolean applyUserRestrictions 13587 = (allUserHandles != null) && (perUserInstalled != null); 13588 PackageSetting disabledPs = null; 13589 // Confirm if the system package has been updated 13590 // An updated system app can be deleted. This will also have to restore 13591 // the system pkg from system partition 13592 // reader 13593 synchronized (mPackages) { 13594 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13595 } 13596 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13597 + " disabledPs=" + disabledPs); 13598 if (disabledPs == null) { 13599 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13600 return false; 13601 } else if (DEBUG_REMOVE) { 13602 Slog.d(TAG, "Deleting system pkg from data partition"); 13603 } 13604 if (DEBUG_REMOVE) { 13605 if (applyUserRestrictions) { 13606 Slog.d(TAG, "Remembering install states:"); 13607 for (int i = 0; i < allUserHandles.length; i++) { 13608 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13609 } 13610 } 13611 } 13612 // Delete the updated package 13613 outInfo.isRemovedPackageSystemUpdate = true; 13614 if (disabledPs.versionCode < newPs.versionCode) { 13615 // Delete data for downgrades 13616 flags &= ~PackageManager.DELETE_KEEP_DATA; 13617 } else { 13618 // Preserve data by setting flag 13619 flags |= PackageManager.DELETE_KEEP_DATA; 13620 } 13621 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13622 allUserHandles, perUserInstalled, outInfo, writeSettings); 13623 if (!ret) { 13624 return false; 13625 } 13626 // writer 13627 synchronized (mPackages) { 13628 // Reinstate the old system package 13629 mSettings.enableSystemPackageLPw(newPs.name); 13630 // Remove any native libraries from the upgraded package. 13631 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13632 } 13633 // Install the system package 13634 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13635 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13636 if (locationIsPrivileged(disabledPs.codePath)) { 13637 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13638 } 13639 13640 final PackageParser.Package newPkg; 13641 try { 13642 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13643 } catch (PackageManagerException e) { 13644 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13645 return false; 13646 } 13647 13648 // writer 13649 synchronized (mPackages) { 13650 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13651 13652 // Propagate the permissions state as we do not want to drop on the floor 13653 // runtime permissions. The update permissions method below will take 13654 // care of removing obsolete permissions and grant install permissions. 13655 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13656 updatePermissionsLPw(newPkg.packageName, newPkg, 13657 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13658 13659 if (applyUserRestrictions) { 13660 if (DEBUG_REMOVE) { 13661 Slog.d(TAG, "Propagating install state across reinstall"); 13662 } 13663 for (int i = 0; i < allUserHandles.length; i++) { 13664 if (DEBUG_REMOVE) { 13665 Slog.d(TAG, " user " + allUserHandles[i] 13666 + " => " + perUserInstalled[i]); 13667 } 13668 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13669 13670 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13671 } 13672 // Regardless of writeSettings we need to ensure that this restriction 13673 // state propagation is persisted 13674 mSettings.writeAllUsersPackageRestrictionsLPr(); 13675 } 13676 // can downgrade to reader here 13677 if (writeSettings) { 13678 mSettings.writeLPr(); 13679 } 13680 } 13681 return true; 13682 } 13683 13684 private boolean deleteInstalledPackageLI(PackageSetting ps, 13685 boolean deleteCodeAndResources, int flags, 13686 int[] allUserHandles, boolean[] perUserInstalled, 13687 PackageRemovedInfo outInfo, boolean writeSettings) { 13688 if (outInfo != null) { 13689 outInfo.uid = ps.appId; 13690 } 13691 13692 // Delete package data from internal structures and also remove data if flag is set 13693 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13694 13695 // Delete application code and resources 13696 if (deleteCodeAndResources && (outInfo != null)) { 13697 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13698 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13699 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13700 } 13701 return true; 13702 } 13703 13704 @Override 13705 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13706 int userId) { 13707 mContext.enforceCallingOrSelfPermission( 13708 android.Manifest.permission.DELETE_PACKAGES, null); 13709 synchronized (mPackages) { 13710 PackageSetting ps = mSettings.mPackages.get(packageName); 13711 if (ps == null) { 13712 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13713 return false; 13714 } 13715 if (!ps.getInstalled(userId)) { 13716 // Can't block uninstall for an app that is not installed or enabled. 13717 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13718 return false; 13719 } 13720 ps.setBlockUninstall(blockUninstall, userId); 13721 mSettings.writePackageRestrictionsLPr(userId); 13722 } 13723 return true; 13724 } 13725 13726 @Override 13727 public boolean getBlockUninstallForUser(String packageName, int userId) { 13728 synchronized (mPackages) { 13729 PackageSetting ps = mSettings.mPackages.get(packageName); 13730 if (ps == null) { 13731 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13732 return false; 13733 } 13734 return ps.getBlockUninstall(userId); 13735 } 13736 } 13737 13738 @Override 13739 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13740 int callingUid = Binder.getCallingUid(); 13741 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13742 throw new SecurityException( 13743 "setRequiredForSystemUser can only be run by the system or root"); 13744 } 13745 synchronized (mPackages) { 13746 PackageSetting ps = mSettings.mPackages.get(packageName); 13747 if (ps == null) { 13748 Log.w(TAG, "Package doesn't exist: " + packageName); 13749 return false; 13750 } 13751 if (systemUserApp) { 13752 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13753 } else { 13754 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13755 } 13756 mSettings.writeLPr(); 13757 } 13758 return true; 13759 } 13760 13761 /* 13762 * This method handles package deletion in general 13763 */ 13764 private boolean deletePackageLI(String packageName, UserHandle user, 13765 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13766 int flags, PackageRemovedInfo outInfo, 13767 boolean writeSettings) { 13768 if (packageName == null) { 13769 Slog.w(TAG, "Attempt to delete null packageName."); 13770 return false; 13771 } 13772 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13773 PackageSetting ps; 13774 boolean dataOnly = false; 13775 int removeUser = -1; 13776 int appId = -1; 13777 synchronized (mPackages) { 13778 ps = mSettings.mPackages.get(packageName); 13779 if (ps == null) { 13780 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13781 return false; 13782 } 13783 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13784 && user.getIdentifier() != UserHandle.USER_ALL) { 13785 // The caller is asking that the package only be deleted for a single 13786 // user. To do this, we just mark its uninstalled state and delete 13787 // its data. If this is a system app, we only allow this to happen if 13788 // they have set the special DELETE_SYSTEM_APP which requests different 13789 // semantics than normal for uninstalling system apps. 13790 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13791 final int userId = user.getIdentifier(); 13792 ps.setUserState(userId, 13793 COMPONENT_ENABLED_STATE_DEFAULT, 13794 false, //installed 13795 true, //stopped 13796 true, //notLaunched 13797 false, //hidden 13798 false, //suspended 13799 null, null, null, 13800 false, // blockUninstall 13801 ps.readUserState(userId).domainVerificationStatus, 0); 13802 if (!isSystemApp(ps)) { 13803 // Do not uninstall the APK if an app should be cached 13804 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13805 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13806 // Other user still have this package installed, so all 13807 // we need to do is clear this user's data and save that 13808 // it is uninstalled. 13809 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13810 removeUser = user.getIdentifier(); 13811 appId = ps.appId; 13812 scheduleWritePackageRestrictionsLocked(removeUser); 13813 } else { 13814 // We need to set it back to 'installed' so the uninstall 13815 // broadcasts will be sent correctly. 13816 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13817 ps.setInstalled(true, user.getIdentifier()); 13818 } 13819 } else { 13820 // This is a system app, so we assume that the 13821 // other users still have this package installed, so all 13822 // we need to do is clear this user's data and save that 13823 // it is uninstalled. 13824 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13825 removeUser = user.getIdentifier(); 13826 appId = ps.appId; 13827 scheduleWritePackageRestrictionsLocked(removeUser); 13828 } 13829 } 13830 } 13831 13832 if (removeUser >= 0) { 13833 // From above, we determined that we are deleting this only 13834 // for a single user. Continue the work here. 13835 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13836 if (outInfo != null) { 13837 outInfo.removedPackage = packageName; 13838 outInfo.removedAppId = appId; 13839 outInfo.removedUsers = new int[] {removeUser}; 13840 } 13841 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13842 removeKeystoreDataIfNeeded(removeUser, appId); 13843 schedulePackageCleaning(packageName, removeUser, false); 13844 synchronized (mPackages) { 13845 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13846 scheduleWritePackageRestrictionsLocked(removeUser); 13847 } 13848 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13849 } 13850 return true; 13851 } 13852 13853 if (dataOnly) { 13854 // Delete application data first 13855 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13856 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13857 return true; 13858 } 13859 13860 boolean ret = false; 13861 if (isSystemApp(ps)) { 13862 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13863 // When an updated system application is deleted we delete the existing resources as well and 13864 // fall back to existing code in system partition 13865 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13866 flags, outInfo, writeSettings); 13867 } else { 13868 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13869 // Kill application pre-emptively especially for apps on sd. 13870 killApplication(packageName, ps.appId, "uninstall pkg"); 13871 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13872 allUserHandles, perUserInstalled, 13873 outInfo, writeSettings); 13874 } 13875 13876 return ret; 13877 } 13878 13879 private final static class ClearStorageConnection implements ServiceConnection { 13880 IMediaContainerService mContainerService; 13881 13882 @Override 13883 public void onServiceConnected(ComponentName name, IBinder service) { 13884 synchronized (this) { 13885 mContainerService = IMediaContainerService.Stub.asInterface(service); 13886 notifyAll(); 13887 } 13888 } 13889 13890 @Override 13891 public void onServiceDisconnected(ComponentName name) { 13892 } 13893 } 13894 13895 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13896 final boolean mounted; 13897 if (Environment.isExternalStorageEmulated()) { 13898 mounted = true; 13899 } else { 13900 final String status = Environment.getExternalStorageState(); 13901 13902 mounted = status.equals(Environment.MEDIA_MOUNTED) 13903 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13904 } 13905 13906 if (!mounted) { 13907 return; 13908 } 13909 13910 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13911 int[] users; 13912 if (userId == UserHandle.USER_ALL) { 13913 users = sUserManager.getUserIds(); 13914 } else { 13915 users = new int[] { userId }; 13916 } 13917 final ClearStorageConnection conn = new ClearStorageConnection(); 13918 if (mContext.bindServiceAsUser( 13919 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13920 try { 13921 for (int curUser : users) { 13922 long timeout = SystemClock.uptimeMillis() + 5000; 13923 synchronized (conn) { 13924 long now = SystemClock.uptimeMillis(); 13925 while (conn.mContainerService == null && now < timeout) { 13926 try { 13927 conn.wait(timeout - now); 13928 } catch (InterruptedException e) { 13929 } 13930 } 13931 } 13932 if (conn.mContainerService == null) { 13933 return; 13934 } 13935 13936 final UserEnvironment userEnv = new UserEnvironment(curUser); 13937 clearDirectory(conn.mContainerService, 13938 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13939 if (allData) { 13940 clearDirectory(conn.mContainerService, 13941 userEnv.buildExternalStorageAppDataDirs(packageName)); 13942 clearDirectory(conn.mContainerService, 13943 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13944 } 13945 } 13946 } finally { 13947 mContext.unbindService(conn); 13948 } 13949 } 13950 } 13951 13952 @Override 13953 public void clearApplicationUserData(final String packageName, 13954 final IPackageDataObserver observer, final int userId) { 13955 mContext.enforceCallingOrSelfPermission( 13956 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13957 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13958 // Queue up an async operation since the package deletion may take a little while. 13959 mHandler.post(new Runnable() { 13960 public void run() { 13961 mHandler.removeCallbacks(this); 13962 final boolean succeeded; 13963 synchronized (mInstallLock) { 13964 succeeded = clearApplicationUserDataLI(packageName, userId); 13965 } 13966 clearExternalStorageDataSync(packageName, userId, true); 13967 if (succeeded) { 13968 // invoke DeviceStorageMonitor's update method to clear any notifications 13969 DeviceStorageMonitorInternal 13970 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13971 if (dsm != null) { 13972 dsm.checkMemory(); 13973 } 13974 } 13975 if(observer != null) { 13976 try { 13977 observer.onRemoveCompleted(packageName, succeeded); 13978 } catch (RemoteException e) { 13979 Log.i(TAG, "Observer no longer exists."); 13980 } 13981 } //end if observer 13982 } //end run 13983 }); 13984 } 13985 13986 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13987 if (packageName == null) { 13988 Slog.w(TAG, "Attempt to delete null packageName."); 13989 return false; 13990 } 13991 13992 // Try finding details about the requested package 13993 PackageParser.Package pkg; 13994 synchronized (mPackages) { 13995 pkg = mPackages.get(packageName); 13996 if (pkg == null) { 13997 final PackageSetting ps = mSettings.mPackages.get(packageName); 13998 if (ps != null) { 13999 pkg = ps.pkg; 14000 } 14001 } 14002 14003 if (pkg == null) { 14004 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14005 return false; 14006 } 14007 14008 PackageSetting ps = (PackageSetting) pkg.mExtras; 14009 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14010 } 14011 14012 // Always delete data directories for package, even if we found no other 14013 // record of app. This helps users recover from UID mismatches without 14014 // resorting to a full data wipe. 14015 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14016 if (retCode < 0) { 14017 Slog.w(TAG, "Couldn't remove cache files for package " + packageName); 14018 return false; 14019 } 14020 14021 final int appId = pkg.applicationInfo.uid; 14022 removeKeystoreDataIfNeeded(userId, appId); 14023 14024 // Create a native library symlink only if we have native libraries 14025 // and if the native libraries are 32 bit libraries. We do not provide 14026 // this symlink for 64 bit libraries. 14027 if (pkg.applicationInfo.primaryCpuAbi != null && 14028 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14029 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14030 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14031 nativeLibPath, userId) < 0) { 14032 Slog.w(TAG, "Failed linking native library dir"); 14033 return false; 14034 } 14035 } 14036 14037 return true; 14038 } 14039 14040 /** 14041 * Reverts user permission state changes (permissions and flags) in 14042 * all packages for a given user. 14043 * 14044 * @param userId The device user for which to do a reset. 14045 */ 14046 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14047 final int packageCount = mPackages.size(); 14048 for (int i = 0; i < packageCount; i++) { 14049 PackageParser.Package pkg = mPackages.valueAt(i); 14050 PackageSetting ps = (PackageSetting) pkg.mExtras; 14051 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14052 } 14053 } 14054 14055 /** 14056 * Reverts user permission state changes (permissions and flags). 14057 * 14058 * @param ps The package for which to reset. 14059 * @param userId The device user for which to do a reset. 14060 */ 14061 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14062 final PackageSetting ps, final int userId) { 14063 if (ps.pkg == null) { 14064 return; 14065 } 14066 14067 // These are flags that can change base on user actions. 14068 final int userSettableMask = FLAG_PERMISSION_USER_SET 14069 | FLAG_PERMISSION_USER_FIXED 14070 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14071 | FLAG_PERMISSION_REVIEW_REQUIRED; 14072 14073 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14074 | FLAG_PERMISSION_POLICY_FIXED; 14075 14076 boolean writeInstallPermissions = false; 14077 boolean writeRuntimePermissions = false; 14078 14079 final int permissionCount = ps.pkg.requestedPermissions.size(); 14080 for (int i = 0; i < permissionCount; i++) { 14081 String permission = ps.pkg.requestedPermissions.get(i); 14082 14083 BasePermission bp = mSettings.mPermissions.get(permission); 14084 if (bp == null) { 14085 continue; 14086 } 14087 14088 // If shared user we just reset the state to which only this app contributed. 14089 if (ps.sharedUser != null) { 14090 boolean used = false; 14091 final int packageCount = ps.sharedUser.packages.size(); 14092 for (int j = 0; j < packageCount; j++) { 14093 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14094 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14095 && pkg.pkg.requestedPermissions.contains(permission)) { 14096 used = true; 14097 break; 14098 } 14099 } 14100 if (used) { 14101 continue; 14102 } 14103 } 14104 14105 PermissionsState permissionsState = ps.getPermissionsState(); 14106 14107 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14108 14109 // Always clear the user settable flags. 14110 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14111 bp.name) != null; 14112 // If permission review is enabled and this is a legacy app, mark the 14113 // permission as requiring a review as this is the initial state. 14114 int flags = 0; 14115 if (Build.PERMISSIONS_REVIEW_REQUIRED 14116 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14117 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14118 } 14119 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14120 if (hasInstallState) { 14121 writeInstallPermissions = true; 14122 } else { 14123 writeRuntimePermissions = true; 14124 } 14125 } 14126 14127 // Below is only runtime permission handling. 14128 if (!bp.isRuntime()) { 14129 continue; 14130 } 14131 14132 // Never clobber system or policy. 14133 if ((oldFlags & policyOrSystemFlags) != 0) { 14134 continue; 14135 } 14136 14137 // If this permission was granted by default, make sure it is. 14138 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14139 if (permissionsState.grantRuntimePermission(bp, userId) 14140 != PERMISSION_OPERATION_FAILURE) { 14141 writeRuntimePermissions = true; 14142 } 14143 // If permission review is enabled the permissions for a legacy apps 14144 // are represented as constantly granted runtime ones, so don't revoke. 14145 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14146 // Otherwise, reset the permission. 14147 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14148 switch (revokeResult) { 14149 case PERMISSION_OPERATION_SUCCESS: { 14150 writeRuntimePermissions = true; 14151 } break; 14152 14153 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14154 writeRuntimePermissions = true; 14155 final int appId = ps.appId; 14156 mHandler.post(new Runnable() { 14157 @Override 14158 public void run() { 14159 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14160 } 14161 }); 14162 } break; 14163 } 14164 } 14165 } 14166 14167 // Synchronously write as we are taking permissions away. 14168 if (writeRuntimePermissions) { 14169 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14170 } 14171 14172 // Synchronously write as we are taking permissions away. 14173 if (writeInstallPermissions) { 14174 mSettings.writeLPr(); 14175 } 14176 } 14177 14178 /** 14179 * Remove entries from the keystore daemon. Will only remove it if the 14180 * {@code appId} is valid. 14181 */ 14182 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14183 if (appId < 0) { 14184 return; 14185 } 14186 14187 final KeyStore keyStore = KeyStore.getInstance(); 14188 if (keyStore != null) { 14189 if (userId == UserHandle.USER_ALL) { 14190 for (final int individual : sUserManager.getUserIds()) { 14191 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14192 } 14193 } else { 14194 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14195 } 14196 } else { 14197 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14198 } 14199 } 14200 14201 @Override 14202 public void deleteApplicationCacheFiles(final String packageName, 14203 final IPackageDataObserver observer) { 14204 mContext.enforceCallingOrSelfPermission( 14205 android.Manifest.permission.DELETE_CACHE_FILES, null); 14206 // Queue up an async operation since the package deletion may take a little while. 14207 final int userId = UserHandle.getCallingUserId(); 14208 mHandler.post(new Runnable() { 14209 public void run() { 14210 mHandler.removeCallbacks(this); 14211 final boolean succeded; 14212 synchronized (mInstallLock) { 14213 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14214 } 14215 clearExternalStorageDataSync(packageName, userId, false); 14216 if (observer != null) { 14217 try { 14218 observer.onRemoveCompleted(packageName, succeded); 14219 } catch (RemoteException e) { 14220 Log.i(TAG, "Observer no longer exists."); 14221 } 14222 } //end if observer 14223 } //end run 14224 }); 14225 } 14226 14227 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14228 if (packageName == null) { 14229 Slog.w(TAG, "Attempt to delete null packageName."); 14230 return false; 14231 } 14232 PackageParser.Package p; 14233 synchronized (mPackages) { 14234 p = mPackages.get(packageName); 14235 } 14236 if (p == null) { 14237 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14238 return false; 14239 } 14240 final ApplicationInfo applicationInfo = p.applicationInfo; 14241 if (applicationInfo == null) { 14242 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14243 return false; 14244 } 14245 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14246 if (retCode < 0) { 14247 Slog.w(TAG, "Couldn't remove cache files for package " 14248 + packageName + " u" + userId); 14249 return false; 14250 } 14251 return true; 14252 } 14253 14254 @Override 14255 public void getPackageSizeInfo(final String packageName, int userHandle, 14256 final IPackageStatsObserver observer) { 14257 mContext.enforceCallingOrSelfPermission( 14258 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14259 if (packageName == null) { 14260 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14261 } 14262 14263 PackageStats stats = new PackageStats(packageName, userHandle); 14264 14265 /* 14266 * Queue up an async operation since the package measurement may take a 14267 * little while. 14268 */ 14269 Message msg = mHandler.obtainMessage(INIT_COPY); 14270 msg.obj = new MeasureParams(stats, observer); 14271 mHandler.sendMessage(msg); 14272 } 14273 14274 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14275 PackageStats pStats) { 14276 if (packageName == null) { 14277 Slog.w(TAG, "Attempt to get size of null packageName."); 14278 return false; 14279 } 14280 PackageParser.Package p; 14281 boolean dataOnly = false; 14282 String libDirRoot = null; 14283 String asecPath = null; 14284 PackageSetting ps = null; 14285 synchronized (mPackages) { 14286 p = mPackages.get(packageName); 14287 ps = mSettings.mPackages.get(packageName); 14288 if(p == null) { 14289 dataOnly = true; 14290 if((ps == null) || (ps.pkg == null)) { 14291 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14292 return false; 14293 } 14294 p = ps.pkg; 14295 } 14296 if (ps != null) { 14297 libDirRoot = ps.legacyNativeLibraryPathString; 14298 } 14299 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14300 final long token = Binder.clearCallingIdentity(); 14301 try { 14302 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14303 if (secureContainerId != null) { 14304 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14305 } 14306 } finally { 14307 Binder.restoreCallingIdentity(token); 14308 } 14309 } 14310 } 14311 String publicSrcDir = null; 14312 if(!dataOnly) { 14313 final ApplicationInfo applicationInfo = p.applicationInfo; 14314 if (applicationInfo == null) { 14315 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14316 return false; 14317 } 14318 if (p.isForwardLocked()) { 14319 publicSrcDir = applicationInfo.getBaseResourcePath(); 14320 } 14321 } 14322 // TODO: extend to measure size of split APKs 14323 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14324 // not just the first level. 14325 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14326 // just the primary. 14327 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14328 14329 String apkPath; 14330 File packageDir = new File(p.codePath); 14331 14332 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14333 apkPath = packageDir.getAbsolutePath(); 14334 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14335 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14336 libDirRoot = null; 14337 } 14338 } else { 14339 apkPath = p.baseCodePath; 14340 } 14341 14342 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14343 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14344 if (res < 0) { 14345 return false; 14346 } 14347 14348 // Fix-up for forward-locked applications in ASEC containers. 14349 if (!isExternal(p)) { 14350 pStats.codeSize += pStats.externalCodeSize; 14351 pStats.externalCodeSize = 0L; 14352 } 14353 14354 return true; 14355 } 14356 14357 14358 @Override 14359 public void addPackageToPreferred(String packageName) { 14360 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14361 } 14362 14363 @Override 14364 public void removePackageFromPreferred(String packageName) { 14365 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14366 } 14367 14368 @Override 14369 public List<PackageInfo> getPreferredPackages(int flags) { 14370 return new ArrayList<PackageInfo>(); 14371 } 14372 14373 private int getUidTargetSdkVersionLockedLPr(int uid) { 14374 Object obj = mSettings.getUserIdLPr(uid); 14375 if (obj instanceof SharedUserSetting) { 14376 final SharedUserSetting sus = (SharedUserSetting) obj; 14377 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14378 final Iterator<PackageSetting> it = sus.packages.iterator(); 14379 while (it.hasNext()) { 14380 final PackageSetting ps = it.next(); 14381 if (ps.pkg != null) { 14382 int v = ps.pkg.applicationInfo.targetSdkVersion; 14383 if (v < vers) vers = v; 14384 } 14385 } 14386 return vers; 14387 } else if (obj instanceof PackageSetting) { 14388 final PackageSetting ps = (PackageSetting) obj; 14389 if (ps.pkg != null) { 14390 return ps.pkg.applicationInfo.targetSdkVersion; 14391 } 14392 } 14393 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14394 } 14395 14396 @Override 14397 public void addPreferredActivity(IntentFilter filter, int match, 14398 ComponentName[] set, ComponentName activity, int userId) { 14399 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14400 "Adding preferred"); 14401 } 14402 14403 private void addPreferredActivityInternal(IntentFilter filter, int match, 14404 ComponentName[] set, ComponentName activity, boolean always, int userId, 14405 String opname) { 14406 // writer 14407 int callingUid = Binder.getCallingUid(); 14408 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14409 if (filter.countActions() == 0) { 14410 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14411 return; 14412 } 14413 synchronized (mPackages) { 14414 if (mContext.checkCallingOrSelfPermission( 14415 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14416 != PackageManager.PERMISSION_GRANTED) { 14417 if (getUidTargetSdkVersionLockedLPr(callingUid) 14418 < Build.VERSION_CODES.FROYO) { 14419 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14420 + callingUid); 14421 return; 14422 } 14423 mContext.enforceCallingOrSelfPermission( 14424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14425 } 14426 14427 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14428 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14429 + userId + ":"); 14430 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14431 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14432 scheduleWritePackageRestrictionsLocked(userId); 14433 } 14434 } 14435 14436 @Override 14437 public void replacePreferredActivity(IntentFilter filter, int match, 14438 ComponentName[] set, ComponentName activity, int userId) { 14439 if (filter.countActions() != 1) { 14440 throw new IllegalArgumentException( 14441 "replacePreferredActivity expects filter to have only 1 action."); 14442 } 14443 if (filter.countDataAuthorities() != 0 14444 || filter.countDataPaths() != 0 14445 || filter.countDataSchemes() > 1 14446 || filter.countDataTypes() != 0) { 14447 throw new IllegalArgumentException( 14448 "replacePreferredActivity expects filter to have no data authorities, " + 14449 "paths, or types; and at most one scheme."); 14450 } 14451 14452 final int callingUid = Binder.getCallingUid(); 14453 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14454 synchronized (mPackages) { 14455 if (mContext.checkCallingOrSelfPermission( 14456 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14457 != PackageManager.PERMISSION_GRANTED) { 14458 if (getUidTargetSdkVersionLockedLPr(callingUid) 14459 < Build.VERSION_CODES.FROYO) { 14460 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14461 + Binder.getCallingUid()); 14462 return; 14463 } 14464 mContext.enforceCallingOrSelfPermission( 14465 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14466 } 14467 14468 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14469 if (pir != null) { 14470 // Get all of the existing entries that exactly match this filter. 14471 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14472 if (existing != null && existing.size() == 1) { 14473 PreferredActivity cur = existing.get(0); 14474 if (DEBUG_PREFERRED) { 14475 Slog.i(TAG, "Checking replace of preferred:"); 14476 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14477 if (!cur.mPref.mAlways) { 14478 Slog.i(TAG, " -- CUR; not mAlways!"); 14479 } else { 14480 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14481 Slog.i(TAG, " -- CUR: mSet=" 14482 + Arrays.toString(cur.mPref.mSetComponents)); 14483 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14484 Slog.i(TAG, " -- NEW: mMatch=" 14485 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14486 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14487 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14488 } 14489 } 14490 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14491 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14492 && cur.mPref.sameSet(set)) { 14493 // Setting the preferred activity to what it happens to be already 14494 if (DEBUG_PREFERRED) { 14495 Slog.i(TAG, "Replacing with same preferred activity " 14496 + cur.mPref.mShortComponent + " for user " 14497 + userId + ":"); 14498 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14499 } 14500 return; 14501 } 14502 } 14503 14504 if (existing != null) { 14505 if (DEBUG_PREFERRED) { 14506 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14507 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14508 } 14509 for (int i = 0; i < existing.size(); i++) { 14510 PreferredActivity pa = existing.get(i); 14511 if (DEBUG_PREFERRED) { 14512 Slog.i(TAG, "Removing existing preferred activity " 14513 + pa.mPref.mComponent + ":"); 14514 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14515 } 14516 pir.removeFilter(pa); 14517 } 14518 } 14519 } 14520 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14521 "Replacing preferred"); 14522 } 14523 } 14524 14525 @Override 14526 public void clearPackagePreferredActivities(String packageName) { 14527 final int uid = Binder.getCallingUid(); 14528 // writer 14529 synchronized (mPackages) { 14530 PackageParser.Package pkg = mPackages.get(packageName); 14531 if (pkg == null || pkg.applicationInfo.uid != uid) { 14532 if (mContext.checkCallingOrSelfPermission( 14533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14534 != PackageManager.PERMISSION_GRANTED) { 14535 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14536 < Build.VERSION_CODES.FROYO) { 14537 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14538 + Binder.getCallingUid()); 14539 return; 14540 } 14541 mContext.enforceCallingOrSelfPermission( 14542 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14543 } 14544 } 14545 14546 int user = UserHandle.getCallingUserId(); 14547 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14548 scheduleWritePackageRestrictionsLocked(user); 14549 } 14550 } 14551 } 14552 14553 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14554 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14555 ArrayList<PreferredActivity> removed = null; 14556 boolean changed = false; 14557 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14558 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14559 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14560 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14561 continue; 14562 } 14563 Iterator<PreferredActivity> it = pir.filterIterator(); 14564 while (it.hasNext()) { 14565 PreferredActivity pa = it.next(); 14566 // Mark entry for removal only if it matches the package name 14567 // and the entry is of type "always". 14568 if (packageName == null || 14569 (pa.mPref.mComponent.getPackageName().equals(packageName) 14570 && pa.mPref.mAlways)) { 14571 if (removed == null) { 14572 removed = new ArrayList<PreferredActivity>(); 14573 } 14574 removed.add(pa); 14575 } 14576 } 14577 if (removed != null) { 14578 for (int j=0; j<removed.size(); j++) { 14579 PreferredActivity pa = removed.get(j); 14580 pir.removeFilter(pa); 14581 } 14582 changed = true; 14583 } 14584 } 14585 return changed; 14586 } 14587 14588 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14589 private void clearIntentFilterVerificationsLPw(int userId) { 14590 final int packageCount = mPackages.size(); 14591 for (int i = 0; i < packageCount; i++) { 14592 PackageParser.Package pkg = mPackages.valueAt(i); 14593 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14594 } 14595 } 14596 14597 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14598 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14599 if (userId == UserHandle.USER_ALL) { 14600 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14601 sUserManager.getUserIds())) { 14602 for (int oneUserId : sUserManager.getUserIds()) { 14603 scheduleWritePackageRestrictionsLocked(oneUserId); 14604 } 14605 } 14606 } else { 14607 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14608 scheduleWritePackageRestrictionsLocked(userId); 14609 } 14610 } 14611 } 14612 14613 void clearDefaultBrowserIfNeeded(String packageName) { 14614 for (int oneUserId : sUserManager.getUserIds()) { 14615 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14616 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14617 if (packageName.equals(defaultBrowserPackageName)) { 14618 setDefaultBrowserPackageName(null, oneUserId); 14619 } 14620 } 14621 } 14622 14623 @Override 14624 public void resetApplicationPreferences(int userId) { 14625 mContext.enforceCallingOrSelfPermission( 14626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14627 // writer 14628 synchronized (mPackages) { 14629 final long identity = Binder.clearCallingIdentity(); 14630 try { 14631 clearPackagePreferredActivitiesLPw(null, userId); 14632 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14633 // TODO: We have to reset the default SMS and Phone. This requires 14634 // significant refactoring to keep all default apps in the package 14635 // manager (cleaner but more work) or have the services provide 14636 // callbacks to the package manager to request a default app reset. 14637 applyFactoryDefaultBrowserLPw(userId); 14638 clearIntentFilterVerificationsLPw(userId); 14639 primeDomainVerificationsLPw(userId); 14640 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14641 scheduleWritePackageRestrictionsLocked(userId); 14642 } finally { 14643 Binder.restoreCallingIdentity(identity); 14644 } 14645 } 14646 } 14647 14648 @Override 14649 public int getPreferredActivities(List<IntentFilter> outFilters, 14650 List<ComponentName> outActivities, String packageName) { 14651 14652 int num = 0; 14653 final int userId = UserHandle.getCallingUserId(); 14654 // reader 14655 synchronized (mPackages) { 14656 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14657 if (pir != null) { 14658 final Iterator<PreferredActivity> it = pir.filterIterator(); 14659 while (it.hasNext()) { 14660 final PreferredActivity pa = it.next(); 14661 if (packageName == null 14662 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14663 && pa.mPref.mAlways)) { 14664 if (outFilters != null) { 14665 outFilters.add(new IntentFilter(pa)); 14666 } 14667 if (outActivities != null) { 14668 outActivities.add(pa.mPref.mComponent); 14669 } 14670 } 14671 } 14672 } 14673 } 14674 14675 return num; 14676 } 14677 14678 @Override 14679 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14680 int userId) { 14681 int callingUid = Binder.getCallingUid(); 14682 if (callingUid != Process.SYSTEM_UID) { 14683 throw new SecurityException( 14684 "addPersistentPreferredActivity can only be run by the system"); 14685 } 14686 if (filter.countActions() == 0) { 14687 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14688 return; 14689 } 14690 synchronized (mPackages) { 14691 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14692 ":"); 14693 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14694 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14695 new PersistentPreferredActivity(filter, activity)); 14696 scheduleWritePackageRestrictionsLocked(userId); 14697 } 14698 } 14699 14700 @Override 14701 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14702 int callingUid = Binder.getCallingUid(); 14703 if (callingUid != Process.SYSTEM_UID) { 14704 throw new SecurityException( 14705 "clearPackagePersistentPreferredActivities can only be run by the system"); 14706 } 14707 ArrayList<PersistentPreferredActivity> removed = null; 14708 boolean changed = false; 14709 synchronized (mPackages) { 14710 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14711 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14712 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14713 .valueAt(i); 14714 if (userId != thisUserId) { 14715 continue; 14716 } 14717 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14718 while (it.hasNext()) { 14719 PersistentPreferredActivity ppa = it.next(); 14720 // Mark entry for removal only if it matches the package name. 14721 if (ppa.mComponent.getPackageName().equals(packageName)) { 14722 if (removed == null) { 14723 removed = new ArrayList<PersistentPreferredActivity>(); 14724 } 14725 removed.add(ppa); 14726 } 14727 } 14728 if (removed != null) { 14729 for (int j=0; j<removed.size(); j++) { 14730 PersistentPreferredActivity ppa = removed.get(j); 14731 ppir.removeFilter(ppa); 14732 } 14733 changed = true; 14734 } 14735 } 14736 14737 if (changed) { 14738 scheduleWritePackageRestrictionsLocked(userId); 14739 } 14740 } 14741 } 14742 14743 /** 14744 * Common machinery for picking apart a restored XML blob and passing 14745 * it to a caller-supplied functor to be applied to the running system. 14746 */ 14747 private void restoreFromXml(XmlPullParser parser, int userId, 14748 String expectedStartTag, BlobXmlRestorer functor) 14749 throws IOException, XmlPullParserException { 14750 int type; 14751 while ((type = parser.next()) != XmlPullParser.START_TAG 14752 && type != XmlPullParser.END_DOCUMENT) { 14753 } 14754 if (type != XmlPullParser.START_TAG) { 14755 // oops didn't find a start tag?! 14756 if (DEBUG_BACKUP) { 14757 Slog.e(TAG, "Didn't find start tag during restore"); 14758 } 14759 return; 14760 } 14761 14762 // this is supposed to be TAG_PREFERRED_BACKUP 14763 if (!expectedStartTag.equals(parser.getName())) { 14764 if (DEBUG_BACKUP) { 14765 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14766 } 14767 return; 14768 } 14769 14770 // skip interfering stuff, then we're aligned with the backing implementation 14771 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14772 functor.apply(parser, userId); 14773 } 14774 14775 private interface BlobXmlRestorer { 14776 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14777 } 14778 14779 /** 14780 * Non-Binder method, support for the backup/restore mechanism: write the 14781 * full set of preferred activities in its canonical XML format. Returns the 14782 * XML output as a byte array, or null if there is none. 14783 */ 14784 @Override 14785 public byte[] getPreferredActivityBackup(int userId) { 14786 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14787 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14788 } 14789 14790 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14791 try { 14792 final XmlSerializer serializer = new FastXmlSerializer(); 14793 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14794 serializer.startDocument(null, true); 14795 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14796 14797 synchronized (mPackages) { 14798 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14799 } 14800 14801 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14802 serializer.endDocument(); 14803 serializer.flush(); 14804 } catch (Exception e) { 14805 if (DEBUG_BACKUP) { 14806 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14807 } 14808 return null; 14809 } 14810 14811 return dataStream.toByteArray(); 14812 } 14813 14814 @Override 14815 public void restorePreferredActivities(byte[] backup, int userId) { 14816 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14817 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14818 } 14819 14820 try { 14821 final XmlPullParser parser = Xml.newPullParser(); 14822 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14823 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14824 new BlobXmlRestorer() { 14825 @Override 14826 public void apply(XmlPullParser parser, int userId) 14827 throws XmlPullParserException, IOException { 14828 synchronized (mPackages) { 14829 mSettings.readPreferredActivitiesLPw(parser, userId); 14830 } 14831 } 14832 } ); 14833 } catch (Exception e) { 14834 if (DEBUG_BACKUP) { 14835 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14836 } 14837 } 14838 } 14839 14840 /** 14841 * Non-Binder method, support for the backup/restore mechanism: write the 14842 * default browser (etc) settings in its canonical XML format. Returns the default 14843 * browser XML representation as a byte array, or null if there is none. 14844 */ 14845 @Override 14846 public byte[] getDefaultAppsBackup(int userId) { 14847 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14848 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14849 } 14850 14851 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14852 try { 14853 final XmlSerializer serializer = new FastXmlSerializer(); 14854 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14855 serializer.startDocument(null, true); 14856 serializer.startTag(null, TAG_DEFAULT_APPS); 14857 14858 synchronized (mPackages) { 14859 mSettings.writeDefaultAppsLPr(serializer, userId); 14860 } 14861 14862 serializer.endTag(null, TAG_DEFAULT_APPS); 14863 serializer.endDocument(); 14864 serializer.flush(); 14865 } catch (Exception e) { 14866 if (DEBUG_BACKUP) { 14867 Slog.e(TAG, "Unable to write default apps for backup", e); 14868 } 14869 return null; 14870 } 14871 14872 return dataStream.toByteArray(); 14873 } 14874 14875 @Override 14876 public void restoreDefaultApps(byte[] backup, int userId) { 14877 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14878 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14879 } 14880 14881 try { 14882 final XmlPullParser parser = Xml.newPullParser(); 14883 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14884 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14885 new BlobXmlRestorer() { 14886 @Override 14887 public void apply(XmlPullParser parser, int userId) 14888 throws XmlPullParserException, IOException { 14889 synchronized (mPackages) { 14890 mSettings.readDefaultAppsLPw(parser, userId); 14891 } 14892 } 14893 } ); 14894 } catch (Exception e) { 14895 if (DEBUG_BACKUP) { 14896 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14897 } 14898 } 14899 } 14900 14901 @Override 14902 public byte[] getIntentFilterVerificationBackup(int userId) { 14903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14904 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14905 } 14906 14907 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14908 try { 14909 final XmlSerializer serializer = new FastXmlSerializer(); 14910 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14911 serializer.startDocument(null, true); 14912 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14913 14914 synchronized (mPackages) { 14915 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14916 } 14917 14918 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14919 serializer.endDocument(); 14920 serializer.flush(); 14921 } catch (Exception e) { 14922 if (DEBUG_BACKUP) { 14923 Slog.e(TAG, "Unable to write default apps for backup", e); 14924 } 14925 return null; 14926 } 14927 14928 return dataStream.toByteArray(); 14929 } 14930 14931 @Override 14932 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14933 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14934 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14935 } 14936 14937 try { 14938 final XmlPullParser parser = Xml.newPullParser(); 14939 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14940 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14941 new BlobXmlRestorer() { 14942 @Override 14943 public void apply(XmlPullParser parser, int userId) 14944 throws XmlPullParserException, IOException { 14945 synchronized (mPackages) { 14946 mSettings.readAllDomainVerificationsLPr(parser, userId); 14947 mSettings.writeLPr(); 14948 } 14949 } 14950 } ); 14951 } catch (Exception e) { 14952 if (DEBUG_BACKUP) { 14953 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14954 } 14955 } 14956 } 14957 14958 @Override 14959 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14960 int sourceUserId, int targetUserId, int flags) { 14961 mContext.enforceCallingOrSelfPermission( 14962 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14963 int callingUid = Binder.getCallingUid(); 14964 enforceOwnerRights(ownerPackage, callingUid); 14965 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14966 if (intentFilter.countActions() == 0) { 14967 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14968 return; 14969 } 14970 synchronized (mPackages) { 14971 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14972 ownerPackage, targetUserId, flags); 14973 CrossProfileIntentResolver resolver = 14974 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14975 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14976 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14977 if (existing != null) { 14978 int size = existing.size(); 14979 for (int i = 0; i < size; i++) { 14980 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14981 return; 14982 } 14983 } 14984 } 14985 resolver.addFilter(newFilter); 14986 scheduleWritePackageRestrictionsLocked(sourceUserId); 14987 } 14988 } 14989 14990 @Override 14991 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14992 mContext.enforceCallingOrSelfPermission( 14993 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14994 int callingUid = Binder.getCallingUid(); 14995 enforceOwnerRights(ownerPackage, callingUid); 14996 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14997 synchronized (mPackages) { 14998 CrossProfileIntentResolver resolver = 14999 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15000 ArraySet<CrossProfileIntentFilter> set = 15001 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15002 for (CrossProfileIntentFilter filter : set) { 15003 if (filter.getOwnerPackage().equals(ownerPackage)) { 15004 resolver.removeFilter(filter); 15005 } 15006 } 15007 scheduleWritePackageRestrictionsLocked(sourceUserId); 15008 } 15009 } 15010 15011 // Enforcing that callingUid is owning pkg on userId 15012 private void enforceOwnerRights(String pkg, int callingUid) { 15013 // The system owns everything. 15014 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15015 return; 15016 } 15017 int callingUserId = UserHandle.getUserId(callingUid); 15018 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15019 if (pi == null) { 15020 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15021 + callingUserId); 15022 } 15023 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15024 throw new SecurityException("Calling uid " + callingUid 15025 + " does not own package " + pkg); 15026 } 15027 } 15028 15029 @Override 15030 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15031 Intent intent = new Intent(Intent.ACTION_MAIN); 15032 intent.addCategory(Intent.CATEGORY_HOME); 15033 15034 final int callingUserId = UserHandle.getCallingUserId(); 15035 List<ResolveInfo> list = queryIntentActivities(intent, null, 15036 PackageManager.GET_META_DATA, callingUserId); 15037 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15038 true, false, false, callingUserId); 15039 15040 allHomeCandidates.clear(); 15041 if (list != null) { 15042 for (ResolveInfo ri : list) { 15043 allHomeCandidates.add(ri); 15044 } 15045 } 15046 return (preferred == null || preferred.activityInfo == null) 15047 ? null 15048 : new ComponentName(preferred.activityInfo.packageName, 15049 preferred.activityInfo.name); 15050 } 15051 15052 @Override 15053 public void setApplicationEnabledSetting(String appPackageName, 15054 int newState, int flags, int userId, String callingPackage) { 15055 if (!sUserManager.exists(userId)) return; 15056 if (callingPackage == null) { 15057 callingPackage = Integer.toString(Binder.getCallingUid()); 15058 } 15059 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15060 } 15061 15062 @Override 15063 public void setComponentEnabledSetting(ComponentName componentName, 15064 int newState, int flags, int userId) { 15065 if (!sUserManager.exists(userId)) return; 15066 setEnabledSetting(componentName.getPackageName(), 15067 componentName.getClassName(), newState, flags, userId, null); 15068 } 15069 15070 private void setEnabledSetting(final String packageName, String className, int newState, 15071 final int flags, int userId, String callingPackage) { 15072 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15073 || newState == COMPONENT_ENABLED_STATE_ENABLED 15074 || newState == COMPONENT_ENABLED_STATE_DISABLED 15075 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15076 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15077 throw new IllegalArgumentException("Invalid new component state: " 15078 + newState); 15079 } 15080 PackageSetting pkgSetting; 15081 final int uid = Binder.getCallingUid(); 15082 final int permission = mContext.checkCallingOrSelfPermission( 15083 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15084 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15085 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15086 boolean sendNow = false; 15087 boolean isApp = (className == null); 15088 String componentName = isApp ? packageName : className; 15089 int packageUid = -1; 15090 ArrayList<String> components; 15091 15092 // writer 15093 synchronized (mPackages) { 15094 pkgSetting = mSettings.mPackages.get(packageName); 15095 if (pkgSetting == null) { 15096 if (className == null) { 15097 throw new IllegalArgumentException("Unknown package: " + packageName); 15098 } 15099 throw new IllegalArgumentException( 15100 "Unknown component: " + packageName + "/" + className); 15101 } 15102 // Allow root and verify that userId is not being specified by a different user 15103 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15104 throw new SecurityException( 15105 "Permission Denial: attempt to change component state from pid=" 15106 + Binder.getCallingPid() 15107 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15108 } 15109 if (className == null) { 15110 // We're dealing with an application/package level state change 15111 if (pkgSetting.getEnabled(userId) == newState) { 15112 // Nothing to do 15113 return; 15114 } 15115 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15116 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15117 // Don't care about who enables an app. 15118 callingPackage = null; 15119 } 15120 pkgSetting.setEnabled(newState, userId, callingPackage); 15121 // pkgSetting.pkg.mSetEnabled = newState; 15122 } else { 15123 // We're dealing with a component level state change 15124 // First, verify that this is a valid class name. 15125 PackageParser.Package pkg = pkgSetting.pkg; 15126 if (pkg == null || !pkg.hasComponentClassName(className)) { 15127 if (pkg != null && 15128 pkg.applicationInfo.targetSdkVersion >= 15129 Build.VERSION_CODES.JELLY_BEAN) { 15130 throw new IllegalArgumentException("Component class " + className 15131 + " does not exist in " + packageName); 15132 } else { 15133 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15134 + className + " does not exist in " + packageName); 15135 } 15136 } 15137 switch (newState) { 15138 case COMPONENT_ENABLED_STATE_ENABLED: 15139 if (!pkgSetting.enableComponentLPw(className, userId)) { 15140 return; 15141 } 15142 break; 15143 case COMPONENT_ENABLED_STATE_DISABLED: 15144 if (!pkgSetting.disableComponentLPw(className, userId)) { 15145 return; 15146 } 15147 break; 15148 case COMPONENT_ENABLED_STATE_DEFAULT: 15149 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15150 return; 15151 } 15152 break; 15153 default: 15154 Slog.e(TAG, "Invalid new component state: " + newState); 15155 return; 15156 } 15157 } 15158 scheduleWritePackageRestrictionsLocked(userId); 15159 components = mPendingBroadcasts.get(userId, packageName); 15160 final boolean newPackage = components == null; 15161 if (newPackage) { 15162 components = new ArrayList<String>(); 15163 } 15164 if (!components.contains(componentName)) { 15165 components.add(componentName); 15166 } 15167 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15168 sendNow = true; 15169 // Purge entry from pending broadcast list if another one exists already 15170 // since we are sending one right away. 15171 mPendingBroadcasts.remove(userId, packageName); 15172 } else { 15173 if (newPackage) { 15174 mPendingBroadcasts.put(userId, packageName, components); 15175 } 15176 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15177 // Schedule a message 15178 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15179 } 15180 } 15181 } 15182 15183 long callingId = Binder.clearCallingIdentity(); 15184 try { 15185 if (sendNow) { 15186 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15187 sendPackageChangedBroadcast(packageName, 15188 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15189 } 15190 } finally { 15191 Binder.restoreCallingIdentity(callingId); 15192 } 15193 } 15194 15195 private void sendPackageChangedBroadcast(String packageName, 15196 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15197 if (DEBUG_INSTALL) 15198 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15199 + componentNames); 15200 Bundle extras = new Bundle(4); 15201 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15202 String nameList[] = new String[componentNames.size()]; 15203 componentNames.toArray(nameList); 15204 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15205 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15206 extras.putInt(Intent.EXTRA_UID, packageUid); 15207 // If this is not reporting a change of the overall package, then only send it 15208 // to registered receivers. We don't want to launch a swath of apps for every 15209 // little component state change. 15210 final int flags = !componentNames.contains(packageName) 15211 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15212 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15213 new int[] {UserHandle.getUserId(packageUid)}); 15214 } 15215 15216 @Override 15217 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15218 if (!sUserManager.exists(userId)) return; 15219 final int uid = Binder.getCallingUid(); 15220 final int permission = mContext.checkCallingOrSelfPermission( 15221 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15222 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15223 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15224 // writer 15225 synchronized (mPackages) { 15226 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15227 allowedByPermission, uid, userId)) { 15228 scheduleWritePackageRestrictionsLocked(userId); 15229 } 15230 } 15231 } 15232 15233 @Override 15234 public String getInstallerPackageName(String packageName) { 15235 // reader 15236 synchronized (mPackages) { 15237 return mSettings.getInstallerPackageNameLPr(packageName); 15238 } 15239 } 15240 15241 @Override 15242 public int getApplicationEnabledSetting(String packageName, int userId) { 15243 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15244 int uid = Binder.getCallingUid(); 15245 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15246 // reader 15247 synchronized (mPackages) { 15248 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15249 } 15250 } 15251 15252 @Override 15253 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15254 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15255 int uid = Binder.getCallingUid(); 15256 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15257 // reader 15258 synchronized (mPackages) { 15259 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15260 } 15261 } 15262 15263 @Override 15264 public void enterSafeMode() { 15265 enforceSystemOrRoot("Only the system can request entering safe mode"); 15266 15267 if (!mSystemReady) { 15268 mSafeMode = true; 15269 } 15270 } 15271 15272 @Override 15273 public void systemReady() { 15274 mSystemReady = true; 15275 15276 // Read the compatibilty setting when the system is ready. 15277 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15278 mContext.getContentResolver(), 15279 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15280 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15281 if (DEBUG_SETTINGS) { 15282 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15283 } 15284 15285 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15286 15287 synchronized (mPackages) { 15288 // Verify that all of the preferred activity components actually 15289 // exist. It is possible for applications to be updated and at 15290 // that point remove a previously declared activity component that 15291 // had been set as a preferred activity. We try to clean this up 15292 // the next time we encounter that preferred activity, but it is 15293 // possible for the user flow to never be able to return to that 15294 // situation so here we do a sanity check to make sure we haven't 15295 // left any junk around. 15296 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15297 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15298 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15299 removed.clear(); 15300 for (PreferredActivity pa : pir.filterSet()) { 15301 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15302 removed.add(pa); 15303 } 15304 } 15305 if (removed.size() > 0) { 15306 for (int r=0; r<removed.size(); r++) { 15307 PreferredActivity pa = removed.get(r); 15308 Slog.w(TAG, "Removing dangling preferred activity: " 15309 + pa.mPref.mComponent); 15310 pir.removeFilter(pa); 15311 } 15312 mSettings.writePackageRestrictionsLPr( 15313 mSettings.mPreferredActivities.keyAt(i)); 15314 } 15315 } 15316 15317 for (int userId : UserManagerService.getInstance().getUserIds()) { 15318 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15319 grantPermissionsUserIds = ArrayUtils.appendInt( 15320 grantPermissionsUserIds, userId); 15321 } 15322 } 15323 } 15324 sUserManager.systemReady(); 15325 15326 // If we upgraded grant all default permissions before kicking off. 15327 for (int userId : grantPermissionsUserIds) { 15328 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15329 } 15330 15331 // Kick off any messages waiting for system ready 15332 if (mPostSystemReadyMessages != null) { 15333 for (Message msg : mPostSystemReadyMessages) { 15334 msg.sendToTarget(); 15335 } 15336 mPostSystemReadyMessages = null; 15337 } 15338 15339 // Watch for external volumes that come and go over time 15340 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15341 storage.registerListener(mStorageListener); 15342 15343 mInstallerService.systemReady(); 15344 mPackageDexOptimizer.systemReady(); 15345 15346 MountServiceInternal mountServiceInternal = LocalServices.getService( 15347 MountServiceInternal.class); 15348 mountServiceInternal.addExternalStoragePolicy( 15349 new MountServiceInternal.ExternalStorageMountPolicy() { 15350 @Override 15351 public int getMountMode(int uid, String packageName) { 15352 if (Process.isIsolated(uid)) { 15353 return Zygote.MOUNT_EXTERNAL_NONE; 15354 } 15355 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15356 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15357 } 15358 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15359 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15360 } 15361 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15362 return Zygote.MOUNT_EXTERNAL_READ; 15363 } 15364 return Zygote.MOUNT_EXTERNAL_WRITE; 15365 } 15366 15367 @Override 15368 public boolean hasExternalStorage(int uid, String packageName) { 15369 return true; 15370 } 15371 }); 15372 } 15373 15374 @Override 15375 public boolean isSafeMode() { 15376 return mSafeMode; 15377 } 15378 15379 @Override 15380 public boolean hasSystemUidErrors() { 15381 return mHasSystemUidErrors; 15382 } 15383 15384 static String arrayToString(int[] array) { 15385 StringBuffer buf = new StringBuffer(128); 15386 buf.append('['); 15387 if (array != null) { 15388 for (int i=0; i<array.length; i++) { 15389 if (i > 0) buf.append(", "); 15390 buf.append(array[i]); 15391 } 15392 } 15393 buf.append(']'); 15394 return buf.toString(); 15395 } 15396 15397 static class DumpState { 15398 public static final int DUMP_LIBS = 1 << 0; 15399 public static final int DUMP_FEATURES = 1 << 1; 15400 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15401 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15402 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15403 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15404 public static final int DUMP_PERMISSIONS = 1 << 6; 15405 public static final int DUMP_PACKAGES = 1 << 7; 15406 public static final int DUMP_SHARED_USERS = 1 << 8; 15407 public static final int DUMP_MESSAGES = 1 << 9; 15408 public static final int DUMP_PROVIDERS = 1 << 10; 15409 public static final int DUMP_VERIFIERS = 1 << 11; 15410 public static final int DUMP_PREFERRED = 1 << 12; 15411 public static final int DUMP_PREFERRED_XML = 1 << 13; 15412 public static final int DUMP_KEYSETS = 1 << 14; 15413 public static final int DUMP_VERSION = 1 << 15; 15414 public static final int DUMP_INSTALLS = 1 << 16; 15415 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15416 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15417 15418 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15419 15420 private int mTypes; 15421 15422 private int mOptions; 15423 15424 private boolean mTitlePrinted; 15425 15426 private SharedUserSetting mSharedUser; 15427 15428 public boolean isDumping(int type) { 15429 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15430 return true; 15431 } 15432 15433 return (mTypes & type) != 0; 15434 } 15435 15436 public void setDump(int type) { 15437 mTypes |= type; 15438 } 15439 15440 public boolean isOptionEnabled(int option) { 15441 return (mOptions & option) != 0; 15442 } 15443 15444 public void setOptionEnabled(int option) { 15445 mOptions |= option; 15446 } 15447 15448 public boolean onTitlePrinted() { 15449 final boolean printed = mTitlePrinted; 15450 mTitlePrinted = true; 15451 return printed; 15452 } 15453 15454 public boolean getTitlePrinted() { 15455 return mTitlePrinted; 15456 } 15457 15458 public void setTitlePrinted(boolean enabled) { 15459 mTitlePrinted = enabled; 15460 } 15461 15462 public SharedUserSetting getSharedUser() { 15463 return mSharedUser; 15464 } 15465 15466 public void setSharedUser(SharedUserSetting user) { 15467 mSharedUser = user; 15468 } 15469 } 15470 15471 @Override 15472 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15473 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15474 (new PackageManagerShellCommand(this)).exec( 15475 this, in, out, err, args, resultReceiver); 15476 } 15477 15478 @Override 15479 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15480 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15481 != PackageManager.PERMISSION_GRANTED) { 15482 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15483 + Binder.getCallingPid() 15484 + ", uid=" + Binder.getCallingUid() 15485 + " without permission " 15486 + android.Manifest.permission.DUMP); 15487 return; 15488 } 15489 15490 DumpState dumpState = new DumpState(); 15491 boolean fullPreferred = false; 15492 boolean checkin = false; 15493 15494 String packageName = null; 15495 ArraySet<String> permissionNames = null; 15496 15497 int opti = 0; 15498 while (opti < args.length) { 15499 String opt = args[opti]; 15500 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15501 break; 15502 } 15503 opti++; 15504 15505 if ("-a".equals(opt)) { 15506 // Right now we only know how to print all. 15507 } else if ("-h".equals(opt)) { 15508 pw.println("Package manager dump options:"); 15509 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15510 pw.println(" --checkin: dump for a checkin"); 15511 pw.println(" -f: print details of intent filters"); 15512 pw.println(" -h: print this help"); 15513 pw.println(" cmd may be one of:"); 15514 pw.println(" l[ibraries]: list known shared libraries"); 15515 pw.println(" f[eatures]: list device features"); 15516 pw.println(" k[eysets]: print known keysets"); 15517 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15518 pw.println(" perm[issions]: dump permissions"); 15519 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15520 pw.println(" pref[erred]: print preferred package settings"); 15521 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15522 pw.println(" prov[iders]: dump content providers"); 15523 pw.println(" p[ackages]: dump installed packages"); 15524 pw.println(" s[hared-users]: dump shared user IDs"); 15525 pw.println(" m[essages]: print collected runtime messages"); 15526 pw.println(" v[erifiers]: print package verifier info"); 15527 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15528 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15529 pw.println(" version: print database version info"); 15530 pw.println(" write: write current settings now"); 15531 pw.println(" installs: details about install sessions"); 15532 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15533 pw.println(" <package.name>: info about given package"); 15534 return; 15535 } else if ("--checkin".equals(opt)) { 15536 checkin = true; 15537 } else if ("-f".equals(opt)) { 15538 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15539 } else { 15540 pw.println("Unknown argument: " + opt + "; use -h for help"); 15541 } 15542 } 15543 15544 // Is the caller requesting to dump a particular piece of data? 15545 if (opti < args.length) { 15546 String cmd = args[opti]; 15547 opti++; 15548 // Is this a package name? 15549 if ("android".equals(cmd) || cmd.contains(".")) { 15550 packageName = cmd; 15551 // When dumping a single package, we always dump all of its 15552 // filter information since the amount of data will be reasonable. 15553 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15554 } else if ("check-permission".equals(cmd)) { 15555 if (opti >= args.length) { 15556 pw.println("Error: check-permission missing permission argument"); 15557 return; 15558 } 15559 String perm = args[opti]; 15560 opti++; 15561 if (opti >= args.length) { 15562 pw.println("Error: check-permission missing package argument"); 15563 return; 15564 } 15565 String pkg = args[opti]; 15566 opti++; 15567 int user = UserHandle.getUserId(Binder.getCallingUid()); 15568 if (opti < args.length) { 15569 try { 15570 user = Integer.parseInt(args[opti]); 15571 } catch (NumberFormatException e) { 15572 pw.println("Error: check-permission user argument is not a number: " 15573 + args[opti]); 15574 return; 15575 } 15576 } 15577 pw.println(checkPermission(perm, pkg, user)); 15578 return; 15579 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15580 dumpState.setDump(DumpState.DUMP_LIBS); 15581 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15582 dumpState.setDump(DumpState.DUMP_FEATURES); 15583 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15584 if (opti >= args.length) { 15585 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15586 | DumpState.DUMP_SERVICE_RESOLVERS 15587 | DumpState.DUMP_RECEIVER_RESOLVERS 15588 | DumpState.DUMP_CONTENT_RESOLVERS); 15589 } else { 15590 while (opti < args.length) { 15591 String name = args[opti]; 15592 if ("a".equals(name) || "activity".equals(name)) { 15593 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15594 } else if ("s".equals(name) || "service".equals(name)) { 15595 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15596 } else if ("r".equals(name) || "receiver".equals(name)) { 15597 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15598 } else if ("c".equals(name) || "content".equals(name)) { 15599 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15600 } else { 15601 pw.println("Error: unknown resolver table type: " + name); 15602 return; 15603 } 15604 opti++; 15605 } 15606 } 15607 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15608 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15609 } else if ("permission".equals(cmd)) { 15610 if (opti >= args.length) { 15611 pw.println("Error: permission requires permission name"); 15612 return; 15613 } 15614 permissionNames = new ArraySet<>(); 15615 while (opti < args.length) { 15616 permissionNames.add(args[opti]); 15617 opti++; 15618 } 15619 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15620 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15621 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15622 dumpState.setDump(DumpState.DUMP_PREFERRED); 15623 } else if ("preferred-xml".equals(cmd)) { 15624 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15625 if (opti < args.length && "--full".equals(args[opti])) { 15626 fullPreferred = true; 15627 opti++; 15628 } 15629 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15630 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15631 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15632 dumpState.setDump(DumpState.DUMP_PACKAGES); 15633 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15634 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15635 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15636 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15637 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15638 dumpState.setDump(DumpState.DUMP_MESSAGES); 15639 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15640 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15641 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15642 || "intent-filter-verifiers".equals(cmd)) { 15643 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15644 } else if ("version".equals(cmd)) { 15645 dumpState.setDump(DumpState.DUMP_VERSION); 15646 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15647 dumpState.setDump(DumpState.DUMP_KEYSETS); 15648 } else if ("installs".equals(cmd)) { 15649 dumpState.setDump(DumpState.DUMP_INSTALLS); 15650 } else if ("write".equals(cmd)) { 15651 synchronized (mPackages) { 15652 mSettings.writeLPr(); 15653 pw.println("Settings written."); 15654 return; 15655 } 15656 } 15657 } 15658 15659 if (checkin) { 15660 pw.println("vers,1"); 15661 } 15662 15663 // reader 15664 synchronized (mPackages) { 15665 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15666 if (!checkin) { 15667 if (dumpState.onTitlePrinted()) 15668 pw.println(); 15669 pw.println("Database versions:"); 15670 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15671 } 15672 } 15673 15674 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15675 if (!checkin) { 15676 if (dumpState.onTitlePrinted()) 15677 pw.println(); 15678 pw.println("Verifiers:"); 15679 pw.print(" Required: "); 15680 pw.print(mRequiredVerifierPackage); 15681 pw.print(" (uid="); 15682 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15683 UserHandle.USER_SYSTEM)); 15684 pw.println(")"); 15685 } else if (mRequiredVerifierPackage != null) { 15686 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15687 pw.print(","); 15688 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15689 UserHandle.USER_SYSTEM)); 15690 } 15691 } 15692 15693 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15694 packageName == null) { 15695 if (mIntentFilterVerifierComponent != null) { 15696 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15697 if (!checkin) { 15698 if (dumpState.onTitlePrinted()) 15699 pw.println(); 15700 pw.println("Intent Filter Verifier:"); 15701 pw.print(" Using: "); 15702 pw.print(verifierPackageName); 15703 pw.print(" (uid="); 15704 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15705 UserHandle.USER_SYSTEM)); 15706 pw.println(")"); 15707 } else if (verifierPackageName != null) { 15708 pw.print("ifv,"); pw.print(verifierPackageName); 15709 pw.print(","); 15710 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15711 UserHandle.USER_SYSTEM)); 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