PackageManagerService.java revision 2bd31dbd023a11d90061c7b6831dd06454c928af
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 updateFlags(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 3137 // Safe mode means we should ignore any third-party apps 3138 if (mSafeMode) { 3139 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3140 } 3141 3142 return flags; 3143 } 3144 3145 /** 3146 * Update given flags when being used to request {@link PackageInfo}. 3147 */ 3148 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3149 boolean triaged = true; 3150 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3151 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3152 // Caller is asking for component details, so they'd better be 3153 // asking for specific encryption matching behavior, or be triaged 3154 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3155 | PackageManager.MATCH_ENCRYPTION_AWARE 3156 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3157 triaged = false; 3158 } 3159 } 3160 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3161 | PackageManager.MATCH_SYSTEM_ONLY 3162 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3163 triaged = false; 3164 } 3165 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3166 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3167 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3168 } 3169 return updateFlags(flags, userId); 3170 } 3171 3172 /** 3173 * Update given flags when being used to request {@link ApplicationInfo}. 3174 */ 3175 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3176 return updateFlagsForPackage(flags, userId, cookie); 3177 } 3178 3179 /** 3180 * Update given flags when being used to request {@link ComponentInfo}. 3181 */ 3182 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3183 if (cookie instanceof Intent) { 3184 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3185 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3186 } 3187 } 3188 3189 boolean triaged = true; 3190 // Caller is asking for component details, so they'd better be 3191 // asking for specific encryption matching behavior, or be triaged 3192 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3193 | PackageManager.MATCH_ENCRYPTION_AWARE 3194 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3195 triaged = false; 3196 } 3197 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3198 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3199 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3200 } 3201 return updateFlags(flags, userId); 3202 } 3203 3204 /** 3205 * Update given flags when being used to request {@link ResolveInfo}. 3206 */ 3207 private int updateFlagsForResolve(int flags, int userId, Object cookie) { 3208 return updateFlagsForComponent(flags, userId, cookie); 3209 } 3210 3211 @Override 3212 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3213 if (!sUserManager.exists(userId)) return null; 3214 flags = updateFlagsForComponent(flags, userId, component); 3215 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3216 synchronized (mPackages) { 3217 PackageParser.Activity a = mActivities.mActivities.get(component); 3218 3219 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3220 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3221 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3222 if (ps == null) return null; 3223 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3224 userId); 3225 } 3226 if (mResolveComponentName.equals(component)) { 3227 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3228 new PackageUserState(), userId); 3229 } 3230 } 3231 return null; 3232 } 3233 3234 @Override 3235 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3236 String resolvedType) { 3237 synchronized (mPackages) { 3238 if (component.equals(mResolveComponentName)) { 3239 // The resolver supports EVERYTHING! 3240 return true; 3241 } 3242 PackageParser.Activity a = mActivities.mActivities.get(component); 3243 if (a == null) { 3244 return false; 3245 } 3246 for (int i=0; i<a.intents.size(); i++) { 3247 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3248 intent.getData(), intent.getCategories(), TAG) >= 0) { 3249 return true; 3250 } 3251 } 3252 return false; 3253 } 3254 } 3255 3256 @Override 3257 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 flags = updateFlagsForComponent(flags, userId, component); 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3261 synchronized (mPackages) { 3262 PackageParser.Activity a = mReceivers.mActivities.get(component); 3263 if (DEBUG_PACKAGE_INFO) Log.v( 3264 TAG, "getReceiverInfo " + component + ": " + a); 3265 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3267 if (ps == null) return null; 3268 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3269 userId); 3270 } 3271 } 3272 return null; 3273 } 3274 3275 @Override 3276 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3277 if (!sUserManager.exists(userId)) return null; 3278 flags = updateFlagsForComponent(flags, userId, component); 3279 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3280 synchronized (mPackages) { 3281 PackageParser.Service s = mServices.mServices.get(component); 3282 if (DEBUG_PACKAGE_INFO) Log.v( 3283 TAG, "getServiceInfo " + component + ": " + s); 3284 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3285 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3286 if (ps == null) return null; 3287 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3288 userId); 3289 } 3290 } 3291 return null; 3292 } 3293 3294 @Override 3295 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3296 if (!sUserManager.exists(userId)) return null; 3297 flags = updateFlagsForComponent(flags, userId, component); 3298 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3299 synchronized (mPackages) { 3300 PackageParser.Provider p = mProviders.mProviders.get(component); 3301 if (DEBUG_PACKAGE_INFO) Log.v( 3302 TAG, "getProviderInfo " + component + ": " + p); 3303 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3304 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3305 if (ps == null) return null; 3306 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3307 userId); 3308 } 3309 } 3310 return null; 3311 } 3312 3313 @Override 3314 public String[] getSystemSharedLibraryNames() { 3315 Set<String> libSet; 3316 synchronized (mPackages) { 3317 libSet = mSharedLibraries.keySet(); 3318 int size = libSet.size(); 3319 if (size > 0) { 3320 String[] libs = new String[size]; 3321 libSet.toArray(libs); 3322 return libs; 3323 } 3324 } 3325 return null; 3326 } 3327 3328 /** 3329 * @hide 3330 */ 3331 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3332 synchronized (mPackages) { 3333 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3334 if (lib != null && lib.apk != null) { 3335 return mPackages.get(lib.apk); 3336 } 3337 } 3338 return null; 3339 } 3340 3341 @Override 3342 public FeatureInfo[] getSystemAvailableFeatures() { 3343 Collection<FeatureInfo> featSet; 3344 synchronized (mPackages) { 3345 featSet = mAvailableFeatures.values(); 3346 int size = featSet.size(); 3347 if (size > 0) { 3348 FeatureInfo[] features = new FeatureInfo[size+1]; 3349 featSet.toArray(features); 3350 FeatureInfo fi = new FeatureInfo(); 3351 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3352 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3353 features[size] = fi; 3354 return features; 3355 } 3356 } 3357 return null; 3358 } 3359 3360 @Override 3361 public boolean hasSystemFeature(String name) { 3362 synchronized (mPackages) { 3363 return mAvailableFeatures.containsKey(name); 3364 } 3365 } 3366 3367 @Override 3368 public int checkPermission(String permName, String pkgName, int userId) { 3369 if (!sUserManager.exists(userId)) { 3370 return PackageManager.PERMISSION_DENIED; 3371 } 3372 3373 synchronized (mPackages) { 3374 final PackageParser.Package p = mPackages.get(pkgName); 3375 if (p != null && p.mExtras != null) { 3376 final PackageSetting ps = (PackageSetting) p.mExtras; 3377 final PermissionsState permissionsState = ps.getPermissionsState(); 3378 if (permissionsState.hasPermission(permName, userId)) { 3379 return PackageManager.PERMISSION_GRANTED; 3380 } 3381 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3382 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3383 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3384 return PackageManager.PERMISSION_GRANTED; 3385 } 3386 } 3387 } 3388 3389 return PackageManager.PERMISSION_DENIED; 3390 } 3391 3392 @Override 3393 public int checkUidPermission(String permName, int uid) { 3394 final int userId = UserHandle.getUserId(uid); 3395 3396 if (!sUserManager.exists(userId)) { 3397 return PackageManager.PERMISSION_DENIED; 3398 } 3399 3400 synchronized (mPackages) { 3401 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3402 if (obj != null) { 3403 final SettingBase ps = (SettingBase) obj; 3404 final PermissionsState permissionsState = ps.getPermissionsState(); 3405 if (permissionsState.hasPermission(permName, userId)) { 3406 return PackageManager.PERMISSION_GRANTED; 3407 } 3408 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3409 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3410 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3411 return PackageManager.PERMISSION_GRANTED; 3412 } 3413 } else { 3414 ArraySet<String> perms = mSystemPermissions.get(uid); 3415 if (perms != null) { 3416 if (perms.contains(permName)) { 3417 return PackageManager.PERMISSION_GRANTED; 3418 } 3419 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3420 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3421 return PackageManager.PERMISSION_GRANTED; 3422 } 3423 } 3424 } 3425 } 3426 3427 return PackageManager.PERMISSION_DENIED; 3428 } 3429 3430 @Override 3431 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3432 if (UserHandle.getCallingUserId() != userId) { 3433 mContext.enforceCallingPermission( 3434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3435 "isPermissionRevokedByPolicy for user " + userId); 3436 } 3437 3438 if (checkPermission(permission, packageName, userId) 3439 == PackageManager.PERMISSION_GRANTED) { 3440 return false; 3441 } 3442 3443 final long identity = Binder.clearCallingIdentity(); 3444 try { 3445 final int flags = getPermissionFlags(permission, packageName, userId); 3446 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3447 } finally { 3448 Binder.restoreCallingIdentity(identity); 3449 } 3450 } 3451 3452 @Override 3453 public String getPermissionControllerPackageName() { 3454 synchronized (mPackages) { 3455 return mRequiredInstallerPackage; 3456 } 3457 } 3458 3459 /** 3460 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3461 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3462 * @param checkShell TODO(yamasani): 3463 * @param message the message to log on security exception 3464 */ 3465 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3466 boolean checkShell, String message) { 3467 if (userId < 0) { 3468 throw new IllegalArgumentException("Invalid userId " + userId); 3469 } 3470 if (checkShell) { 3471 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3472 } 3473 if (userId == UserHandle.getUserId(callingUid)) return; 3474 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3475 if (requireFullPermission) { 3476 mContext.enforceCallingOrSelfPermission( 3477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3478 } else { 3479 try { 3480 mContext.enforceCallingOrSelfPermission( 3481 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3482 } catch (SecurityException se) { 3483 mContext.enforceCallingOrSelfPermission( 3484 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3485 } 3486 } 3487 } 3488 } 3489 3490 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3491 if (callingUid == Process.SHELL_UID) { 3492 if (userHandle >= 0 3493 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3494 throw new SecurityException("Shell does not have permission to access user " 3495 + userHandle); 3496 } else if (userHandle < 0) { 3497 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3498 + Debug.getCallers(3)); 3499 } 3500 } 3501 } 3502 3503 private BasePermission findPermissionTreeLP(String permName) { 3504 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3505 if (permName.startsWith(bp.name) && 3506 permName.length() > bp.name.length() && 3507 permName.charAt(bp.name.length()) == '.') { 3508 return bp; 3509 } 3510 } 3511 return null; 3512 } 3513 3514 private BasePermission checkPermissionTreeLP(String permName) { 3515 if (permName != null) { 3516 BasePermission bp = findPermissionTreeLP(permName); 3517 if (bp != null) { 3518 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3519 return bp; 3520 } 3521 throw new SecurityException("Calling uid " 3522 + Binder.getCallingUid() 3523 + " is not allowed to add to permission tree " 3524 + bp.name + " owned by uid " + bp.uid); 3525 } 3526 } 3527 throw new SecurityException("No permission tree found for " + permName); 3528 } 3529 3530 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3531 if (s1 == null) { 3532 return s2 == null; 3533 } 3534 if (s2 == null) { 3535 return false; 3536 } 3537 if (s1.getClass() != s2.getClass()) { 3538 return false; 3539 } 3540 return s1.equals(s2); 3541 } 3542 3543 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3544 if (pi1.icon != pi2.icon) return false; 3545 if (pi1.logo != pi2.logo) return false; 3546 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3547 if (!compareStrings(pi1.name, pi2.name)) return false; 3548 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3549 // We'll take care of setting this one. 3550 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3551 // These are not currently stored in settings. 3552 //if (!compareStrings(pi1.group, pi2.group)) return false; 3553 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3554 //if (pi1.labelRes != pi2.labelRes) return false; 3555 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3556 return true; 3557 } 3558 3559 int permissionInfoFootprint(PermissionInfo info) { 3560 int size = info.name.length(); 3561 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3562 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3563 return size; 3564 } 3565 3566 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3567 int size = 0; 3568 for (BasePermission perm : mSettings.mPermissions.values()) { 3569 if (perm.uid == tree.uid) { 3570 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3571 } 3572 } 3573 return size; 3574 } 3575 3576 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3577 // We calculate the max size of permissions defined by this uid and throw 3578 // if that plus the size of 'info' would exceed our stated maximum. 3579 if (tree.uid != Process.SYSTEM_UID) { 3580 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3581 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3582 throw new SecurityException("Permission tree size cap exceeded"); 3583 } 3584 } 3585 } 3586 3587 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3588 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3589 throw new SecurityException("Label must be specified in permission"); 3590 } 3591 BasePermission tree = checkPermissionTreeLP(info.name); 3592 BasePermission bp = mSettings.mPermissions.get(info.name); 3593 boolean added = bp == null; 3594 boolean changed = true; 3595 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3596 if (added) { 3597 enforcePermissionCapLocked(info, tree); 3598 bp = new BasePermission(info.name, tree.sourcePackage, 3599 BasePermission.TYPE_DYNAMIC); 3600 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3601 throw new SecurityException( 3602 "Not allowed to modify non-dynamic permission " 3603 + info.name); 3604 } else { 3605 if (bp.protectionLevel == fixedLevel 3606 && bp.perm.owner.equals(tree.perm.owner) 3607 && bp.uid == tree.uid 3608 && comparePermissionInfos(bp.perm.info, info)) { 3609 changed = false; 3610 } 3611 } 3612 bp.protectionLevel = fixedLevel; 3613 info = new PermissionInfo(info); 3614 info.protectionLevel = fixedLevel; 3615 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3616 bp.perm.info.packageName = tree.perm.info.packageName; 3617 bp.uid = tree.uid; 3618 if (added) { 3619 mSettings.mPermissions.put(info.name, bp); 3620 } 3621 if (changed) { 3622 if (!async) { 3623 mSettings.writeLPr(); 3624 } else { 3625 scheduleWriteSettingsLocked(); 3626 } 3627 } 3628 return added; 3629 } 3630 3631 @Override 3632 public boolean addPermission(PermissionInfo info) { 3633 synchronized (mPackages) { 3634 return addPermissionLocked(info, false); 3635 } 3636 } 3637 3638 @Override 3639 public boolean addPermissionAsync(PermissionInfo info) { 3640 synchronized (mPackages) { 3641 return addPermissionLocked(info, true); 3642 } 3643 } 3644 3645 @Override 3646 public void removePermission(String name) { 3647 synchronized (mPackages) { 3648 checkPermissionTreeLP(name); 3649 BasePermission bp = mSettings.mPermissions.get(name); 3650 if (bp != null) { 3651 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3652 throw new SecurityException( 3653 "Not allowed to modify non-dynamic permission " 3654 + name); 3655 } 3656 mSettings.mPermissions.remove(name); 3657 mSettings.writeLPr(); 3658 } 3659 } 3660 } 3661 3662 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3663 BasePermission bp) { 3664 int index = pkg.requestedPermissions.indexOf(bp.name); 3665 if (index == -1) { 3666 throw new SecurityException("Package " + pkg.packageName 3667 + " has not requested permission " + bp.name); 3668 } 3669 if (!bp.isRuntime() && !bp.isDevelopment()) { 3670 throw new SecurityException("Permission " + bp.name 3671 + " is not a changeable permission type"); 3672 } 3673 } 3674 3675 @Override 3676 public void grantRuntimePermission(String packageName, String name, final int userId) { 3677 if (!sUserManager.exists(userId)) { 3678 Log.e(TAG, "No such user:" + userId); 3679 return; 3680 } 3681 3682 mContext.enforceCallingOrSelfPermission( 3683 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3684 "grantRuntimePermission"); 3685 3686 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3687 "grantRuntimePermission"); 3688 3689 final int uid; 3690 final SettingBase sb; 3691 3692 synchronized (mPackages) { 3693 final PackageParser.Package pkg = mPackages.get(packageName); 3694 if (pkg == null) { 3695 throw new IllegalArgumentException("Unknown package: " + packageName); 3696 } 3697 3698 final BasePermission bp = mSettings.mPermissions.get(name); 3699 if (bp == null) { 3700 throw new IllegalArgumentException("Unknown permission: " + name); 3701 } 3702 3703 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3704 3705 // If a permission review is required for legacy apps we represent 3706 // their permissions as always granted runtime ones since we need 3707 // to keep the review required permission flag per user while an 3708 // install permission's state is shared across all users. 3709 if (Build.PERMISSIONS_REVIEW_REQUIRED 3710 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3711 && bp.isRuntime()) { 3712 return; 3713 } 3714 3715 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3716 sb = (SettingBase) pkg.mExtras; 3717 if (sb == null) { 3718 throw new IllegalArgumentException("Unknown package: " + packageName); 3719 } 3720 3721 final PermissionsState permissionsState = sb.getPermissionsState(); 3722 3723 final int flags = permissionsState.getPermissionFlags(name, userId); 3724 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3725 throw new SecurityException("Cannot grant system fixed permission " 3726 + name + " for package " + packageName); 3727 } 3728 3729 if (bp.isDevelopment()) { 3730 // Development permissions must be handled specially, since they are not 3731 // normal runtime permissions. For now they apply to all users. 3732 if (permissionsState.grantInstallPermission(bp) != 3733 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3734 scheduleWriteSettingsLocked(); 3735 } 3736 return; 3737 } 3738 3739 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3740 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3741 return; 3742 } 3743 3744 final int result = permissionsState.grantRuntimePermission(bp, userId); 3745 switch (result) { 3746 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3747 return; 3748 } 3749 3750 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3751 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3752 mHandler.post(new Runnable() { 3753 @Override 3754 public void run() { 3755 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3756 } 3757 }); 3758 } 3759 break; 3760 } 3761 3762 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3763 3764 // Not critical if that is lost - app has to request again. 3765 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3766 } 3767 3768 // Only need to do this if user is initialized. Otherwise it's a new user 3769 // and there are no processes running as the user yet and there's no need 3770 // to make an expensive call to remount processes for the changed permissions. 3771 if (READ_EXTERNAL_STORAGE.equals(name) 3772 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3773 final long token = Binder.clearCallingIdentity(); 3774 try { 3775 if (sUserManager.isInitialized(userId)) { 3776 MountServiceInternal mountServiceInternal = LocalServices.getService( 3777 MountServiceInternal.class); 3778 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3779 } 3780 } finally { 3781 Binder.restoreCallingIdentity(token); 3782 } 3783 } 3784 } 3785 3786 @Override 3787 public void revokeRuntimePermission(String packageName, String name, int userId) { 3788 if (!sUserManager.exists(userId)) { 3789 Log.e(TAG, "No such user:" + userId); 3790 return; 3791 } 3792 3793 mContext.enforceCallingOrSelfPermission( 3794 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3795 "revokeRuntimePermission"); 3796 3797 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3798 "revokeRuntimePermission"); 3799 3800 final int appId; 3801 3802 synchronized (mPackages) { 3803 final PackageParser.Package pkg = mPackages.get(packageName); 3804 if (pkg == null) { 3805 throw new IllegalArgumentException("Unknown package: " + packageName); 3806 } 3807 3808 final BasePermission bp = mSettings.mPermissions.get(name); 3809 if (bp == null) { 3810 throw new IllegalArgumentException("Unknown permission: " + name); 3811 } 3812 3813 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3814 3815 // If a permission review is required for legacy apps we represent 3816 // their permissions as always granted runtime ones since we need 3817 // to keep the review required permission flag per user while an 3818 // install permission's state is shared across all users. 3819 if (Build.PERMISSIONS_REVIEW_REQUIRED 3820 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3821 && bp.isRuntime()) { 3822 return; 3823 } 3824 3825 SettingBase sb = (SettingBase) pkg.mExtras; 3826 if (sb == null) { 3827 throw new IllegalArgumentException("Unknown package: " + packageName); 3828 } 3829 3830 final PermissionsState permissionsState = sb.getPermissionsState(); 3831 3832 final int flags = permissionsState.getPermissionFlags(name, userId); 3833 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3834 throw new SecurityException("Cannot revoke system fixed permission " 3835 + name + " for package " + packageName); 3836 } 3837 3838 if (bp.isDevelopment()) { 3839 // Development permissions must be handled specially, since they are not 3840 // normal runtime permissions. For now they apply to all users. 3841 if (permissionsState.revokeInstallPermission(bp) != 3842 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3843 scheduleWriteSettingsLocked(); 3844 } 3845 return; 3846 } 3847 3848 if (permissionsState.revokeRuntimePermission(bp, userId) == 3849 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3850 return; 3851 } 3852 3853 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3854 3855 // Critical, after this call app should never have the permission. 3856 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3857 3858 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3859 } 3860 3861 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3862 } 3863 3864 @Override 3865 public void resetRuntimePermissions() { 3866 mContext.enforceCallingOrSelfPermission( 3867 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3868 "revokeRuntimePermission"); 3869 3870 int callingUid = Binder.getCallingUid(); 3871 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3872 mContext.enforceCallingOrSelfPermission( 3873 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3874 "resetRuntimePermissions"); 3875 } 3876 3877 synchronized (mPackages) { 3878 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3879 for (int userId : UserManagerService.getInstance().getUserIds()) { 3880 final int packageCount = mPackages.size(); 3881 for (int i = 0; i < packageCount; i++) { 3882 PackageParser.Package pkg = mPackages.valueAt(i); 3883 if (!(pkg.mExtras instanceof PackageSetting)) { 3884 continue; 3885 } 3886 PackageSetting ps = (PackageSetting) pkg.mExtras; 3887 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3888 } 3889 } 3890 } 3891 } 3892 3893 @Override 3894 public int getPermissionFlags(String name, String packageName, int userId) { 3895 if (!sUserManager.exists(userId)) { 3896 return 0; 3897 } 3898 3899 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3900 3901 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3902 "getPermissionFlags"); 3903 3904 synchronized (mPackages) { 3905 final PackageParser.Package pkg = mPackages.get(packageName); 3906 if (pkg == null) { 3907 throw new IllegalArgumentException("Unknown package: " + packageName); 3908 } 3909 3910 final BasePermission bp = mSettings.mPermissions.get(name); 3911 if (bp == null) { 3912 throw new IllegalArgumentException("Unknown permission: " + name); 3913 } 3914 3915 SettingBase sb = (SettingBase) pkg.mExtras; 3916 if (sb == null) { 3917 throw new IllegalArgumentException("Unknown package: " + packageName); 3918 } 3919 3920 PermissionsState permissionsState = sb.getPermissionsState(); 3921 return permissionsState.getPermissionFlags(name, userId); 3922 } 3923 } 3924 3925 @Override 3926 public void updatePermissionFlags(String name, String packageName, int flagMask, 3927 int flagValues, int userId) { 3928 if (!sUserManager.exists(userId)) { 3929 return; 3930 } 3931 3932 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3933 3934 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3935 "updatePermissionFlags"); 3936 3937 // Only the system can change these flags and nothing else. 3938 if (getCallingUid() != Process.SYSTEM_UID) { 3939 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3940 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3941 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3942 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3943 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3944 } 3945 3946 synchronized (mPackages) { 3947 final PackageParser.Package pkg = mPackages.get(packageName); 3948 if (pkg == null) { 3949 throw new IllegalArgumentException("Unknown package: " + packageName); 3950 } 3951 3952 final BasePermission bp = mSettings.mPermissions.get(name); 3953 if (bp == null) { 3954 throw new IllegalArgumentException("Unknown permission: " + name); 3955 } 3956 3957 SettingBase sb = (SettingBase) pkg.mExtras; 3958 if (sb == null) { 3959 throw new IllegalArgumentException("Unknown package: " + packageName); 3960 } 3961 3962 PermissionsState permissionsState = sb.getPermissionsState(); 3963 3964 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 3965 3966 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3967 // Install and runtime permissions are stored in different places, 3968 // so figure out what permission changed and persist the change. 3969 if (permissionsState.getInstallPermissionState(name) != null) { 3970 scheduleWriteSettingsLocked(); 3971 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 3972 || hadState) { 3973 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3974 } 3975 } 3976 } 3977 } 3978 3979 /** 3980 * Update the permission flags for all packages and runtime permissions of a user in order 3981 * to allow device or profile owner to remove POLICY_FIXED. 3982 */ 3983 @Override 3984 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 3985 if (!sUserManager.exists(userId)) { 3986 return; 3987 } 3988 3989 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 3990 3991 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3992 "updatePermissionFlagsForAllApps"); 3993 3994 // Only the system can change system fixed flags. 3995 if (getCallingUid() != Process.SYSTEM_UID) { 3996 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3997 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3998 } 3999 4000 synchronized (mPackages) { 4001 boolean changed = false; 4002 final int packageCount = mPackages.size(); 4003 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4004 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4005 SettingBase sb = (SettingBase) pkg.mExtras; 4006 if (sb == null) { 4007 continue; 4008 } 4009 PermissionsState permissionsState = sb.getPermissionsState(); 4010 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4011 userId, flagMask, flagValues); 4012 } 4013 if (changed) { 4014 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4015 } 4016 } 4017 } 4018 4019 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4020 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4021 != PackageManager.PERMISSION_GRANTED 4022 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4023 != PackageManager.PERMISSION_GRANTED) { 4024 throw new SecurityException(message + " requires " 4025 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4026 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4027 } 4028 } 4029 4030 @Override 4031 public boolean shouldShowRequestPermissionRationale(String permissionName, 4032 String packageName, int userId) { 4033 if (UserHandle.getCallingUserId() != userId) { 4034 mContext.enforceCallingPermission( 4035 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4036 "canShowRequestPermissionRationale for user " + userId); 4037 } 4038 4039 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4040 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4041 return false; 4042 } 4043 4044 if (checkPermission(permissionName, packageName, userId) 4045 == PackageManager.PERMISSION_GRANTED) { 4046 return false; 4047 } 4048 4049 final int flags; 4050 4051 final long identity = Binder.clearCallingIdentity(); 4052 try { 4053 flags = getPermissionFlags(permissionName, 4054 packageName, userId); 4055 } finally { 4056 Binder.restoreCallingIdentity(identity); 4057 } 4058 4059 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4060 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4061 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4062 4063 if ((flags & fixedFlags) != 0) { 4064 return false; 4065 } 4066 4067 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4068 } 4069 4070 @Override 4071 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4072 mContext.enforceCallingOrSelfPermission( 4073 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4074 "addOnPermissionsChangeListener"); 4075 4076 synchronized (mPackages) { 4077 mOnPermissionChangeListeners.addListenerLocked(listener); 4078 } 4079 } 4080 4081 @Override 4082 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4083 synchronized (mPackages) { 4084 mOnPermissionChangeListeners.removeListenerLocked(listener); 4085 } 4086 } 4087 4088 @Override 4089 public boolean isProtectedBroadcast(String actionName) { 4090 synchronized (mPackages) { 4091 if (mProtectedBroadcasts.contains(actionName)) { 4092 return true; 4093 } else if (actionName != null) { 4094 // TODO: remove these terrible hacks 4095 if (actionName.startsWith("android.net.netmon.lingerExpired") 4096 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4097 return true; 4098 } 4099 } 4100 } 4101 return false; 4102 } 4103 4104 @Override 4105 public int checkSignatures(String pkg1, String pkg2) { 4106 synchronized (mPackages) { 4107 final PackageParser.Package p1 = mPackages.get(pkg1); 4108 final PackageParser.Package p2 = mPackages.get(pkg2); 4109 if (p1 == null || p1.mExtras == null 4110 || p2 == null || p2.mExtras == null) { 4111 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4112 } 4113 return compareSignatures(p1.mSignatures, p2.mSignatures); 4114 } 4115 } 4116 4117 @Override 4118 public int checkUidSignatures(int uid1, int uid2) { 4119 // Map to base uids. 4120 uid1 = UserHandle.getAppId(uid1); 4121 uid2 = UserHandle.getAppId(uid2); 4122 // reader 4123 synchronized (mPackages) { 4124 Signature[] s1; 4125 Signature[] s2; 4126 Object obj = mSettings.getUserIdLPr(uid1); 4127 if (obj != null) { 4128 if (obj instanceof SharedUserSetting) { 4129 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4130 } else if (obj instanceof PackageSetting) { 4131 s1 = ((PackageSetting)obj).signatures.mSignatures; 4132 } else { 4133 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4134 } 4135 } else { 4136 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4137 } 4138 obj = mSettings.getUserIdLPr(uid2); 4139 if (obj != null) { 4140 if (obj instanceof SharedUserSetting) { 4141 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4142 } else if (obj instanceof PackageSetting) { 4143 s2 = ((PackageSetting)obj).signatures.mSignatures; 4144 } else { 4145 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4146 } 4147 } else { 4148 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4149 } 4150 return compareSignatures(s1, s2); 4151 } 4152 } 4153 4154 private void killUid(int appId, int userId, String reason) { 4155 final long identity = Binder.clearCallingIdentity(); 4156 try { 4157 IActivityManager am = ActivityManagerNative.getDefault(); 4158 if (am != null) { 4159 try { 4160 am.killUid(appId, userId, reason); 4161 } catch (RemoteException e) { 4162 /* ignore - same process */ 4163 } 4164 } 4165 } finally { 4166 Binder.restoreCallingIdentity(identity); 4167 } 4168 } 4169 4170 /** 4171 * Compares two sets of signatures. Returns: 4172 * <br /> 4173 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4174 * <br /> 4175 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4176 * <br /> 4177 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4178 * <br /> 4179 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4180 * <br /> 4181 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4182 */ 4183 static int compareSignatures(Signature[] s1, Signature[] s2) { 4184 if (s1 == null) { 4185 return s2 == null 4186 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4187 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4188 } 4189 4190 if (s2 == null) { 4191 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4192 } 4193 4194 if (s1.length != s2.length) { 4195 return PackageManager.SIGNATURE_NO_MATCH; 4196 } 4197 4198 // Since both signature sets are of size 1, we can compare without HashSets. 4199 if (s1.length == 1) { 4200 return s1[0].equals(s2[0]) ? 4201 PackageManager.SIGNATURE_MATCH : 4202 PackageManager.SIGNATURE_NO_MATCH; 4203 } 4204 4205 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4206 for (Signature sig : s1) { 4207 set1.add(sig); 4208 } 4209 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4210 for (Signature sig : s2) { 4211 set2.add(sig); 4212 } 4213 // Make sure s2 contains all signatures in s1. 4214 if (set1.equals(set2)) { 4215 return PackageManager.SIGNATURE_MATCH; 4216 } 4217 return PackageManager.SIGNATURE_NO_MATCH; 4218 } 4219 4220 /** 4221 * If the database version for this type of package (internal storage or 4222 * external storage) is less than the version where package signatures 4223 * were updated, return true. 4224 */ 4225 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4226 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4227 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4228 } 4229 4230 /** 4231 * Used for backward compatibility to make sure any packages with 4232 * certificate chains get upgraded to the new style. {@code existingSigs} 4233 * will be in the old format (since they were stored on disk from before the 4234 * system upgrade) and {@code scannedSigs} will be in the newer format. 4235 */ 4236 private int compareSignaturesCompat(PackageSignatures existingSigs, 4237 PackageParser.Package scannedPkg) { 4238 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4239 return PackageManager.SIGNATURE_NO_MATCH; 4240 } 4241 4242 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4243 for (Signature sig : existingSigs.mSignatures) { 4244 existingSet.add(sig); 4245 } 4246 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4247 for (Signature sig : scannedPkg.mSignatures) { 4248 try { 4249 Signature[] chainSignatures = sig.getChainSignatures(); 4250 for (Signature chainSig : chainSignatures) { 4251 scannedCompatSet.add(chainSig); 4252 } 4253 } catch (CertificateEncodingException e) { 4254 scannedCompatSet.add(sig); 4255 } 4256 } 4257 /* 4258 * Make sure the expanded scanned set contains all signatures in the 4259 * existing one. 4260 */ 4261 if (scannedCompatSet.equals(existingSet)) { 4262 // Migrate the old signatures to the new scheme. 4263 existingSigs.assignSignatures(scannedPkg.mSignatures); 4264 // The new KeySets will be re-added later in the scanning process. 4265 synchronized (mPackages) { 4266 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4267 } 4268 return PackageManager.SIGNATURE_MATCH; 4269 } 4270 return PackageManager.SIGNATURE_NO_MATCH; 4271 } 4272 4273 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4274 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4275 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4276 } 4277 4278 private int compareSignaturesRecover(PackageSignatures existingSigs, 4279 PackageParser.Package scannedPkg) { 4280 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4281 return PackageManager.SIGNATURE_NO_MATCH; 4282 } 4283 4284 String msg = null; 4285 try { 4286 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4287 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4288 + scannedPkg.packageName); 4289 return PackageManager.SIGNATURE_MATCH; 4290 } 4291 } catch (CertificateException e) { 4292 msg = e.getMessage(); 4293 } 4294 4295 logCriticalInfo(Log.INFO, 4296 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4297 return PackageManager.SIGNATURE_NO_MATCH; 4298 } 4299 4300 @Override 4301 public String[] getPackagesForUid(int uid) { 4302 uid = UserHandle.getAppId(uid); 4303 // reader 4304 synchronized (mPackages) { 4305 Object obj = mSettings.getUserIdLPr(uid); 4306 if (obj instanceof SharedUserSetting) { 4307 final SharedUserSetting sus = (SharedUserSetting) obj; 4308 final int N = sus.packages.size(); 4309 final String[] res = new String[N]; 4310 final Iterator<PackageSetting> it = sus.packages.iterator(); 4311 int i = 0; 4312 while (it.hasNext()) { 4313 res[i++] = it.next().name; 4314 } 4315 return res; 4316 } else if (obj instanceof PackageSetting) { 4317 final PackageSetting ps = (PackageSetting) obj; 4318 return new String[] { ps.name }; 4319 } 4320 } 4321 return null; 4322 } 4323 4324 @Override 4325 public String getNameForUid(int uid) { 4326 // reader 4327 synchronized (mPackages) { 4328 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4329 if (obj instanceof SharedUserSetting) { 4330 final SharedUserSetting sus = (SharedUserSetting) obj; 4331 return sus.name + ":" + sus.userId; 4332 } else if (obj instanceof PackageSetting) { 4333 final PackageSetting ps = (PackageSetting) obj; 4334 return ps.name; 4335 } 4336 } 4337 return null; 4338 } 4339 4340 @Override 4341 public int getUidForSharedUser(String sharedUserName) { 4342 if(sharedUserName == null) { 4343 return -1; 4344 } 4345 // reader 4346 synchronized (mPackages) { 4347 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4348 if (suid == null) { 4349 return -1; 4350 } 4351 return suid.userId; 4352 } 4353 } 4354 4355 @Override 4356 public int getFlagsForUid(int uid) { 4357 synchronized (mPackages) { 4358 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4359 if (obj instanceof SharedUserSetting) { 4360 final SharedUserSetting sus = (SharedUserSetting) obj; 4361 return sus.pkgFlags; 4362 } else if (obj instanceof PackageSetting) { 4363 final PackageSetting ps = (PackageSetting) obj; 4364 return ps.pkgFlags; 4365 } 4366 } 4367 return 0; 4368 } 4369 4370 @Override 4371 public int getPrivateFlagsForUid(int uid) { 4372 synchronized (mPackages) { 4373 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4374 if (obj instanceof SharedUserSetting) { 4375 final SharedUserSetting sus = (SharedUserSetting) obj; 4376 return sus.pkgPrivateFlags; 4377 } else if (obj instanceof PackageSetting) { 4378 final PackageSetting ps = (PackageSetting) obj; 4379 return ps.pkgPrivateFlags; 4380 } 4381 } 4382 return 0; 4383 } 4384 4385 @Override 4386 public boolean isUidPrivileged(int uid) { 4387 uid = UserHandle.getAppId(uid); 4388 // reader 4389 synchronized (mPackages) { 4390 Object obj = mSettings.getUserIdLPr(uid); 4391 if (obj instanceof SharedUserSetting) { 4392 final SharedUserSetting sus = (SharedUserSetting) obj; 4393 final Iterator<PackageSetting> it = sus.packages.iterator(); 4394 while (it.hasNext()) { 4395 if (it.next().isPrivileged()) { 4396 return true; 4397 } 4398 } 4399 } else if (obj instanceof PackageSetting) { 4400 final PackageSetting ps = (PackageSetting) obj; 4401 return ps.isPrivileged(); 4402 } 4403 } 4404 return false; 4405 } 4406 4407 @Override 4408 public String[] getAppOpPermissionPackages(String permissionName) { 4409 synchronized (mPackages) { 4410 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4411 if (pkgs == null) { 4412 return null; 4413 } 4414 return pkgs.toArray(new String[pkgs.size()]); 4415 } 4416 } 4417 4418 @Override 4419 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4420 int flags, int userId) { 4421 if (!sUserManager.exists(userId)) return null; 4422 flags = updateFlagsForResolve(flags, userId, intent); 4423 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4424 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4425 final ResolveInfo bestChoice = 4426 chooseBestActivity(intent, resolvedType, flags, query, userId); 4427 4428 if (isEphemeralAllowed(intent, query, userId)) { 4429 final EphemeralResolveInfo ai = 4430 getEphemeralResolveInfo(intent, resolvedType, userId); 4431 if (ai != null) { 4432 if (DEBUG_EPHEMERAL) { 4433 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4434 } 4435 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4436 bestChoice.ephemeralResolveInfo = ai; 4437 } 4438 } 4439 return bestChoice; 4440 } 4441 4442 @Override 4443 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4444 IntentFilter filter, int match, ComponentName activity) { 4445 final int userId = UserHandle.getCallingUserId(); 4446 if (DEBUG_PREFERRED) { 4447 Log.v(TAG, "setLastChosenActivity intent=" + intent 4448 + " resolvedType=" + resolvedType 4449 + " flags=" + flags 4450 + " filter=" + filter 4451 + " match=" + match 4452 + " activity=" + activity); 4453 filter.dump(new PrintStreamPrinter(System.out), " "); 4454 } 4455 intent.setComponent(null); 4456 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4457 // Find any earlier preferred or last chosen entries and nuke them 4458 findPreferredActivity(intent, resolvedType, 4459 flags, query, 0, false, true, false, userId); 4460 // Add the new activity as the last chosen for this filter 4461 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4462 "Setting last chosen"); 4463 } 4464 4465 @Override 4466 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4467 final int userId = UserHandle.getCallingUserId(); 4468 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4469 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4470 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4471 false, false, false, userId); 4472 } 4473 4474 4475 private boolean isEphemeralAllowed( 4476 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4477 // Short circuit and return early if possible. 4478 final int callingUser = UserHandle.getCallingUserId(); 4479 if (callingUser != UserHandle.USER_SYSTEM) { 4480 return false; 4481 } 4482 if (mEphemeralResolverConnection == null) { 4483 return false; 4484 } 4485 if (intent.getComponent() != null) { 4486 return false; 4487 } 4488 if (intent.getPackage() != null) { 4489 return false; 4490 } 4491 final boolean isWebUri = hasWebURI(intent); 4492 if (!isWebUri) { 4493 return false; 4494 } 4495 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4496 synchronized (mPackages) { 4497 final int count = resolvedActivites.size(); 4498 for (int n = 0; n < count; n++) { 4499 ResolveInfo info = resolvedActivites.get(n); 4500 String packageName = info.activityInfo.packageName; 4501 PackageSetting ps = mSettings.mPackages.get(packageName); 4502 if (ps != null) { 4503 // Try to get the status from User settings first 4504 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4505 int status = (int) (packedStatus >> 32); 4506 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4507 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4508 if (DEBUG_EPHEMERAL) { 4509 Slog.v(TAG, "DENY ephemeral apps;" 4510 + " pkg: " + packageName + ", status: " + status); 4511 } 4512 return false; 4513 } 4514 } 4515 } 4516 } 4517 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4518 return true; 4519 } 4520 4521 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4522 int userId) { 4523 MessageDigest digest = null; 4524 try { 4525 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4526 } catch (NoSuchAlgorithmException e) { 4527 // If we can't create a digest, ignore ephemeral apps. 4528 return null; 4529 } 4530 4531 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4532 final byte[] digestBytes = digest.digest(hostBytes); 4533 int shaPrefix = 4534 digestBytes[0] << 24 4535 | digestBytes[1] << 16 4536 | digestBytes[2] << 8 4537 | digestBytes[3] << 0; 4538 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4539 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4540 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4541 // No hash prefix match; there are no ephemeral apps for this domain. 4542 return null; 4543 } 4544 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4545 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4546 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4547 continue; 4548 } 4549 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4550 // No filters; this should never happen. 4551 if (filters.isEmpty()) { 4552 continue; 4553 } 4554 // We have a domain match; resolve the filters to see if anything matches. 4555 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4556 for (int j = filters.size() - 1; j >= 0; --j) { 4557 final EphemeralResolveIntentInfo intentInfo = 4558 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4559 ephemeralResolver.addFilter(intentInfo); 4560 } 4561 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4562 intent, resolvedType, false /*defaultOnly*/, userId); 4563 if (!matchedResolveInfoList.isEmpty()) { 4564 return matchedResolveInfoList.get(0); 4565 } 4566 } 4567 // Hash or filter mis-match; no ephemeral apps for this domain. 4568 return null; 4569 } 4570 4571 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4572 int flags, List<ResolveInfo> query, int userId) { 4573 if (query != null) { 4574 final int N = query.size(); 4575 if (N == 1) { 4576 return query.get(0); 4577 } else if (N > 1) { 4578 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4579 // If there is more than one activity with the same priority, 4580 // then let the user decide between them. 4581 ResolveInfo r0 = query.get(0); 4582 ResolveInfo r1 = query.get(1); 4583 if (DEBUG_INTENT_MATCHING || debug) { 4584 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4585 + r1.activityInfo.name + "=" + r1.priority); 4586 } 4587 // If the first activity has a higher priority, or a different 4588 // default, then it is always desirable to pick it. 4589 if (r0.priority != r1.priority 4590 || r0.preferredOrder != r1.preferredOrder 4591 || r0.isDefault != r1.isDefault) { 4592 return query.get(0); 4593 } 4594 // If we have saved a preference for a preferred activity for 4595 // this Intent, use that. 4596 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4597 flags, query, r0.priority, true, false, debug, userId); 4598 if (ri != null) { 4599 return ri; 4600 } 4601 ri = new ResolveInfo(mResolveInfo); 4602 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4603 ri.activityInfo.applicationInfo = new ApplicationInfo( 4604 ri.activityInfo.applicationInfo); 4605 if (userId != 0) { 4606 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4607 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4608 } 4609 // Make sure that the resolver is displayable in car mode 4610 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4611 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4612 return ri; 4613 } 4614 } 4615 return null; 4616 } 4617 4618 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4619 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4620 final int N = query.size(); 4621 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4622 .get(userId); 4623 // Get the list of persistent preferred activities that handle the intent 4624 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4625 List<PersistentPreferredActivity> pprefs = ppir != null 4626 ? ppir.queryIntent(intent, resolvedType, 4627 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4628 : null; 4629 if (pprefs != null && pprefs.size() > 0) { 4630 final int M = pprefs.size(); 4631 for (int i=0; i<M; i++) { 4632 final PersistentPreferredActivity ppa = pprefs.get(i); 4633 if (DEBUG_PREFERRED || debug) { 4634 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4635 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4636 + "\n component=" + ppa.mComponent); 4637 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4638 } 4639 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4640 flags | MATCH_DISABLED_COMPONENTS, userId); 4641 if (DEBUG_PREFERRED || debug) { 4642 Slog.v(TAG, "Found persistent preferred activity:"); 4643 if (ai != null) { 4644 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4645 } else { 4646 Slog.v(TAG, " null"); 4647 } 4648 } 4649 if (ai == null) { 4650 // This previously registered persistent preferred activity 4651 // component is no longer known. Ignore it and do NOT remove it. 4652 continue; 4653 } 4654 for (int j=0; j<N; j++) { 4655 final ResolveInfo ri = query.get(j); 4656 if (!ri.activityInfo.applicationInfo.packageName 4657 .equals(ai.applicationInfo.packageName)) { 4658 continue; 4659 } 4660 if (!ri.activityInfo.name.equals(ai.name)) { 4661 continue; 4662 } 4663 // Found a persistent preference that can handle the intent. 4664 if (DEBUG_PREFERRED || debug) { 4665 Slog.v(TAG, "Returning persistent preferred activity: " + 4666 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4667 } 4668 return ri; 4669 } 4670 } 4671 } 4672 return null; 4673 } 4674 4675 // TODO: handle preferred activities missing while user has amnesia 4676 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4677 List<ResolveInfo> query, int priority, boolean always, 4678 boolean removeMatches, boolean debug, int userId) { 4679 if (!sUserManager.exists(userId)) return null; 4680 flags = updateFlagsForResolve(flags, userId, intent); 4681 // writer 4682 synchronized (mPackages) { 4683 if (intent.getSelector() != null) { 4684 intent = intent.getSelector(); 4685 } 4686 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4687 4688 // Try to find a matching persistent preferred activity. 4689 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4690 debug, userId); 4691 4692 // If a persistent preferred activity matched, use it. 4693 if (pri != null) { 4694 return pri; 4695 } 4696 4697 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4698 // Get the list of preferred activities that handle the intent 4699 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4700 List<PreferredActivity> prefs = pir != null 4701 ? pir.queryIntent(intent, resolvedType, 4702 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4703 : null; 4704 if (prefs != null && prefs.size() > 0) { 4705 boolean changed = false; 4706 try { 4707 // First figure out how good the original match set is. 4708 // We will only allow preferred activities that came 4709 // from the same match quality. 4710 int match = 0; 4711 4712 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4713 4714 final int N = query.size(); 4715 for (int j=0; j<N; j++) { 4716 final ResolveInfo ri = query.get(j); 4717 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4718 + ": 0x" + Integer.toHexString(match)); 4719 if (ri.match > match) { 4720 match = ri.match; 4721 } 4722 } 4723 4724 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4725 + Integer.toHexString(match)); 4726 4727 match &= IntentFilter.MATCH_CATEGORY_MASK; 4728 final int M = prefs.size(); 4729 for (int i=0; i<M; i++) { 4730 final PreferredActivity pa = prefs.get(i); 4731 if (DEBUG_PREFERRED || debug) { 4732 Slog.v(TAG, "Checking PreferredActivity ds=" 4733 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4734 + "\n component=" + pa.mPref.mComponent); 4735 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4736 } 4737 if (pa.mPref.mMatch != match) { 4738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4739 + Integer.toHexString(pa.mPref.mMatch)); 4740 continue; 4741 } 4742 // If it's not an "always" type preferred activity and that's what we're 4743 // looking for, skip it. 4744 if (always && !pa.mPref.mAlways) { 4745 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4746 continue; 4747 } 4748 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4749 flags | MATCH_DISABLED_COMPONENTS, userId); 4750 if (DEBUG_PREFERRED || debug) { 4751 Slog.v(TAG, "Found preferred activity:"); 4752 if (ai != null) { 4753 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4754 } else { 4755 Slog.v(TAG, " null"); 4756 } 4757 } 4758 if (ai == null) { 4759 // This previously registered preferred activity 4760 // component is no longer known. Most likely an update 4761 // to the app was installed and in the new version this 4762 // component no longer exists. Clean it up by removing 4763 // it from the preferred activities list, and skip it. 4764 Slog.w(TAG, "Removing dangling preferred activity: " 4765 + pa.mPref.mComponent); 4766 pir.removeFilter(pa); 4767 changed = true; 4768 continue; 4769 } 4770 for (int j=0; j<N; j++) { 4771 final ResolveInfo ri = query.get(j); 4772 if (!ri.activityInfo.applicationInfo.packageName 4773 .equals(ai.applicationInfo.packageName)) { 4774 continue; 4775 } 4776 if (!ri.activityInfo.name.equals(ai.name)) { 4777 continue; 4778 } 4779 4780 if (removeMatches) { 4781 pir.removeFilter(pa); 4782 changed = true; 4783 if (DEBUG_PREFERRED) { 4784 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4785 } 4786 break; 4787 } 4788 4789 // Okay we found a previously set preferred or last chosen app. 4790 // If the result set is different from when this 4791 // was created, we need to clear it and re-ask the 4792 // user their preference, if we're looking for an "always" type entry. 4793 if (always && !pa.mPref.sameSet(query)) { 4794 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4795 + intent + " type " + resolvedType); 4796 if (DEBUG_PREFERRED) { 4797 Slog.v(TAG, "Removing preferred activity since set changed " 4798 + pa.mPref.mComponent); 4799 } 4800 pir.removeFilter(pa); 4801 // Re-add the filter as a "last chosen" entry (!always) 4802 PreferredActivity lastChosen = new PreferredActivity( 4803 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4804 pir.addFilter(lastChosen); 4805 changed = true; 4806 return null; 4807 } 4808 4809 // Yay! Either the set matched or we're looking for the last chosen 4810 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4811 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4812 return ri; 4813 } 4814 } 4815 } finally { 4816 if (changed) { 4817 if (DEBUG_PREFERRED) { 4818 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4819 } 4820 scheduleWritePackageRestrictionsLocked(userId); 4821 } 4822 } 4823 } 4824 } 4825 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4826 return null; 4827 } 4828 4829 /* 4830 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4831 */ 4832 @Override 4833 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4834 int targetUserId) { 4835 mContext.enforceCallingOrSelfPermission( 4836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4837 List<CrossProfileIntentFilter> matches = 4838 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4839 if (matches != null) { 4840 int size = matches.size(); 4841 for (int i = 0; i < size; i++) { 4842 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4843 } 4844 } 4845 if (hasWebURI(intent)) { 4846 // cross-profile app linking works only towards the parent. 4847 final UserInfo parent = getProfileParent(sourceUserId); 4848 synchronized(mPackages) { 4849 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4850 intent, resolvedType, 0, sourceUserId, parent.id); 4851 return xpDomainInfo != null; 4852 } 4853 } 4854 return false; 4855 } 4856 4857 private UserInfo getProfileParent(int userId) { 4858 final long identity = Binder.clearCallingIdentity(); 4859 try { 4860 return sUserManager.getProfileParent(userId); 4861 } finally { 4862 Binder.restoreCallingIdentity(identity); 4863 } 4864 } 4865 4866 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4867 String resolvedType, int userId) { 4868 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4869 if (resolver != null) { 4870 return resolver.queryIntent(intent, resolvedType, false, userId); 4871 } 4872 return null; 4873 } 4874 4875 @Override 4876 public List<ResolveInfo> queryIntentActivities(Intent intent, 4877 String resolvedType, int flags, int userId) { 4878 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4879 flags = updateFlagsForResolve(flags, userId, intent); 4880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4881 ComponentName comp = intent.getComponent(); 4882 if (comp == null) { 4883 if (intent.getSelector() != null) { 4884 intent = intent.getSelector(); 4885 comp = intent.getComponent(); 4886 } 4887 } 4888 4889 if (comp != null) { 4890 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4891 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4892 if (ai != null) { 4893 final ResolveInfo ri = new ResolveInfo(); 4894 ri.activityInfo = ai; 4895 list.add(ri); 4896 } 4897 return list; 4898 } 4899 4900 // reader 4901 synchronized (mPackages) { 4902 final String pkgName = intent.getPackage(); 4903 if (pkgName == null) { 4904 List<CrossProfileIntentFilter> matchingFilters = 4905 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4906 // Check for results that need to skip the current profile. 4907 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4908 resolvedType, flags, userId); 4909 if (xpResolveInfo != null) { 4910 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4911 result.add(xpResolveInfo); 4912 return filterIfNotSystemUser(result, userId); 4913 } 4914 4915 // Check for results in the current profile. 4916 List<ResolveInfo> result = mActivities.queryIntent( 4917 intent, resolvedType, flags, userId); 4918 result = filterIfNotSystemUser(result, userId); 4919 4920 // Check for cross profile results. 4921 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4922 xpResolveInfo = queryCrossProfileIntents( 4923 matchingFilters, intent, resolvedType, flags, userId, 4924 hasNonNegativePriorityResult); 4925 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4926 boolean isVisibleToUser = filterIfNotSystemUser( 4927 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4928 if (isVisibleToUser) { 4929 result.add(xpResolveInfo); 4930 Collections.sort(result, mResolvePrioritySorter); 4931 } 4932 } 4933 if (hasWebURI(intent)) { 4934 CrossProfileDomainInfo xpDomainInfo = null; 4935 final UserInfo parent = getProfileParent(userId); 4936 if (parent != null) { 4937 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4938 flags, userId, parent.id); 4939 } 4940 if (xpDomainInfo != null) { 4941 if (xpResolveInfo != null) { 4942 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4943 // in the result. 4944 result.remove(xpResolveInfo); 4945 } 4946 if (result.size() == 0) { 4947 result.add(xpDomainInfo.resolveInfo); 4948 return result; 4949 } 4950 } else if (result.size() <= 1) { 4951 return result; 4952 } 4953 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 4954 xpDomainInfo, userId); 4955 Collections.sort(result, mResolvePrioritySorter); 4956 } 4957 return result; 4958 } 4959 final PackageParser.Package pkg = mPackages.get(pkgName); 4960 if (pkg != null) { 4961 return filterIfNotSystemUser( 4962 mActivities.queryIntentForPackage( 4963 intent, resolvedType, flags, pkg.activities, userId), 4964 userId); 4965 } 4966 return new ArrayList<ResolveInfo>(); 4967 } 4968 } 4969 4970 private static class CrossProfileDomainInfo { 4971 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4972 ResolveInfo resolveInfo; 4973 /* Best domain verification status of the activities found in the other profile */ 4974 int bestDomainVerificationStatus; 4975 } 4976 4977 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4978 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4979 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 4980 sourceUserId)) { 4981 return null; 4982 } 4983 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4984 resolvedType, flags, parentUserId); 4985 4986 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4987 return null; 4988 } 4989 CrossProfileDomainInfo result = null; 4990 int size = resultTargetUser.size(); 4991 for (int i = 0; i < size; i++) { 4992 ResolveInfo riTargetUser = resultTargetUser.get(i); 4993 // Intent filter verification is only for filters that specify a host. So don't return 4994 // those that handle all web uris. 4995 if (riTargetUser.handleAllWebDataURI) { 4996 continue; 4997 } 4998 String packageName = riTargetUser.activityInfo.packageName; 4999 PackageSetting ps = mSettings.mPackages.get(packageName); 5000 if (ps == null) { 5001 continue; 5002 } 5003 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5004 int status = (int)(verificationState >> 32); 5005 if (result == null) { 5006 result = new CrossProfileDomainInfo(); 5007 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5008 sourceUserId, parentUserId); 5009 result.bestDomainVerificationStatus = status; 5010 } else { 5011 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5012 result.bestDomainVerificationStatus); 5013 } 5014 } 5015 // Don't consider matches with status NEVER across profiles. 5016 if (result != null && result.bestDomainVerificationStatus 5017 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5018 return null; 5019 } 5020 return result; 5021 } 5022 5023 /** 5024 * Verification statuses are ordered from the worse to the best, except for 5025 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5026 */ 5027 private int bestDomainVerificationStatus(int status1, int status2) { 5028 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5029 return status2; 5030 } 5031 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5032 return status1; 5033 } 5034 return (int) MathUtils.max(status1, status2); 5035 } 5036 5037 private boolean isUserEnabled(int userId) { 5038 long callingId = Binder.clearCallingIdentity(); 5039 try { 5040 UserInfo userInfo = sUserManager.getUserInfo(userId); 5041 return userInfo != null && userInfo.isEnabled(); 5042 } finally { 5043 Binder.restoreCallingIdentity(callingId); 5044 } 5045 } 5046 5047 /** 5048 * Filter out activities with systemUserOnly flag set, when current user is not System. 5049 * 5050 * @return filtered list 5051 */ 5052 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5053 if (userId == UserHandle.USER_SYSTEM) { 5054 return resolveInfos; 5055 } 5056 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5057 ResolveInfo info = resolveInfos.get(i); 5058 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5059 resolveInfos.remove(i); 5060 } 5061 } 5062 return resolveInfos; 5063 } 5064 5065 /** 5066 * @param resolveInfos list of resolve infos in descending priority order 5067 * @return if the list contains a resolve info with non-negative priority 5068 */ 5069 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5070 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5071 } 5072 5073 private static boolean hasWebURI(Intent intent) { 5074 if (intent.getData() == null) { 5075 return false; 5076 } 5077 final String scheme = intent.getScheme(); 5078 if (TextUtils.isEmpty(scheme)) { 5079 return false; 5080 } 5081 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5082 } 5083 5084 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5085 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5086 int userId) { 5087 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5088 5089 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5090 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5091 candidates.size()); 5092 } 5093 5094 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5095 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5096 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5097 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5098 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5099 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5100 5101 synchronized (mPackages) { 5102 final int count = candidates.size(); 5103 // First, try to use linked apps. Partition the candidates into four lists: 5104 // one for the final results, one for the "do not use ever", one for "undefined status" 5105 // and finally one for "browser app type". 5106 for (int n=0; n<count; n++) { 5107 ResolveInfo info = candidates.get(n); 5108 String packageName = info.activityInfo.packageName; 5109 PackageSetting ps = mSettings.mPackages.get(packageName); 5110 if (ps != null) { 5111 // Add to the special match all list (Browser use case) 5112 if (info.handleAllWebDataURI) { 5113 matchAllList.add(info); 5114 continue; 5115 } 5116 // Try to get the status from User settings first 5117 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5118 int status = (int)(packedStatus >> 32); 5119 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5120 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5121 if (DEBUG_DOMAIN_VERIFICATION) { 5122 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5123 + " : linkgen=" + linkGeneration); 5124 } 5125 // Use link-enabled generation as preferredOrder, i.e. 5126 // prefer newly-enabled over earlier-enabled. 5127 info.preferredOrder = linkGeneration; 5128 alwaysList.add(info); 5129 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5130 if (DEBUG_DOMAIN_VERIFICATION) { 5131 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5132 } 5133 neverList.add(info); 5134 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5135 if (DEBUG_DOMAIN_VERIFICATION) { 5136 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5137 } 5138 alwaysAskList.add(info); 5139 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5140 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5141 if (DEBUG_DOMAIN_VERIFICATION) { 5142 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5143 } 5144 undefinedList.add(info); 5145 } 5146 } 5147 } 5148 5149 // We'll want to include browser possibilities in a few cases 5150 boolean includeBrowser = false; 5151 5152 // First try to add the "always" resolution(s) for the current user, if any 5153 if (alwaysList.size() > 0) { 5154 result.addAll(alwaysList); 5155 } else { 5156 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5157 result.addAll(undefinedList); 5158 // Maybe add one for the other profile. 5159 if (xpDomainInfo != null && ( 5160 xpDomainInfo.bestDomainVerificationStatus 5161 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5162 result.add(xpDomainInfo.resolveInfo); 5163 } 5164 includeBrowser = true; 5165 } 5166 5167 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5168 // If there were 'always' entries their preferred order has been set, so we also 5169 // back that off to make the alternatives equivalent 5170 if (alwaysAskList.size() > 0) { 5171 for (ResolveInfo i : result) { 5172 i.preferredOrder = 0; 5173 } 5174 result.addAll(alwaysAskList); 5175 includeBrowser = true; 5176 } 5177 5178 if (includeBrowser) { 5179 // Also add browsers (all of them or only the default one) 5180 if (DEBUG_DOMAIN_VERIFICATION) { 5181 Slog.v(TAG, " ...including browsers in candidate set"); 5182 } 5183 if ((matchFlags & MATCH_ALL) != 0) { 5184 result.addAll(matchAllList); 5185 } else { 5186 // Browser/generic handling case. If there's a default browser, go straight 5187 // to that (but only if there is no other higher-priority match). 5188 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5189 int maxMatchPrio = 0; 5190 ResolveInfo defaultBrowserMatch = null; 5191 final int numCandidates = matchAllList.size(); 5192 for (int n = 0; n < numCandidates; n++) { 5193 ResolveInfo info = matchAllList.get(n); 5194 // track the highest overall match priority... 5195 if (info.priority > maxMatchPrio) { 5196 maxMatchPrio = info.priority; 5197 } 5198 // ...and the highest-priority default browser match 5199 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5200 if (defaultBrowserMatch == null 5201 || (defaultBrowserMatch.priority < info.priority)) { 5202 if (debug) { 5203 Slog.v(TAG, "Considering default browser match " + info); 5204 } 5205 defaultBrowserMatch = info; 5206 } 5207 } 5208 } 5209 if (defaultBrowserMatch != null 5210 && defaultBrowserMatch.priority >= maxMatchPrio 5211 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5212 { 5213 if (debug) { 5214 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5215 } 5216 result.add(defaultBrowserMatch); 5217 } else { 5218 result.addAll(matchAllList); 5219 } 5220 } 5221 5222 // If there is nothing selected, add all candidates and remove the ones that the user 5223 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5224 if (result.size() == 0) { 5225 result.addAll(candidates); 5226 result.removeAll(neverList); 5227 } 5228 } 5229 } 5230 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5231 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5232 result.size()); 5233 for (ResolveInfo info : result) { 5234 Slog.v(TAG, " + " + info.activityInfo); 5235 } 5236 } 5237 return result; 5238 } 5239 5240 // Returns a packed value as a long: 5241 // 5242 // high 'int'-sized word: link status: undefined/ask/never/always. 5243 // low 'int'-sized word: relative priority among 'always' results. 5244 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5245 long result = ps.getDomainVerificationStatusForUser(userId); 5246 // if none available, get the master status 5247 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5248 if (ps.getIntentFilterVerificationInfo() != null) { 5249 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5250 } 5251 } 5252 return result; 5253 } 5254 5255 private ResolveInfo querySkipCurrentProfileIntents( 5256 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5257 int flags, int sourceUserId) { 5258 if (matchingFilters != null) { 5259 int size = matchingFilters.size(); 5260 for (int i = 0; i < size; i ++) { 5261 CrossProfileIntentFilter filter = matchingFilters.get(i); 5262 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5263 // Checking if there are activities in the target user that can handle the 5264 // intent. 5265 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5266 resolvedType, flags, sourceUserId); 5267 if (resolveInfo != null) { 5268 return resolveInfo; 5269 } 5270 } 5271 } 5272 } 5273 return null; 5274 } 5275 5276 // Return matching ResolveInfo in target user if any. 5277 private ResolveInfo queryCrossProfileIntents( 5278 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5279 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5280 if (matchingFilters != null) { 5281 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5282 // match the same intent. For performance reasons, it is better not to 5283 // run queryIntent twice for the same userId 5284 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5285 int size = matchingFilters.size(); 5286 for (int i = 0; i < size; i++) { 5287 CrossProfileIntentFilter filter = matchingFilters.get(i); 5288 int targetUserId = filter.getTargetUserId(); 5289 boolean skipCurrentProfile = 5290 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5291 boolean skipCurrentProfileIfNoMatchFound = 5292 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5293 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5294 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5295 // Checking if there are activities in the target user that can handle the 5296 // intent. 5297 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5298 resolvedType, flags, sourceUserId); 5299 if (resolveInfo != null) return resolveInfo; 5300 alreadyTriedUserIds.put(targetUserId, true); 5301 } 5302 } 5303 } 5304 return null; 5305 } 5306 5307 /** 5308 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5309 * will forward the intent to the filter's target user. 5310 * Otherwise, returns null. 5311 */ 5312 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5313 String resolvedType, int flags, int sourceUserId) { 5314 int targetUserId = filter.getTargetUserId(); 5315 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5316 resolvedType, flags, targetUserId); 5317 if (resultTargetUser != null && !resultTargetUser.isEmpty() 5318 && isUserEnabled(targetUserId)) { 5319 return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId); 5320 } 5321 return null; 5322 } 5323 5324 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5325 int sourceUserId, int targetUserId) { 5326 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5327 long ident = Binder.clearCallingIdentity(); 5328 boolean targetIsProfile; 5329 try { 5330 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5331 } finally { 5332 Binder.restoreCallingIdentity(ident); 5333 } 5334 String className; 5335 if (targetIsProfile) { 5336 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5337 } else { 5338 className = FORWARD_INTENT_TO_PARENT; 5339 } 5340 ComponentName forwardingActivityComponentName = new ComponentName( 5341 mAndroidApplication.packageName, className); 5342 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5343 sourceUserId); 5344 if (!targetIsProfile) { 5345 forwardingActivityInfo.showUserIcon = targetUserId; 5346 forwardingResolveInfo.noResourceId = true; 5347 } 5348 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5349 forwardingResolveInfo.priority = 0; 5350 forwardingResolveInfo.preferredOrder = 0; 5351 forwardingResolveInfo.match = 0; 5352 forwardingResolveInfo.isDefault = true; 5353 forwardingResolveInfo.filter = filter; 5354 forwardingResolveInfo.targetUserId = targetUserId; 5355 return forwardingResolveInfo; 5356 } 5357 5358 @Override 5359 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5360 Intent[] specifics, String[] specificTypes, Intent intent, 5361 String resolvedType, int flags, int userId) { 5362 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5363 flags = updateFlagsForResolve(flags, userId, intent); 5364 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5365 false, "query intent activity options"); 5366 final String resultsAction = intent.getAction(); 5367 5368 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5369 | PackageManager.GET_RESOLVED_FILTER, userId); 5370 5371 if (DEBUG_INTENT_MATCHING) { 5372 Log.v(TAG, "Query " + intent + ": " + results); 5373 } 5374 5375 int specificsPos = 0; 5376 int N; 5377 5378 // todo: note that the algorithm used here is O(N^2). This 5379 // isn't a problem in our current environment, but if we start running 5380 // into situations where we have more than 5 or 10 matches then this 5381 // should probably be changed to something smarter... 5382 5383 // First we go through and resolve each of the specific items 5384 // that were supplied, taking care of removing any corresponding 5385 // duplicate items in the generic resolve list. 5386 if (specifics != null) { 5387 for (int i=0; i<specifics.length; i++) { 5388 final Intent sintent = specifics[i]; 5389 if (sintent == null) { 5390 continue; 5391 } 5392 5393 if (DEBUG_INTENT_MATCHING) { 5394 Log.v(TAG, "Specific #" + i + ": " + sintent); 5395 } 5396 5397 String action = sintent.getAction(); 5398 if (resultsAction != null && resultsAction.equals(action)) { 5399 // If this action was explicitly requested, then don't 5400 // remove things that have it. 5401 action = null; 5402 } 5403 5404 ResolveInfo ri = null; 5405 ActivityInfo ai = null; 5406 5407 ComponentName comp = sintent.getComponent(); 5408 if (comp == null) { 5409 ri = resolveIntent( 5410 sintent, 5411 specificTypes != null ? specificTypes[i] : null, 5412 flags, userId); 5413 if (ri == null) { 5414 continue; 5415 } 5416 if (ri == mResolveInfo) { 5417 // ACK! Must do something better with this. 5418 } 5419 ai = ri.activityInfo; 5420 comp = new ComponentName(ai.applicationInfo.packageName, 5421 ai.name); 5422 } else { 5423 ai = getActivityInfo(comp, flags, userId); 5424 if (ai == null) { 5425 continue; 5426 } 5427 } 5428 5429 // Look for any generic query activities that are duplicates 5430 // of this specific one, and remove them from the results. 5431 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5432 N = results.size(); 5433 int j; 5434 for (j=specificsPos; j<N; j++) { 5435 ResolveInfo sri = results.get(j); 5436 if ((sri.activityInfo.name.equals(comp.getClassName()) 5437 && sri.activityInfo.applicationInfo.packageName.equals( 5438 comp.getPackageName())) 5439 || (action != null && sri.filter.matchAction(action))) { 5440 results.remove(j); 5441 if (DEBUG_INTENT_MATCHING) Log.v( 5442 TAG, "Removing duplicate item from " + j 5443 + " due to specific " + specificsPos); 5444 if (ri == null) { 5445 ri = sri; 5446 } 5447 j--; 5448 N--; 5449 } 5450 } 5451 5452 // Add this specific item to its proper place. 5453 if (ri == null) { 5454 ri = new ResolveInfo(); 5455 ri.activityInfo = ai; 5456 } 5457 results.add(specificsPos, ri); 5458 ri.specificIndex = i; 5459 specificsPos++; 5460 } 5461 } 5462 5463 // Now we go through the remaining generic results and remove any 5464 // duplicate actions that are found here. 5465 N = results.size(); 5466 for (int i=specificsPos; i<N-1; i++) { 5467 final ResolveInfo rii = results.get(i); 5468 if (rii.filter == null) { 5469 continue; 5470 } 5471 5472 // Iterate over all of the actions of this result's intent 5473 // filter... typically this should be just one. 5474 final Iterator<String> it = rii.filter.actionsIterator(); 5475 if (it == null) { 5476 continue; 5477 } 5478 while (it.hasNext()) { 5479 final String action = it.next(); 5480 if (resultsAction != null && resultsAction.equals(action)) { 5481 // If this action was explicitly requested, then don't 5482 // remove things that have it. 5483 continue; 5484 } 5485 for (int j=i+1; j<N; j++) { 5486 final ResolveInfo rij = results.get(j); 5487 if (rij.filter != null && rij.filter.hasAction(action)) { 5488 results.remove(j); 5489 if (DEBUG_INTENT_MATCHING) Log.v( 5490 TAG, "Removing duplicate item from " + j 5491 + " due to action " + action + " at " + i); 5492 j--; 5493 N--; 5494 } 5495 } 5496 } 5497 5498 // If the caller didn't request filter information, drop it now 5499 // so we don't have to marshall/unmarshall it. 5500 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5501 rii.filter = null; 5502 } 5503 } 5504 5505 // Filter out the caller activity if so requested. 5506 if (caller != null) { 5507 N = results.size(); 5508 for (int i=0; i<N; i++) { 5509 ActivityInfo ainfo = results.get(i).activityInfo; 5510 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5511 && caller.getClassName().equals(ainfo.name)) { 5512 results.remove(i); 5513 break; 5514 } 5515 } 5516 } 5517 5518 // If the caller didn't request filter information, 5519 // drop them now so we don't have to 5520 // marshall/unmarshall it. 5521 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5522 N = results.size(); 5523 for (int i=0; i<N; i++) { 5524 results.get(i).filter = null; 5525 } 5526 } 5527 5528 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5529 return results; 5530 } 5531 5532 @Override 5533 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5534 int userId) { 5535 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5536 flags = updateFlagsForResolve(flags, userId, intent); 5537 ComponentName comp = intent.getComponent(); 5538 if (comp == null) { 5539 if (intent.getSelector() != null) { 5540 intent = intent.getSelector(); 5541 comp = intent.getComponent(); 5542 } 5543 } 5544 if (comp != null) { 5545 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5546 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5547 if (ai != null) { 5548 ResolveInfo ri = new ResolveInfo(); 5549 ri.activityInfo = ai; 5550 list.add(ri); 5551 } 5552 return list; 5553 } 5554 5555 // reader 5556 synchronized (mPackages) { 5557 String pkgName = intent.getPackage(); 5558 if (pkgName == null) { 5559 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5560 } 5561 final PackageParser.Package pkg = mPackages.get(pkgName); 5562 if (pkg != null) { 5563 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5564 userId); 5565 } 5566 return null; 5567 } 5568 } 5569 5570 @Override 5571 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5572 if (!sUserManager.exists(userId)) return null; 5573 flags = updateFlagsForResolve(flags, userId, intent); 5574 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5575 if (query != null) { 5576 if (query.size() >= 1) { 5577 // If there is more than one service with the same priority, 5578 // just arbitrarily pick the first one. 5579 return query.get(0); 5580 } 5581 } 5582 return null; 5583 } 5584 5585 @Override 5586 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5587 int userId) { 5588 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5589 flags = updateFlagsForResolve(flags, userId, intent); 5590 ComponentName comp = intent.getComponent(); 5591 if (comp == null) { 5592 if (intent.getSelector() != null) { 5593 intent = intent.getSelector(); 5594 comp = intent.getComponent(); 5595 } 5596 } 5597 if (comp != null) { 5598 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5599 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5600 if (si != null) { 5601 final ResolveInfo ri = new ResolveInfo(); 5602 ri.serviceInfo = si; 5603 list.add(ri); 5604 } 5605 return list; 5606 } 5607 5608 // reader 5609 synchronized (mPackages) { 5610 String pkgName = intent.getPackage(); 5611 if (pkgName == null) { 5612 return mServices.queryIntent(intent, resolvedType, flags, userId); 5613 } 5614 final PackageParser.Package pkg = mPackages.get(pkgName); 5615 if (pkg != null) { 5616 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5617 userId); 5618 } 5619 return null; 5620 } 5621 } 5622 5623 @Override 5624 public List<ResolveInfo> queryIntentContentProviders( 5625 Intent intent, String resolvedType, int flags, int userId) { 5626 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5627 flags = updateFlagsForResolve(flags, userId, intent); 5628 ComponentName comp = intent.getComponent(); 5629 if (comp == null) { 5630 if (intent.getSelector() != null) { 5631 intent = intent.getSelector(); 5632 comp = intent.getComponent(); 5633 } 5634 } 5635 if (comp != null) { 5636 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5637 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5638 if (pi != null) { 5639 final ResolveInfo ri = new ResolveInfo(); 5640 ri.providerInfo = pi; 5641 list.add(ri); 5642 } 5643 return list; 5644 } 5645 5646 // reader 5647 synchronized (mPackages) { 5648 String pkgName = intent.getPackage(); 5649 if (pkgName == null) { 5650 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5651 } 5652 final PackageParser.Package pkg = mPackages.get(pkgName); 5653 if (pkg != null) { 5654 return mProviders.queryIntentForPackage( 5655 intent, resolvedType, flags, pkg.providers, userId); 5656 } 5657 return null; 5658 } 5659 } 5660 5661 @Override 5662 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5663 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5664 flags = updateFlagsForPackage(flags, userId, null); 5665 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5666 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5667 5668 // writer 5669 synchronized (mPackages) { 5670 ArrayList<PackageInfo> list; 5671 if (listUninstalled) { 5672 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5673 for (PackageSetting ps : mSettings.mPackages.values()) { 5674 PackageInfo pi; 5675 if (ps.pkg != null) { 5676 pi = generatePackageInfo(ps.pkg, flags, userId); 5677 } else { 5678 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5679 } 5680 if (pi != null) { 5681 list.add(pi); 5682 } 5683 } 5684 } else { 5685 list = new ArrayList<PackageInfo>(mPackages.size()); 5686 for (PackageParser.Package p : mPackages.values()) { 5687 PackageInfo pi = generatePackageInfo(p, flags, userId); 5688 if (pi != null) { 5689 list.add(pi); 5690 } 5691 } 5692 } 5693 5694 return new ParceledListSlice<PackageInfo>(list); 5695 } 5696 } 5697 5698 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5699 String[] permissions, boolean[] tmp, int flags, int userId) { 5700 int numMatch = 0; 5701 final PermissionsState permissionsState = ps.getPermissionsState(); 5702 for (int i=0; i<permissions.length; i++) { 5703 final String permission = permissions[i]; 5704 if (permissionsState.hasPermission(permission, userId)) { 5705 tmp[i] = true; 5706 numMatch++; 5707 } else { 5708 tmp[i] = false; 5709 } 5710 } 5711 if (numMatch == 0) { 5712 return; 5713 } 5714 PackageInfo pi; 5715 if (ps.pkg != null) { 5716 pi = generatePackageInfo(ps.pkg, flags, userId); 5717 } else { 5718 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5719 } 5720 // The above might return null in cases of uninstalled apps or install-state 5721 // skew across users/profiles. 5722 if (pi != null) { 5723 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5724 if (numMatch == permissions.length) { 5725 pi.requestedPermissions = permissions; 5726 } else { 5727 pi.requestedPermissions = new String[numMatch]; 5728 numMatch = 0; 5729 for (int i=0; i<permissions.length; i++) { 5730 if (tmp[i]) { 5731 pi.requestedPermissions[numMatch] = permissions[i]; 5732 numMatch++; 5733 } 5734 } 5735 } 5736 } 5737 list.add(pi); 5738 } 5739 } 5740 5741 @Override 5742 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5743 String[] permissions, int flags, int userId) { 5744 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5745 flags = updateFlagsForPackage(flags, userId, permissions); 5746 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5747 5748 // writer 5749 synchronized (mPackages) { 5750 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5751 boolean[] tmpBools = new boolean[permissions.length]; 5752 if (listUninstalled) { 5753 for (PackageSetting ps : mSettings.mPackages.values()) { 5754 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5755 } 5756 } else { 5757 for (PackageParser.Package pkg : mPackages.values()) { 5758 PackageSetting ps = (PackageSetting)pkg.mExtras; 5759 if (ps != null) { 5760 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5761 userId); 5762 } 5763 } 5764 } 5765 5766 return new ParceledListSlice<PackageInfo>(list); 5767 } 5768 } 5769 5770 @Override 5771 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5772 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5773 flags = updateFlagsForApplication(flags, userId, null); 5774 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5775 5776 // writer 5777 synchronized (mPackages) { 5778 ArrayList<ApplicationInfo> list; 5779 if (listUninstalled) { 5780 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5781 for (PackageSetting ps : mSettings.mPackages.values()) { 5782 ApplicationInfo ai; 5783 if (ps.pkg != null) { 5784 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5785 ps.readUserState(userId), userId); 5786 } else { 5787 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5788 } 5789 if (ai != null) { 5790 list.add(ai); 5791 } 5792 } 5793 } else { 5794 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5795 for (PackageParser.Package p : mPackages.values()) { 5796 if (p.mExtras != null) { 5797 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5798 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5799 if (ai != null) { 5800 list.add(ai); 5801 } 5802 } 5803 } 5804 } 5805 5806 return new ParceledListSlice<ApplicationInfo>(list); 5807 } 5808 } 5809 5810 @Override 5811 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5812 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5813 "getEphemeralApplications"); 5814 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5815 "getEphemeralApplications"); 5816 synchronized (mPackages) { 5817 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5818 .getEphemeralApplicationsLPw(userId); 5819 if (ephemeralApps != null) { 5820 return new ParceledListSlice<>(ephemeralApps); 5821 } 5822 } 5823 return null; 5824 } 5825 5826 @Override 5827 public boolean isEphemeralApplication(String packageName, int userId) { 5828 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5829 "isEphemeral"); 5830 if (!isCallerSameApp(packageName)) { 5831 return false; 5832 } 5833 synchronized (mPackages) { 5834 PackageParser.Package pkg = mPackages.get(packageName); 5835 if (pkg != null) { 5836 return pkg.applicationInfo.isEphemeralApp(); 5837 } 5838 } 5839 return false; 5840 } 5841 5842 @Override 5843 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5844 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5845 "getCookie"); 5846 if (!isCallerSameApp(packageName)) { 5847 return null; 5848 } 5849 synchronized (mPackages) { 5850 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5851 packageName, userId); 5852 } 5853 } 5854 5855 @Override 5856 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5857 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5858 "setCookie"); 5859 if (!isCallerSameApp(packageName)) { 5860 return false; 5861 } 5862 synchronized (mPackages) { 5863 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5864 packageName, cookie, userId); 5865 } 5866 } 5867 5868 @Override 5869 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5870 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5871 "getEphemeralApplicationIcon"); 5872 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5873 "getEphemeralApplicationIcon"); 5874 synchronized (mPackages) { 5875 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5876 packageName, userId); 5877 } 5878 } 5879 5880 private boolean isCallerSameApp(String packageName) { 5881 PackageParser.Package pkg = mPackages.get(packageName); 5882 return pkg != null 5883 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5884 } 5885 5886 public List<ApplicationInfo> getPersistentApplications(int flags) { 5887 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5888 5889 // reader 5890 synchronized (mPackages) { 5891 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5892 final int userId = UserHandle.getCallingUserId(); 5893 while (i.hasNext()) { 5894 final PackageParser.Package p = i.next(); 5895 if (p.applicationInfo != null 5896 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5897 && (!mSafeMode || isSystemApp(p))) { 5898 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5899 if (ps != null) { 5900 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5901 ps.readUserState(userId), userId); 5902 if (ai != null) { 5903 finalList.add(ai); 5904 } 5905 } 5906 } 5907 } 5908 } 5909 5910 return finalList; 5911 } 5912 5913 @Override 5914 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5915 if (!sUserManager.exists(userId)) return null; 5916 flags = updateFlagsForComponent(flags, userId, name); 5917 // reader 5918 synchronized (mPackages) { 5919 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5920 PackageSetting ps = provider != null 5921 ? mSettings.mPackages.get(provider.owner.packageName) 5922 : null; 5923 return ps != null 5924 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 5925 ? PackageParser.generateProviderInfo(provider, flags, 5926 ps.readUserState(userId), userId) 5927 : null; 5928 } 5929 } 5930 5931 /** 5932 * @deprecated 5933 */ 5934 @Deprecated 5935 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5936 // reader 5937 synchronized (mPackages) { 5938 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5939 .entrySet().iterator(); 5940 final int userId = UserHandle.getCallingUserId(); 5941 while (i.hasNext()) { 5942 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5943 PackageParser.Provider p = entry.getValue(); 5944 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5945 5946 if (ps != null && p.syncable 5947 && (!mSafeMode || (p.info.applicationInfo.flags 5948 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5949 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5950 ps.readUserState(userId), userId); 5951 if (info != null) { 5952 outNames.add(entry.getKey()); 5953 outInfo.add(info); 5954 } 5955 } 5956 } 5957 } 5958 } 5959 5960 @Override 5961 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 5962 int uid, int flags) { 5963 final int userId = processName != null ? UserHandle.getUserId(uid) 5964 : UserHandle.getCallingUserId(); 5965 if (!sUserManager.exists(userId)) return null; 5966 flags = updateFlagsForComponent(flags, userId, processName); 5967 5968 ArrayList<ProviderInfo> finalList = null; 5969 // reader 5970 synchronized (mPackages) { 5971 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5972 while (i.hasNext()) { 5973 final PackageParser.Provider p = i.next(); 5974 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5975 if (ps != null && p.info.authority != null 5976 && (processName == null 5977 || (p.info.processName.equals(processName) 5978 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5979 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5980 if (finalList == null) { 5981 finalList = new ArrayList<ProviderInfo>(3); 5982 } 5983 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5984 ps.readUserState(userId), userId); 5985 if (info != null) { 5986 finalList.add(info); 5987 } 5988 } 5989 } 5990 } 5991 5992 if (finalList != null) { 5993 Collections.sort(finalList, mProviderInitOrderSorter); 5994 return new ParceledListSlice<ProviderInfo>(finalList); 5995 } 5996 5997 return null; 5998 } 5999 6000 @Override 6001 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6002 // reader 6003 synchronized (mPackages) { 6004 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6005 return PackageParser.generateInstrumentationInfo(i, flags); 6006 } 6007 } 6008 6009 @Override 6010 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6011 int flags) { 6012 ArrayList<InstrumentationInfo> finalList = 6013 new ArrayList<InstrumentationInfo>(); 6014 6015 // reader 6016 synchronized (mPackages) { 6017 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6018 while (i.hasNext()) { 6019 final PackageParser.Instrumentation p = i.next(); 6020 if (targetPackage == null 6021 || targetPackage.equals(p.info.targetPackage)) { 6022 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6023 flags); 6024 if (ii != null) { 6025 finalList.add(ii); 6026 } 6027 } 6028 } 6029 } 6030 6031 return finalList; 6032 } 6033 6034 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6035 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6036 if (overlays == null) { 6037 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6038 return; 6039 } 6040 for (PackageParser.Package opkg : overlays.values()) { 6041 // Not much to do if idmap fails: we already logged the error 6042 // and we certainly don't want to abort installation of pkg simply 6043 // because an overlay didn't fit properly. For these reasons, 6044 // ignore the return value of createIdmapForPackagePairLI. 6045 createIdmapForPackagePairLI(pkg, opkg); 6046 } 6047 } 6048 6049 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6050 PackageParser.Package opkg) { 6051 if (!opkg.mTrustedOverlay) { 6052 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6053 opkg.baseCodePath + ": overlay not trusted"); 6054 return false; 6055 } 6056 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6057 if (overlaySet == null) { 6058 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6059 opkg.baseCodePath + " but target package has no known overlays"); 6060 return false; 6061 } 6062 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6063 // TODO: generate idmap for split APKs 6064 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 6065 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6066 + opkg.baseCodePath); 6067 return false; 6068 } 6069 PackageParser.Package[] overlayArray = 6070 overlaySet.values().toArray(new PackageParser.Package[0]); 6071 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6072 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6073 return p1.mOverlayPriority - p2.mOverlayPriority; 6074 } 6075 }; 6076 Arrays.sort(overlayArray, cmp); 6077 6078 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6079 int i = 0; 6080 for (PackageParser.Package p : overlayArray) { 6081 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6082 } 6083 return true; 6084 } 6085 6086 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6088 try { 6089 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6090 } finally { 6091 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6092 } 6093 } 6094 6095 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6096 final File[] files = dir.listFiles(); 6097 if (ArrayUtils.isEmpty(files)) { 6098 Log.d(TAG, "No files in app dir " + dir); 6099 return; 6100 } 6101 6102 if (DEBUG_PACKAGE_SCANNING) { 6103 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6104 + " flags=0x" + Integer.toHexString(parseFlags)); 6105 } 6106 6107 for (File file : files) { 6108 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6109 && !PackageInstallerService.isStageName(file.getName()); 6110 if (!isPackage) { 6111 // Ignore entries which are not packages 6112 continue; 6113 } 6114 try { 6115 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6116 scanFlags, currentTime, null); 6117 } catch (PackageManagerException e) { 6118 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6119 6120 // Delete invalid userdata apps 6121 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6122 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6123 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6124 if (file.isDirectory()) { 6125 mInstaller.rmPackageDir(file.getAbsolutePath()); 6126 } else { 6127 file.delete(); 6128 } 6129 } 6130 } 6131 } 6132 } 6133 6134 private static File getSettingsProblemFile() { 6135 File dataDir = Environment.getDataDirectory(); 6136 File systemDir = new File(dataDir, "system"); 6137 File fname = new File(systemDir, "uiderrors.txt"); 6138 return fname; 6139 } 6140 6141 static void reportSettingsProblem(int priority, String msg) { 6142 logCriticalInfo(priority, msg); 6143 } 6144 6145 static void logCriticalInfo(int priority, String msg) { 6146 Slog.println(priority, TAG, msg); 6147 EventLogTags.writePmCriticalInfo(msg); 6148 try { 6149 File fname = getSettingsProblemFile(); 6150 FileOutputStream out = new FileOutputStream(fname, true); 6151 PrintWriter pw = new FastPrintWriter(out); 6152 SimpleDateFormat formatter = new SimpleDateFormat(); 6153 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6154 pw.println(dateString + ": " + msg); 6155 pw.close(); 6156 FileUtils.setPermissions( 6157 fname.toString(), 6158 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6159 -1, -1); 6160 } catch (java.io.IOException e) { 6161 } 6162 } 6163 6164 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6165 PackageParser.Package pkg, File srcFile, int parseFlags) 6166 throws PackageManagerException { 6167 if (ps != null 6168 && ps.codePath.equals(srcFile) 6169 && ps.timeStamp == srcFile.lastModified() 6170 && !isCompatSignatureUpdateNeeded(pkg) 6171 && !isRecoverSignatureUpdateNeeded(pkg)) { 6172 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6174 ArraySet<PublicKey> signingKs; 6175 synchronized (mPackages) { 6176 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6177 } 6178 if (ps.signatures.mSignatures != null 6179 && ps.signatures.mSignatures.length != 0 6180 && signingKs != null) { 6181 // Optimization: reuse the existing cached certificates 6182 // if the package appears to be unchanged. 6183 pkg.mSignatures = ps.signatures.mSignatures; 6184 pkg.mSigningKeys = signingKs; 6185 return; 6186 } 6187 6188 Slog.w(TAG, "PackageSetting for " + ps.name 6189 + " is missing signatures. Collecting certs again to recover them."); 6190 } else { 6191 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6192 } 6193 6194 try { 6195 pp.collectCertificates(pkg, parseFlags); 6196 } catch (PackageParserException e) { 6197 throw PackageManagerException.from(e); 6198 } 6199 } 6200 6201 /** 6202 * Traces a package scan. 6203 * @see #scanPackageLI(File, int, int, long, UserHandle) 6204 */ 6205 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6206 long currentTime, UserHandle user) throws PackageManagerException { 6207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6208 try { 6209 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6210 } finally { 6211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6212 } 6213 } 6214 6215 /** 6216 * Scans a package and returns the newly parsed package. 6217 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6218 */ 6219 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6220 long currentTime, UserHandle user) throws PackageManagerException { 6221 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6222 parseFlags |= mDefParseFlags; 6223 PackageParser pp = new PackageParser(); 6224 pp.setSeparateProcesses(mSeparateProcesses); 6225 pp.setOnlyCoreApps(mOnlyCore); 6226 pp.setDisplayMetrics(mMetrics); 6227 6228 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6229 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6230 } 6231 6232 final PackageParser.Package pkg; 6233 try { 6234 pkg = pp.parsePackage(scanFile, parseFlags); 6235 } catch (PackageParserException e) { 6236 throw PackageManagerException.from(e); 6237 } 6238 6239 PackageSetting ps = null; 6240 PackageSetting updatedPkg; 6241 // reader 6242 synchronized (mPackages) { 6243 // Look to see if we already know about this package. 6244 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6245 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6246 // This package has been renamed to its original name. Let's 6247 // use that. 6248 ps = mSettings.peekPackageLPr(oldName); 6249 } 6250 // If there was no original package, see one for the real package name. 6251 if (ps == null) { 6252 ps = mSettings.peekPackageLPr(pkg.packageName); 6253 } 6254 // Check to see if this package could be hiding/updating a system 6255 // package. Must look for it either under the original or real 6256 // package name depending on our state. 6257 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6258 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6259 } 6260 boolean updatedPkgBetter = false; 6261 // First check if this is a system package that may involve an update 6262 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6263 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6264 // it needs to drop FLAG_PRIVILEGED. 6265 if (locationIsPrivileged(scanFile)) { 6266 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6267 } else { 6268 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6269 } 6270 6271 if (ps != null && !ps.codePath.equals(scanFile)) { 6272 // The path has changed from what was last scanned... check the 6273 // version of the new path against what we have stored to determine 6274 // what to do. 6275 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6276 if (pkg.mVersionCode <= ps.versionCode) { 6277 // The system package has been updated and the code path does not match 6278 // Ignore entry. Skip it. 6279 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6280 + " ignored: updated version " + ps.versionCode 6281 + " better than this " + pkg.mVersionCode); 6282 if (!updatedPkg.codePath.equals(scanFile)) { 6283 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6284 + ps.name + " changing from " + updatedPkg.codePathString 6285 + " to " + scanFile); 6286 updatedPkg.codePath = scanFile; 6287 updatedPkg.codePathString = scanFile.toString(); 6288 updatedPkg.resourcePath = scanFile; 6289 updatedPkg.resourcePathString = scanFile.toString(); 6290 } 6291 updatedPkg.pkg = pkg; 6292 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6293 "Package " + ps.name + " at " + scanFile 6294 + " ignored: updated version " + ps.versionCode 6295 + " better than this " + pkg.mVersionCode); 6296 } else { 6297 // The current app on the system partition is better than 6298 // what we have updated to on the data partition; switch 6299 // back to the system partition version. 6300 // At this point, its safely assumed that package installation for 6301 // apps in system partition will go through. If not there won't be a working 6302 // version of the app 6303 // writer 6304 synchronized (mPackages) { 6305 // Just remove the loaded entries from package lists. 6306 mPackages.remove(ps.name); 6307 } 6308 6309 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6310 + " reverting from " + ps.codePathString 6311 + ": new version " + pkg.mVersionCode 6312 + " better than installed " + ps.versionCode); 6313 6314 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6315 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6316 synchronized (mInstallLock) { 6317 args.cleanUpResourcesLI(); 6318 } 6319 synchronized (mPackages) { 6320 mSettings.enableSystemPackageLPw(ps.name); 6321 } 6322 updatedPkgBetter = true; 6323 } 6324 } 6325 } 6326 6327 if (updatedPkg != null) { 6328 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6329 // initially 6330 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6331 6332 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6333 // flag set initially 6334 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6335 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6336 } 6337 } 6338 6339 // Verify certificates against what was last scanned 6340 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6341 6342 /* 6343 * A new system app appeared, but we already had a non-system one of the 6344 * same name installed earlier. 6345 */ 6346 boolean shouldHideSystemApp = false; 6347 if (updatedPkg == null && ps != null 6348 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6349 /* 6350 * Check to make sure the signatures match first. If they don't, 6351 * wipe the installed application and its data. 6352 */ 6353 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6354 != PackageManager.SIGNATURE_MATCH) { 6355 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6356 + " signatures don't match existing userdata copy; removing"); 6357 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6358 ps = null; 6359 } else { 6360 /* 6361 * If the newly-added system app is an older version than the 6362 * already installed version, hide it. It will be scanned later 6363 * and re-added like an update. 6364 */ 6365 if (pkg.mVersionCode <= ps.versionCode) { 6366 shouldHideSystemApp = true; 6367 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6368 + " but new version " + pkg.mVersionCode + " better than installed " 6369 + ps.versionCode + "; hiding system"); 6370 } else { 6371 /* 6372 * The newly found system app is a newer version that the 6373 * one previously installed. Simply remove the 6374 * already-installed application and replace it with our own 6375 * while keeping the application data. 6376 */ 6377 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6378 + " reverting from " + ps.codePathString + ": new version " 6379 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6380 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6381 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6382 synchronized (mInstallLock) { 6383 args.cleanUpResourcesLI(); 6384 } 6385 } 6386 } 6387 } 6388 6389 // The apk is forward locked (not public) if its code and resources 6390 // are kept in different files. (except for app in either system or 6391 // vendor path). 6392 // TODO grab this value from PackageSettings 6393 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6394 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6395 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6396 } 6397 } 6398 6399 // TODO: extend to support forward-locked splits 6400 String resourcePath = null; 6401 String baseResourcePath = null; 6402 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6403 if (ps != null && ps.resourcePathString != null) { 6404 resourcePath = ps.resourcePathString; 6405 baseResourcePath = ps.resourcePathString; 6406 } else { 6407 // Should not happen at all. Just log an error. 6408 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6409 } 6410 } else { 6411 resourcePath = pkg.codePath; 6412 baseResourcePath = pkg.baseCodePath; 6413 } 6414 6415 // Set application objects path explicitly. 6416 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6417 pkg.applicationInfo.setCodePath(pkg.codePath); 6418 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6419 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6420 pkg.applicationInfo.setResourcePath(resourcePath); 6421 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6422 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6423 6424 // Note that we invoke the following method only if we are about to unpack an application 6425 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6426 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6427 6428 /* 6429 * If the system app should be overridden by a previously installed 6430 * data, hide the system app now and let the /data/app scan pick it up 6431 * again. 6432 */ 6433 if (shouldHideSystemApp) { 6434 synchronized (mPackages) { 6435 mSettings.disableSystemPackageLPw(pkg.packageName); 6436 } 6437 } 6438 6439 return scannedPkg; 6440 } 6441 6442 private static String fixProcessName(String defProcessName, 6443 String processName, int uid) { 6444 if (processName == null) { 6445 return defProcessName; 6446 } 6447 return processName; 6448 } 6449 6450 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6451 throws PackageManagerException { 6452 if (pkgSetting.signatures.mSignatures != null) { 6453 // Already existing package. Make sure signatures match 6454 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6455 == PackageManager.SIGNATURE_MATCH; 6456 if (!match) { 6457 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6458 == PackageManager.SIGNATURE_MATCH; 6459 } 6460 if (!match) { 6461 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6462 == PackageManager.SIGNATURE_MATCH; 6463 } 6464 if (!match) { 6465 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6466 + pkg.packageName + " signatures do not match the " 6467 + "previously installed version; ignoring!"); 6468 } 6469 } 6470 6471 // Check for shared user signatures 6472 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6473 // Already existing package. Make sure signatures match 6474 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6475 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6476 if (!match) { 6477 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6478 == PackageManager.SIGNATURE_MATCH; 6479 } 6480 if (!match) { 6481 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6482 == PackageManager.SIGNATURE_MATCH; 6483 } 6484 if (!match) { 6485 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6486 "Package " + pkg.packageName 6487 + " has no signatures that match those in shared user " 6488 + pkgSetting.sharedUser.name + "; ignoring!"); 6489 } 6490 } 6491 } 6492 6493 /** 6494 * Enforces that only the system UID or root's UID can call a method exposed 6495 * via Binder. 6496 * 6497 * @param message used as message if SecurityException is thrown 6498 * @throws SecurityException if the caller is not system or root 6499 */ 6500 private static final void enforceSystemOrRoot(String message) { 6501 final int uid = Binder.getCallingUid(); 6502 if (uid != Process.SYSTEM_UID && uid != 0) { 6503 throw new SecurityException(message); 6504 } 6505 } 6506 6507 @Override 6508 public void performFstrimIfNeeded() { 6509 enforceSystemOrRoot("Only the system can request fstrim"); 6510 6511 // Before everything else, see whether we need to fstrim. 6512 try { 6513 IMountService ms = PackageHelper.getMountService(); 6514 if (ms != null) { 6515 final boolean isUpgrade = isUpgrade(); 6516 boolean doTrim = isUpgrade; 6517 if (doTrim) { 6518 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6519 } else { 6520 final long interval = android.provider.Settings.Global.getLong( 6521 mContext.getContentResolver(), 6522 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6523 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6524 if (interval > 0) { 6525 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6526 if (timeSinceLast > interval) { 6527 doTrim = true; 6528 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6529 + "; running immediately"); 6530 } 6531 } 6532 } 6533 if (doTrim) { 6534 if (!isFirstBoot()) { 6535 try { 6536 ActivityManagerNative.getDefault().showBootMessage( 6537 mContext.getResources().getString( 6538 R.string.android_upgrading_fstrim), true); 6539 } catch (RemoteException e) { 6540 } 6541 } 6542 ms.runMaintenance(); 6543 } 6544 } else { 6545 Slog.e(TAG, "Mount service unavailable!"); 6546 } 6547 } catch (RemoteException e) { 6548 // Can't happen; MountService is local 6549 } 6550 } 6551 6552 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6553 List<ResolveInfo> ris = null; 6554 try { 6555 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6556 intent, null, 0, userId); 6557 } catch (RemoteException e) { 6558 } 6559 ArraySet<String> pkgNames = new ArraySet<String>(); 6560 if (ris != null) { 6561 for (ResolveInfo ri : ris) { 6562 pkgNames.add(ri.activityInfo.packageName); 6563 } 6564 } 6565 return pkgNames; 6566 } 6567 6568 @Override 6569 public void notifyPackageUse(String packageName) { 6570 synchronized (mPackages) { 6571 PackageParser.Package p = mPackages.get(packageName); 6572 if (p == null) { 6573 return; 6574 } 6575 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6576 } 6577 } 6578 6579 @Override 6580 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6581 return performDexOptTraced(packageName, instructionSet); 6582 } 6583 6584 public boolean performDexOpt(String packageName, String instructionSet) { 6585 return performDexOptTraced(packageName, instructionSet); 6586 } 6587 6588 private boolean performDexOptTraced(String packageName, String instructionSet) { 6589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6590 try { 6591 return performDexOptInternal(packageName, instructionSet); 6592 } finally { 6593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6594 } 6595 } 6596 6597 private boolean performDexOptInternal(String packageName, String instructionSet) { 6598 PackageParser.Package p; 6599 final String targetInstructionSet; 6600 synchronized (mPackages) { 6601 p = mPackages.get(packageName); 6602 if (p == null) { 6603 return false; 6604 } 6605 mPackageUsage.write(false); 6606 6607 targetInstructionSet = instructionSet != null ? instructionSet : 6608 getPrimaryInstructionSet(p.applicationInfo); 6609 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 6610 return false; 6611 } 6612 } 6613 long callingId = Binder.clearCallingIdentity(); 6614 try { 6615 synchronized (mInstallLock) { 6616 final String[] instructionSets = new String[] { targetInstructionSet }; 6617 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6618 true /* inclDependencies */); 6619 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6620 } 6621 } finally { 6622 Binder.restoreCallingIdentity(callingId); 6623 } 6624 } 6625 6626 public ArraySet<String> getPackagesThatNeedDexOpt() { 6627 ArraySet<String> pkgs = null; 6628 synchronized (mPackages) { 6629 for (PackageParser.Package p : mPackages.values()) { 6630 if (DEBUG_DEXOPT) { 6631 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 6632 } 6633 if (!p.mDexOptPerformed.isEmpty()) { 6634 continue; 6635 } 6636 if (pkgs == null) { 6637 pkgs = new ArraySet<String>(); 6638 } 6639 pkgs.add(p.packageName); 6640 } 6641 } 6642 return pkgs; 6643 } 6644 6645 public void shutdown() { 6646 mPackageUsage.write(true); 6647 } 6648 6649 @Override 6650 public void forceDexOpt(String packageName) { 6651 enforceSystemOrRoot("forceDexOpt"); 6652 6653 PackageParser.Package pkg; 6654 synchronized (mPackages) { 6655 pkg = mPackages.get(packageName); 6656 if (pkg == null) { 6657 throw new IllegalArgumentException("Unknown package: " + packageName); 6658 } 6659 } 6660 6661 synchronized (mInstallLock) { 6662 final String[] instructionSets = new String[] { 6663 getPrimaryInstructionSet(pkg.applicationInfo) }; 6664 6665 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6666 6667 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6668 true /* inclDependencies */); 6669 6670 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6671 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6672 throw new IllegalStateException("Failed to dexopt: " + res); 6673 } 6674 } 6675 } 6676 6677 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6678 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6679 Slog.w(TAG, "Unable to update from " + oldPkg.name 6680 + " to " + newPkg.packageName 6681 + ": old package not in system partition"); 6682 return false; 6683 } else if (mPackages.get(oldPkg.name) != null) { 6684 Slog.w(TAG, "Unable to update from " + oldPkg.name 6685 + " to " + newPkg.packageName 6686 + ": old package still exists"); 6687 return false; 6688 } 6689 return true; 6690 } 6691 6692 private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) 6693 throws PackageManagerException { 6694 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 6695 if (res != 0) { 6696 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6697 "Failed to install " + packageName + ": " + res); 6698 } 6699 6700 final int[] users = sUserManager.getUserIds(); 6701 for (int user : users) { 6702 if (user != 0) { 6703 res = mInstaller.createUserData(volumeUuid, packageName, 6704 UserHandle.getUid(user, uid), user, seinfo); 6705 if (res != 0) { 6706 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6707 "Failed to createUserData " + packageName + ": " + res); 6708 } 6709 } 6710 } 6711 } 6712 6713 private int removeDataDirsLI(String volumeUuid, String packageName) { 6714 int[] users = sUserManager.getUserIds(); 6715 int res = 0; 6716 for (int user : users) { 6717 int resInner = mInstaller.remove(volumeUuid, packageName, user); 6718 if (resInner < 0) { 6719 res = resInner; 6720 } 6721 } 6722 6723 return res; 6724 } 6725 6726 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6727 int[] users = sUserManager.getUserIds(); 6728 int res = 0; 6729 for (int user : users) { 6730 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 6731 if (resInner < 0) { 6732 res = resInner; 6733 } 6734 } 6735 return res; 6736 } 6737 6738 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6739 PackageParser.Package changingLib) { 6740 if (file.path != null) { 6741 usesLibraryFiles.add(file.path); 6742 return; 6743 } 6744 PackageParser.Package p = mPackages.get(file.apk); 6745 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6746 // If we are doing this while in the middle of updating a library apk, 6747 // then we need to make sure to use that new apk for determining the 6748 // dependencies here. (We haven't yet finished committing the new apk 6749 // to the package manager state.) 6750 if (p == null || p.packageName.equals(changingLib.packageName)) { 6751 p = changingLib; 6752 } 6753 } 6754 if (p != null) { 6755 usesLibraryFiles.addAll(p.getAllCodePaths()); 6756 } 6757 } 6758 6759 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6760 PackageParser.Package changingLib) throws PackageManagerException { 6761 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6762 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6763 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6764 for (int i=0; i<N; i++) { 6765 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6766 if (file == null) { 6767 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6768 "Package " + pkg.packageName + " requires unavailable shared library " 6769 + pkg.usesLibraries.get(i) + "; failing!"); 6770 } 6771 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6772 } 6773 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6774 for (int i=0; i<N; i++) { 6775 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6776 if (file == null) { 6777 Slog.w(TAG, "Package " + pkg.packageName 6778 + " desires unavailable shared library " 6779 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6780 } else { 6781 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6782 } 6783 } 6784 N = usesLibraryFiles.size(); 6785 if (N > 0) { 6786 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6787 } else { 6788 pkg.usesLibraryFiles = null; 6789 } 6790 } 6791 } 6792 6793 private static boolean hasString(List<String> list, List<String> which) { 6794 if (list == null) { 6795 return false; 6796 } 6797 for (int i=list.size()-1; i>=0; i--) { 6798 for (int j=which.size()-1; j>=0; j--) { 6799 if (which.get(j).equals(list.get(i))) { 6800 return true; 6801 } 6802 } 6803 } 6804 return false; 6805 } 6806 6807 private void updateAllSharedLibrariesLPw() { 6808 for (PackageParser.Package pkg : mPackages.values()) { 6809 try { 6810 updateSharedLibrariesLPw(pkg, null); 6811 } catch (PackageManagerException e) { 6812 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6813 } 6814 } 6815 } 6816 6817 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6818 PackageParser.Package changingPkg) { 6819 ArrayList<PackageParser.Package> res = null; 6820 for (PackageParser.Package pkg : mPackages.values()) { 6821 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6822 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6823 if (res == null) { 6824 res = new ArrayList<PackageParser.Package>(); 6825 } 6826 res.add(pkg); 6827 try { 6828 updateSharedLibrariesLPw(pkg, changingPkg); 6829 } catch (PackageManagerException e) { 6830 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6831 } 6832 } 6833 } 6834 return res; 6835 } 6836 6837 /** 6838 * Derive the value of the {@code cpuAbiOverride} based on the provided 6839 * value and an optional stored value from the package settings. 6840 */ 6841 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6842 String cpuAbiOverride = null; 6843 6844 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6845 cpuAbiOverride = null; 6846 } else if (abiOverride != null) { 6847 cpuAbiOverride = abiOverride; 6848 } else if (settings != null) { 6849 cpuAbiOverride = settings.cpuAbiOverrideString; 6850 } 6851 6852 return cpuAbiOverride; 6853 } 6854 6855 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6856 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6858 try { 6859 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6860 } finally { 6861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6862 } 6863 } 6864 6865 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6866 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6867 boolean success = false; 6868 try { 6869 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6870 currentTime, user); 6871 success = true; 6872 return res; 6873 } finally { 6874 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6875 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6876 } 6877 } 6878 } 6879 6880 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6881 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6882 final File scanFile = new File(pkg.codePath); 6883 if (pkg.applicationInfo.getCodePath() == null || 6884 pkg.applicationInfo.getResourcePath() == null) { 6885 // Bail out. The resource and code paths haven't been set. 6886 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6887 "Code and resource paths haven't been set correctly"); 6888 } 6889 6890 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6891 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6892 } else { 6893 // Only allow system apps to be flagged as core apps. 6894 pkg.coreApp = false; 6895 } 6896 6897 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6898 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6899 } 6900 6901 if (mCustomResolverComponentName != null && 6902 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6903 setUpCustomResolverActivity(pkg); 6904 } 6905 6906 if (pkg.packageName.equals("android")) { 6907 synchronized (mPackages) { 6908 if (mAndroidApplication != null) { 6909 Slog.w(TAG, "*************************************************"); 6910 Slog.w(TAG, "Core android package being redefined. Skipping."); 6911 Slog.w(TAG, " file=" + scanFile); 6912 Slog.w(TAG, "*************************************************"); 6913 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6914 "Core android package being redefined. Skipping."); 6915 } 6916 6917 // Set up information for our fall-back user intent resolution activity. 6918 mPlatformPackage = pkg; 6919 pkg.mVersionCode = mSdkVersion; 6920 mAndroidApplication = pkg.applicationInfo; 6921 6922 if (!mResolverReplaced) { 6923 mResolveActivity.applicationInfo = mAndroidApplication; 6924 mResolveActivity.name = ResolverActivity.class.getName(); 6925 mResolveActivity.packageName = mAndroidApplication.packageName; 6926 mResolveActivity.processName = "system:ui"; 6927 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6928 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6929 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6930 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6931 mResolveActivity.exported = true; 6932 mResolveActivity.enabled = true; 6933 mResolveInfo.activityInfo = mResolveActivity; 6934 mResolveInfo.priority = 0; 6935 mResolveInfo.preferredOrder = 0; 6936 mResolveInfo.match = 0; 6937 mResolveComponentName = new ComponentName( 6938 mAndroidApplication.packageName, mResolveActivity.name); 6939 } 6940 } 6941 } 6942 6943 if (DEBUG_PACKAGE_SCANNING) { 6944 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6945 Log.d(TAG, "Scanning package " + pkg.packageName); 6946 } 6947 6948 if (mPackages.containsKey(pkg.packageName) 6949 || mSharedLibraries.containsKey(pkg.packageName)) { 6950 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6951 "Application package " + pkg.packageName 6952 + " already installed. Skipping duplicate."); 6953 } 6954 6955 // If we're only installing presumed-existing packages, require that the 6956 // scanned APK is both already known and at the path previously established 6957 // for it. Previously unknown packages we pick up normally, but if we have an 6958 // a priori expectation about this package's install presence, enforce it. 6959 // With a singular exception for new system packages. When an OTA contains 6960 // a new system package, we allow the codepath to change from a system location 6961 // to the user-installed location. If we don't allow this change, any newer, 6962 // user-installed version of the application will be ignored. 6963 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6964 if (mExpectingBetter.containsKey(pkg.packageName)) { 6965 logCriticalInfo(Log.WARN, 6966 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 6967 } else { 6968 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6969 if (known != null) { 6970 if (DEBUG_PACKAGE_SCANNING) { 6971 Log.d(TAG, "Examining " + pkg.codePath 6972 + " and requiring known paths " + known.codePathString 6973 + " & " + known.resourcePathString); 6974 } 6975 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6976 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6977 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6978 "Application package " + pkg.packageName 6979 + " found at " + pkg.applicationInfo.getCodePath() 6980 + " but expected at " + known.codePathString + "; ignoring."); 6981 } 6982 } 6983 } 6984 } 6985 6986 // Initialize package source and resource directories 6987 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6988 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6989 6990 SharedUserSetting suid = null; 6991 PackageSetting pkgSetting = null; 6992 6993 if (!isSystemApp(pkg)) { 6994 // Only system apps can use these features. 6995 pkg.mOriginalPackages = null; 6996 pkg.mRealPackage = null; 6997 pkg.mAdoptPermissions = null; 6998 } 6999 7000 // writer 7001 synchronized (mPackages) { 7002 if (pkg.mSharedUserId != null) { 7003 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7004 if (suid == null) { 7005 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7006 "Creating application package " + pkg.packageName 7007 + " for shared user failed"); 7008 } 7009 if (DEBUG_PACKAGE_SCANNING) { 7010 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7011 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7012 + "): packages=" + suid.packages); 7013 } 7014 } 7015 7016 // Check if we are renaming from an original package name. 7017 PackageSetting origPackage = null; 7018 String realName = null; 7019 if (pkg.mOriginalPackages != null) { 7020 // This package may need to be renamed to a previously 7021 // installed name. Let's check on that... 7022 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7023 if (pkg.mOriginalPackages.contains(renamed)) { 7024 // This package had originally been installed as the 7025 // original name, and we have already taken care of 7026 // transitioning to the new one. Just update the new 7027 // one to continue using the old name. 7028 realName = pkg.mRealPackage; 7029 if (!pkg.packageName.equals(renamed)) { 7030 // Callers into this function may have already taken 7031 // care of renaming the package; only do it here if 7032 // it is not already done. 7033 pkg.setPackageName(renamed); 7034 } 7035 7036 } else { 7037 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7038 if ((origPackage = mSettings.peekPackageLPr( 7039 pkg.mOriginalPackages.get(i))) != null) { 7040 // We do have the package already installed under its 7041 // original name... should we use it? 7042 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7043 // New package is not compatible with original. 7044 origPackage = null; 7045 continue; 7046 } else if (origPackage.sharedUser != null) { 7047 // Make sure uid is compatible between packages. 7048 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7049 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7050 + " to " + pkg.packageName + ": old uid " 7051 + origPackage.sharedUser.name 7052 + " differs from " + pkg.mSharedUserId); 7053 origPackage = null; 7054 continue; 7055 } 7056 } else { 7057 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7058 + pkg.packageName + " to old name " + origPackage.name); 7059 } 7060 break; 7061 } 7062 } 7063 } 7064 } 7065 7066 if (mTransferedPackages.contains(pkg.packageName)) { 7067 Slog.w(TAG, "Package " + pkg.packageName 7068 + " was transferred to another, but its .apk remains"); 7069 } 7070 7071 // Just create the setting, don't add it yet. For already existing packages 7072 // the PkgSetting exists already and doesn't have to be created. 7073 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7074 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7075 pkg.applicationInfo.primaryCpuAbi, 7076 pkg.applicationInfo.secondaryCpuAbi, 7077 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7078 user, false); 7079 if (pkgSetting == null) { 7080 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7081 "Creating application package " + pkg.packageName + " failed"); 7082 } 7083 7084 if (pkgSetting.origPackage != null) { 7085 // If we are first transitioning from an original package, 7086 // fix up the new package's name now. We need to do this after 7087 // looking up the package under its new name, so getPackageLP 7088 // can take care of fiddling things correctly. 7089 pkg.setPackageName(origPackage.name); 7090 7091 // File a report about this. 7092 String msg = "New package " + pkgSetting.realName 7093 + " renamed to replace old package " + pkgSetting.name; 7094 reportSettingsProblem(Log.WARN, msg); 7095 7096 // Make a note of it. 7097 mTransferedPackages.add(origPackage.name); 7098 7099 // No longer need to retain this. 7100 pkgSetting.origPackage = null; 7101 } 7102 7103 if (realName != null) { 7104 // Make a note of it. 7105 mTransferedPackages.add(pkg.packageName); 7106 } 7107 7108 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7109 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7110 } 7111 7112 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7113 // Check all shared libraries and map to their actual file path. 7114 // We only do this here for apps not on a system dir, because those 7115 // are the only ones that can fail an install due to this. We 7116 // will take care of the system apps by updating all of their 7117 // library paths after the scan is done. 7118 updateSharedLibrariesLPw(pkg, null); 7119 } 7120 7121 if (mFoundPolicyFile) { 7122 SELinuxMMAC.assignSeinfoValue(pkg); 7123 } 7124 7125 pkg.applicationInfo.uid = pkgSetting.appId; 7126 pkg.mExtras = pkgSetting; 7127 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7128 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7129 // We just determined the app is signed correctly, so bring 7130 // over the latest parsed certs. 7131 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7132 } else { 7133 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7134 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7135 "Package " + pkg.packageName + " upgrade keys do not match the " 7136 + "previously installed version"); 7137 } else { 7138 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7139 String msg = "System package " + pkg.packageName 7140 + " signature changed; retaining data."; 7141 reportSettingsProblem(Log.WARN, msg); 7142 } 7143 } 7144 } else { 7145 try { 7146 verifySignaturesLP(pkgSetting, pkg); 7147 // We just determined the app is signed correctly, so bring 7148 // over the latest parsed certs. 7149 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7150 } catch (PackageManagerException e) { 7151 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7152 throw e; 7153 } 7154 // The signature has changed, but this package is in the system 7155 // image... let's recover! 7156 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7157 // However... if this package is part of a shared user, but it 7158 // doesn't match the signature of the shared user, let's fail. 7159 // What this means is that you can't change the signatures 7160 // associated with an overall shared user, which doesn't seem all 7161 // that unreasonable. 7162 if (pkgSetting.sharedUser != null) { 7163 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7164 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7165 throw new PackageManagerException( 7166 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7167 "Signature mismatch for shared user: " 7168 + pkgSetting.sharedUser); 7169 } 7170 } 7171 // File a report about this. 7172 String msg = "System package " + pkg.packageName 7173 + " signature changed; retaining data."; 7174 reportSettingsProblem(Log.WARN, msg); 7175 } 7176 } 7177 // Verify that this new package doesn't have any content providers 7178 // that conflict with existing packages. Only do this if the 7179 // package isn't already installed, since we don't want to break 7180 // things that are installed. 7181 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7182 final int N = pkg.providers.size(); 7183 int i; 7184 for (i=0; i<N; i++) { 7185 PackageParser.Provider p = pkg.providers.get(i); 7186 if (p.info.authority != null) { 7187 String names[] = p.info.authority.split(";"); 7188 for (int j = 0; j < names.length; j++) { 7189 if (mProvidersByAuthority.containsKey(names[j])) { 7190 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7191 final String otherPackageName = 7192 ((other != null && other.getComponentName() != null) ? 7193 other.getComponentName().getPackageName() : "?"); 7194 throw new PackageManagerException( 7195 INSTALL_FAILED_CONFLICTING_PROVIDER, 7196 "Can't install because provider name " + names[j] 7197 + " (in package " + pkg.applicationInfo.packageName 7198 + ") is already used by " + otherPackageName); 7199 } 7200 } 7201 } 7202 } 7203 } 7204 7205 if (pkg.mAdoptPermissions != null) { 7206 // This package wants to adopt ownership of permissions from 7207 // another package. 7208 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7209 final String origName = pkg.mAdoptPermissions.get(i); 7210 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7211 if (orig != null) { 7212 if (verifyPackageUpdateLPr(orig, pkg)) { 7213 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7214 + pkg.packageName); 7215 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7216 } 7217 } 7218 } 7219 } 7220 } 7221 7222 final String pkgName = pkg.packageName; 7223 7224 final long scanFileTime = scanFile.lastModified(); 7225 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7226 pkg.applicationInfo.processName = fixProcessName( 7227 pkg.applicationInfo.packageName, 7228 pkg.applicationInfo.processName, 7229 pkg.applicationInfo.uid); 7230 7231 if (pkg != mPlatformPackage) { 7232 // This is a normal package, need to make its data directory. 7233 final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory( 7234 pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName); 7235 7236 boolean uidError = false; 7237 if (dataPath.exists()) { 7238 int currentUid = 0; 7239 try { 7240 StructStat stat = Os.stat(dataPath.getPath()); 7241 currentUid = stat.st_uid; 7242 } catch (ErrnoException e) { 7243 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 7244 } 7245 7246 // If we have mismatched owners for the data path, we have a problem. 7247 if (currentUid != pkg.applicationInfo.uid) { 7248 boolean recovered = false; 7249 if (currentUid == 0) { 7250 // The directory somehow became owned by root. Wow. 7251 // This is probably because the system was stopped while 7252 // installd was in the middle of messing with its libs 7253 // directory. Ask installd to fix that. 7254 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 7255 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 7256 if (ret >= 0) { 7257 recovered = true; 7258 String msg = "Package " + pkg.packageName 7259 + " unexpectedly changed to uid 0; recovered to " + 7260 + pkg.applicationInfo.uid; 7261 reportSettingsProblem(Log.WARN, msg); 7262 } 7263 } 7264 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7265 || (scanFlags&SCAN_BOOTING) != 0)) { 7266 // If this is a system app, we can at least delete its 7267 // current data so the application will still work. 7268 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 7269 if (ret >= 0) { 7270 // TODO: Kill the processes first 7271 // Old data gone! 7272 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 7273 ? "System package " : "Third party package "; 7274 String msg = prefix + pkg.packageName 7275 + " has changed from uid: " 7276 + currentUid + " to " 7277 + pkg.applicationInfo.uid + "; old data erased"; 7278 reportSettingsProblem(Log.WARN, msg); 7279 recovered = true; 7280 } 7281 if (!recovered) { 7282 mHasSystemUidErrors = true; 7283 } 7284 } else if (!recovered) { 7285 // If we allow this install to proceed, we will be broken. 7286 // Abort, abort! 7287 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 7288 "scanPackageLI"); 7289 } 7290 if (!recovered) { 7291 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 7292 + pkg.applicationInfo.uid + "/fs_" 7293 + currentUid; 7294 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 7295 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 7296 String msg = "Package " + pkg.packageName 7297 + " has mismatched uid: " 7298 + currentUid + " on disk, " 7299 + pkg.applicationInfo.uid + " in settings"; 7300 // writer 7301 synchronized (mPackages) { 7302 mSettings.mReadMessages.append(msg); 7303 mSettings.mReadMessages.append('\n'); 7304 uidError = true; 7305 if (!pkgSetting.uidError) { 7306 reportSettingsProblem(Log.ERROR, msg); 7307 } 7308 } 7309 } 7310 } 7311 7312 // Ensure that directories are prepared 7313 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7314 pkg.applicationInfo.seinfo); 7315 7316 if (mShouldRestoreconData) { 7317 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 7318 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 7319 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 7320 } 7321 } else { 7322 if (DEBUG_PACKAGE_SCANNING) { 7323 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7324 Log.v(TAG, "Want this data dir: " + dataPath); 7325 } 7326 createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 7327 pkg.applicationInfo.seinfo); 7328 } 7329 7330 // Get all of our default paths setup 7331 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7332 7333 pkgSetting.uidError = uidError; 7334 } 7335 7336 final String path = scanFile.getPath(); 7337 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7338 7339 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7340 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7341 7342 // Some system apps still use directory structure for native libraries 7343 // in which case we might end up not detecting abi solely based on apk 7344 // structure. Try to detect abi based on directory structure. 7345 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7346 pkg.applicationInfo.primaryCpuAbi == null) { 7347 setBundledAppAbisAndRoots(pkg, pkgSetting); 7348 setNativeLibraryPaths(pkg); 7349 } 7350 7351 } else { 7352 if ((scanFlags & SCAN_MOVE) != 0) { 7353 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7354 // but we already have this packages package info in the PackageSetting. We just 7355 // use that and derive the native library path based on the new codepath. 7356 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7357 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7358 } 7359 7360 // Set native library paths again. For moves, the path will be updated based on the 7361 // ABIs we've determined above. For non-moves, the path will be updated based on the 7362 // ABIs we determined during compilation, but the path will depend on the final 7363 // package path (after the rename away from the stage path). 7364 setNativeLibraryPaths(pkg); 7365 } 7366 7367 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 7368 final int[] userIds = sUserManager.getUserIds(); 7369 synchronized (mInstallLock) { 7370 // Make sure all user data directories are ready to roll; we're okay 7371 // if they already exist 7372 if (!TextUtils.isEmpty(pkg.volumeUuid)) { 7373 for (int userId : userIds) { 7374 if (userId != UserHandle.USER_SYSTEM) { 7375 mInstaller.createUserData(pkg.volumeUuid, pkg.packageName, 7376 UserHandle.getUid(userId, pkg.applicationInfo.uid), userId, 7377 pkg.applicationInfo.seinfo); 7378 } 7379 } 7380 } 7381 7382 // Create a native library symlink only if we have native libraries 7383 // and if the native libraries are 32 bit libraries. We do not provide 7384 // this symlink for 64 bit libraries. 7385 if (pkg.applicationInfo.primaryCpuAbi != null && 7386 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 7387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib"); 7388 try { 7389 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 7390 for (int userId : userIds) { 7391 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 7392 nativeLibPath, userId) < 0) { 7393 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7394 "Failed linking native library dir (user=" + userId + ")"); 7395 } 7396 } 7397 } finally { 7398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7399 } 7400 } 7401 } 7402 7403 // This is a special case for the "system" package, where the ABI is 7404 // dictated by the zygote configuration (and init.rc). We should keep track 7405 // of this ABI so that we can deal with "normal" applications that run under 7406 // the same UID correctly. 7407 if (mPlatformPackage == pkg) { 7408 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7409 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7410 } 7411 7412 // If there's a mismatch between the abi-override in the package setting 7413 // and the abiOverride specified for the install. Warn about this because we 7414 // would've already compiled the app without taking the package setting into 7415 // account. 7416 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7417 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7418 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7419 " for package " + pkg.packageName); 7420 } 7421 } 7422 7423 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7424 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7425 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7426 7427 // Copy the derived override back to the parsed package, so that we can 7428 // update the package settings accordingly. 7429 pkg.cpuAbiOverride = cpuAbiOverride; 7430 7431 if (DEBUG_ABI_SELECTION) { 7432 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7433 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7434 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7435 } 7436 7437 // Push the derived path down into PackageSettings so we know what to 7438 // clean up at uninstall time. 7439 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7440 7441 if (DEBUG_ABI_SELECTION) { 7442 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7443 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7444 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7445 } 7446 7447 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7448 // We don't do this here during boot because we can do it all 7449 // at once after scanning all existing packages. 7450 // 7451 // We also do this *before* we perform dexopt on this package, so that 7452 // we can avoid redundant dexopts, and also to make sure we've got the 7453 // code and package path correct. 7454 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7455 pkg, true /* boot complete */); 7456 } 7457 7458 if (mFactoryTest && pkg.requestedPermissions.contains( 7459 android.Manifest.permission.FACTORY_TEST)) { 7460 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7461 } 7462 7463 ArrayList<PackageParser.Package> clientLibPkgs = null; 7464 7465 // writer 7466 synchronized (mPackages) { 7467 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7468 // Only system apps can add new shared libraries. 7469 if (pkg.libraryNames != null) { 7470 for (int i=0; i<pkg.libraryNames.size(); i++) { 7471 String name = pkg.libraryNames.get(i); 7472 boolean allowed = false; 7473 if (pkg.isUpdatedSystemApp()) { 7474 // New library entries can only be added through the 7475 // system image. This is important to get rid of a lot 7476 // of nasty edge cases: for example if we allowed a non- 7477 // system update of the app to add a library, then uninstalling 7478 // the update would make the library go away, and assumptions 7479 // we made such as through app install filtering would now 7480 // have allowed apps on the device which aren't compatible 7481 // with it. Better to just have the restriction here, be 7482 // conservative, and create many fewer cases that can negatively 7483 // impact the user experience. 7484 final PackageSetting sysPs = mSettings 7485 .getDisabledSystemPkgLPr(pkg.packageName); 7486 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7487 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7488 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7489 allowed = true; 7490 break; 7491 } 7492 } 7493 } 7494 } else { 7495 allowed = true; 7496 } 7497 if (allowed) { 7498 if (!mSharedLibraries.containsKey(name)) { 7499 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7500 } else if (!name.equals(pkg.packageName)) { 7501 Slog.w(TAG, "Package " + pkg.packageName + " library " 7502 + name + " already exists; skipping"); 7503 } 7504 } else { 7505 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7506 + name + " that is not declared on system image; skipping"); 7507 } 7508 } 7509 if ((scanFlags & SCAN_BOOTING) == 0) { 7510 // If we are not booting, we need to update any applications 7511 // that are clients of our shared library. If we are booting, 7512 // this will all be done once the scan is complete. 7513 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7514 } 7515 } 7516 } 7517 } 7518 7519 // Request the ActivityManager to kill the process(only for existing packages) 7520 // so that we do not end up in a confused state while the user is still using the older 7521 // version of the application while the new one gets installed. 7522 if ((scanFlags & SCAN_REPLACING) != 0) { 7523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7524 7525 killApplication(pkg.applicationInfo.packageName, 7526 pkg.applicationInfo.uid, "replace pkg"); 7527 7528 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7529 } 7530 7531 // Also need to kill any apps that are dependent on the library. 7532 if (clientLibPkgs != null) { 7533 for (int i=0; i<clientLibPkgs.size(); i++) { 7534 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7535 killApplication(clientPkg.applicationInfo.packageName, 7536 clientPkg.applicationInfo.uid, "update lib"); 7537 } 7538 } 7539 7540 // Make sure we're not adding any bogus keyset info 7541 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7542 ksms.assertScannedPackageValid(pkg); 7543 7544 // writer 7545 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7546 7547 boolean createIdmapFailed = false; 7548 synchronized (mPackages) { 7549 // We don't expect installation to fail beyond this point 7550 7551 // Add the new setting to mSettings 7552 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7553 // Add the new setting to mPackages 7554 mPackages.put(pkg.applicationInfo.packageName, pkg); 7555 // Make sure we don't accidentally delete its data. 7556 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7557 while (iter.hasNext()) { 7558 PackageCleanItem item = iter.next(); 7559 if (pkgName.equals(item.packageName)) { 7560 iter.remove(); 7561 } 7562 } 7563 7564 // Take care of first install / last update times. 7565 if (currentTime != 0) { 7566 if (pkgSetting.firstInstallTime == 0) { 7567 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7568 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7569 pkgSetting.lastUpdateTime = currentTime; 7570 } 7571 } else if (pkgSetting.firstInstallTime == 0) { 7572 // We need *something*. Take time time stamp of the file. 7573 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7574 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7575 if (scanFileTime != pkgSetting.timeStamp) { 7576 // A package on the system image has changed; consider this 7577 // to be an update. 7578 pkgSetting.lastUpdateTime = scanFileTime; 7579 } 7580 } 7581 7582 // Add the package's KeySets to the global KeySetManagerService 7583 ksms.addScannedPackageLPw(pkg); 7584 7585 int N = pkg.providers.size(); 7586 StringBuilder r = null; 7587 int i; 7588 for (i=0; i<N; i++) { 7589 PackageParser.Provider p = pkg.providers.get(i); 7590 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7591 p.info.processName, pkg.applicationInfo.uid); 7592 mProviders.addProvider(p); 7593 p.syncable = p.info.isSyncable; 7594 if (p.info.authority != null) { 7595 String names[] = p.info.authority.split(";"); 7596 p.info.authority = null; 7597 for (int j = 0; j < names.length; j++) { 7598 if (j == 1 && p.syncable) { 7599 // We only want the first authority for a provider to possibly be 7600 // syncable, so if we already added this provider using a different 7601 // authority clear the syncable flag. We copy the provider before 7602 // changing it because the mProviders object contains a reference 7603 // to a provider that we don't want to change. 7604 // Only do this for the second authority since the resulting provider 7605 // object can be the same for all future authorities for this provider. 7606 p = new PackageParser.Provider(p); 7607 p.syncable = false; 7608 } 7609 if (!mProvidersByAuthority.containsKey(names[j])) { 7610 mProvidersByAuthority.put(names[j], p); 7611 if (p.info.authority == null) { 7612 p.info.authority = names[j]; 7613 } else { 7614 p.info.authority = p.info.authority + ";" + names[j]; 7615 } 7616 if (DEBUG_PACKAGE_SCANNING) { 7617 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7618 Log.d(TAG, "Registered content provider: " + names[j] 7619 + ", className = " + p.info.name + ", isSyncable = " 7620 + p.info.isSyncable); 7621 } 7622 } else { 7623 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7624 Slog.w(TAG, "Skipping provider name " + names[j] + 7625 " (in package " + pkg.applicationInfo.packageName + 7626 "): name already used by " 7627 + ((other != null && other.getComponentName() != null) 7628 ? other.getComponentName().getPackageName() : "?")); 7629 } 7630 } 7631 } 7632 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7633 if (r == null) { 7634 r = new StringBuilder(256); 7635 } else { 7636 r.append(' '); 7637 } 7638 r.append(p.info.name); 7639 } 7640 } 7641 if (r != null) { 7642 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7643 } 7644 7645 N = pkg.services.size(); 7646 r = null; 7647 for (i=0; i<N; i++) { 7648 PackageParser.Service s = pkg.services.get(i); 7649 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7650 s.info.processName, pkg.applicationInfo.uid); 7651 mServices.addService(s); 7652 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7653 if (r == null) { 7654 r = new StringBuilder(256); 7655 } else { 7656 r.append(' '); 7657 } 7658 r.append(s.info.name); 7659 } 7660 } 7661 if (r != null) { 7662 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7663 } 7664 7665 N = pkg.receivers.size(); 7666 r = null; 7667 for (i=0; i<N; i++) { 7668 PackageParser.Activity a = pkg.receivers.get(i); 7669 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7670 a.info.processName, pkg.applicationInfo.uid); 7671 mReceivers.addActivity(a, "receiver"); 7672 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7673 if (r == null) { 7674 r = new StringBuilder(256); 7675 } else { 7676 r.append(' '); 7677 } 7678 r.append(a.info.name); 7679 } 7680 } 7681 if (r != null) { 7682 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7683 } 7684 7685 N = pkg.activities.size(); 7686 r = null; 7687 for (i=0; i<N; i++) { 7688 PackageParser.Activity a = pkg.activities.get(i); 7689 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7690 a.info.processName, pkg.applicationInfo.uid); 7691 mActivities.addActivity(a, "activity"); 7692 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7693 if (r == null) { 7694 r = new StringBuilder(256); 7695 } else { 7696 r.append(' '); 7697 } 7698 r.append(a.info.name); 7699 } 7700 } 7701 if (r != null) { 7702 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7703 } 7704 7705 N = pkg.permissionGroups.size(); 7706 r = null; 7707 for (i=0; i<N; i++) { 7708 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7709 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7710 if (cur == null) { 7711 mPermissionGroups.put(pg.info.name, pg); 7712 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7713 if (r == null) { 7714 r = new StringBuilder(256); 7715 } else { 7716 r.append(' '); 7717 } 7718 r.append(pg.info.name); 7719 } 7720 } else { 7721 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7722 + pg.info.packageName + " ignored: original from " 7723 + cur.info.packageName); 7724 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7725 if (r == null) { 7726 r = new StringBuilder(256); 7727 } else { 7728 r.append(' '); 7729 } 7730 r.append("DUP:"); 7731 r.append(pg.info.name); 7732 } 7733 } 7734 } 7735 if (r != null) { 7736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7737 } 7738 7739 N = pkg.permissions.size(); 7740 r = null; 7741 for (i=0; i<N; i++) { 7742 PackageParser.Permission p = pkg.permissions.get(i); 7743 7744 // Assume by default that we did not install this permission into the system. 7745 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7746 7747 // Now that permission groups have a special meaning, we ignore permission 7748 // groups for legacy apps to prevent unexpected behavior. In particular, 7749 // permissions for one app being granted to someone just becuase they happen 7750 // to be in a group defined by another app (before this had no implications). 7751 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7752 p.group = mPermissionGroups.get(p.info.group); 7753 // Warn for a permission in an unknown group. 7754 if (p.info.group != null && p.group == null) { 7755 Slog.w(TAG, "Permission " + p.info.name + " from package " 7756 + p.info.packageName + " in an unknown group " + p.info.group); 7757 } 7758 } 7759 7760 ArrayMap<String, BasePermission> permissionMap = 7761 p.tree ? mSettings.mPermissionTrees 7762 : mSettings.mPermissions; 7763 BasePermission bp = permissionMap.get(p.info.name); 7764 7765 // Allow system apps to redefine non-system permissions 7766 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7767 final boolean currentOwnerIsSystem = (bp.perm != null 7768 && isSystemApp(bp.perm.owner)); 7769 if (isSystemApp(p.owner)) { 7770 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7771 // It's a built-in permission and no owner, take ownership now 7772 bp.packageSetting = pkgSetting; 7773 bp.perm = p; 7774 bp.uid = pkg.applicationInfo.uid; 7775 bp.sourcePackage = p.info.packageName; 7776 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7777 } else if (!currentOwnerIsSystem) { 7778 String msg = "New decl " + p.owner + " of permission " 7779 + p.info.name + " is system; overriding " + bp.sourcePackage; 7780 reportSettingsProblem(Log.WARN, msg); 7781 bp = null; 7782 } 7783 } 7784 } 7785 7786 if (bp == null) { 7787 bp = new BasePermission(p.info.name, p.info.packageName, 7788 BasePermission.TYPE_NORMAL); 7789 permissionMap.put(p.info.name, bp); 7790 } 7791 7792 if (bp.perm == null) { 7793 if (bp.sourcePackage == null 7794 || bp.sourcePackage.equals(p.info.packageName)) { 7795 BasePermission tree = findPermissionTreeLP(p.info.name); 7796 if (tree == null 7797 || tree.sourcePackage.equals(p.info.packageName)) { 7798 bp.packageSetting = pkgSetting; 7799 bp.perm = p; 7800 bp.uid = pkg.applicationInfo.uid; 7801 bp.sourcePackage = p.info.packageName; 7802 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7803 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7804 if (r == null) { 7805 r = new StringBuilder(256); 7806 } else { 7807 r.append(' '); 7808 } 7809 r.append(p.info.name); 7810 } 7811 } else { 7812 Slog.w(TAG, "Permission " + p.info.name + " from package " 7813 + p.info.packageName + " ignored: base tree " 7814 + tree.name + " is from package " 7815 + tree.sourcePackage); 7816 } 7817 } else { 7818 Slog.w(TAG, "Permission " + p.info.name + " from package " 7819 + p.info.packageName + " ignored: original from " 7820 + bp.sourcePackage); 7821 } 7822 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7823 if (r == null) { 7824 r = new StringBuilder(256); 7825 } else { 7826 r.append(' '); 7827 } 7828 r.append("DUP:"); 7829 r.append(p.info.name); 7830 } 7831 if (bp.perm == p) { 7832 bp.protectionLevel = p.info.protectionLevel; 7833 } 7834 } 7835 7836 if (r != null) { 7837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7838 } 7839 7840 N = pkg.instrumentation.size(); 7841 r = null; 7842 for (i=0; i<N; i++) { 7843 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7844 a.info.packageName = pkg.applicationInfo.packageName; 7845 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7846 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7847 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7848 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7849 a.info.dataDir = pkg.applicationInfo.dataDir; 7850 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7851 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7852 7853 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7854 // need other information about the application, like the ABI and what not ? 7855 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7856 mInstrumentation.put(a.getComponentName(), a); 7857 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7858 if (r == null) { 7859 r = new StringBuilder(256); 7860 } else { 7861 r.append(' '); 7862 } 7863 r.append(a.info.name); 7864 } 7865 } 7866 if (r != null) { 7867 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7868 } 7869 7870 if (pkg.protectedBroadcasts != null) { 7871 N = pkg.protectedBroadcasts.size(); 7872 for (i=0; i<N; i++) { 7873 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7874 } 7875 } 7876 7877 pkgSetting.setTimeStamp(scanFileTime); 7878 7879 // Create idmap files for pairs of (packages, overlay packages). 7880 // Note: "android", ie framework-res.apk, is handled by native layers. 7881 if (pkg.mOverlayTarget != null) { 7882 // This is an overlay package. 7883 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7884 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7885 mOverlays.put(pkg.mOverlayTarget, 7886 new ArrayMap<String, PackageParser.Package>()); 7887 } 7888 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7889 map.put(pkg.packageName, pkg); 7890 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7891 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7892 createIdmapFailed = true; 7893 } 7894 } 7895 } else if (mOverlays.containsKey(pkg.packageName) && 7896 !pkg.packageName.equals("android")) { 7897 // This is a regular package, with one or more known overlay packages. 7898 createIdmapsForPackageLI(pkg); 7899 } 7900 } 7901 7902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7903 7904 if (createIdmapFailed) { 7905 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7906 "scanPackageLI failed to createIdmap"); 7907 } 7908 return pkg; 7909 } 7910 7911 /** 7912 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7913 * is derived purely on the basis of the contents of {@code scanFile} and 7914 * {@code cpuAbiOverride}. 7915 * 7916 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7917 */ 7918 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7919 String cpuAbiOverride, boolean extractLibs) 7920 throws PackageManagerException { 7921 // TODO: We can probably be smarter about this stuff. For installed apps, 7922 // we can calculate this information at install time once and for all. For 7923 // system apps, we can probably assume that this information doesn't change 7924 // after the first boot scan. As things stand, we do lots of unnecessary work. 7925 7926 // Give ourselves some initial paths; we'll come back for another 7927 // pass once we've determined ABI below. 7928 setNativeLibraryPaths(pkg); 7929 7930 // We would never need to extract libs for forward-locked and external packages, 7931 // since the container service will do it for us. We shouldn't attempt to 7932 // extract libs from system app when it was not updated. 7933 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7934 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7935 extractLibs = false; 7936 } 7937 7938 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7939 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7940 7941 NativeLibraryHelper.Handle handle = null; 7942 try { 7943 handle = NativeLibraryHelper.Handle.create(pkg); 7944 // TODO(multiArch): This can be null for apps that didn't go through the 7945 // usual installation process. We can calculate it again, like we 7946 // do during install time. 7947 // 7948 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7949 // unnecessary. 7950 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7951 7952 // Null out the abis so that they can be recalculated. 7953 pkg.applicationInfo.primaryCpuAbi = null; 7954 pkg.applicationInfo.secondaryCpuAbi = null; 7955 if (isMultiArch(pkg.applicationInfo)) { 7956 // Warn if we've set an abiOverride for multi-lib packages.. 7957 // By definition, we need to copy both 32 and 64 bit libraries for 7958 // such packages. 7959 if (pkg.cpuAbiOverride != null 7960 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7961 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7962 } 7963 7964 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7965 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7966 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7967 if (extractLibs) { 7968 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7969 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7970 useIsaSpecificSubdirs); 7971 } else { 7972 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7973 } 7974 } 7975 7976 maybeThrowExceptionForMultiArchCopy( 7977 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7978 7979 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7980 if (extractLibs) { 7981 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7982 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7983 useIsaSpecificSubdirs); 7984 } else { 7985 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7986 } 7987 } 7988 7989 maybeThrowExceptionForMultiArchCopy( 7990 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7991 7992 if (abi64 >= 0) { 7993 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7994 } 7995 7996 if (abi32 >= 0) { 7997 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7998 if (abi64 >= 0) { 7999 pkg.applicationInfo.secondaryCpuAbi = abi; 8000 } else { 8001 pkg.applicationInfo.primaryCpuAbi = abi; 8002 } 8003 } 8004 } else { 8005 String[] abiList = (cpuAbiOverride != null) ? 8006 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8007 8008 // Enable gross and lame hacks for apps that are built with old 8009 // SDK tools. We must scan their APKs for renderscript bitcode and 8010 // not launch them if it's present. Don't bother checking on devices 8011 // that don't have 64 bit support. 8012 boolean needsRenderScriptOverride = false; 8013 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8014 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8015 abiList = Build.SUPPORTED_32_BIT_ABIS; 8016 needsRenderScriptOverride = true; 8017 } 8018 8019 final int copyRet; 8020 if (extractLibs) { 8021 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8022 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8023 } else { 8024 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8025 } 8026 8027 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8028 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8029 "Error unpackaging native libs for app, errorCode=" + copyRet); 8030 } 8031 8032 if (copyRet >= 0) { 8033 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8034 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8035 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8036 } else if (needsRenderScriptOverride) { 8037 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8038 } 8039 } 8040 } catch (IOException ioe) { 8041 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8042 } finally { 8043 IoUtils.closeQuietly(handle); 8044 } 8045 8046 // Now that we've calculated the ABIs and determined if it's an internal app, 8047 // we will go ahead and populate the nativeLibraryPath. 8048 setNativeLibraryPaths(pkg); 8049 } 8050 8051 /** 8052 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8053 * i.e, so that all packages can be run inside a single process if required. 8054 * 8055 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8056 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8057 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8058 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8059 * updating a package that belongs to a shared user. 8060 * 8061 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8062 * adds unnecessary complexity. 8063 */ 8064 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8065 PackageParser.Package scannedPackage, boolean bootComplete) { 8066 String requiredInstructionSet = null; 8067 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8068 requiredInstructionSet = VMRuntime.getInstructionSet( 8069 scannedPackage.applicationInfo.primaryCpuAbi); 8070 } 8071 8072 PackageSetting requirer = null; 8073 for (PackageSetting ps : packagesForUser) { 8074 // If packagesForUser contains scannedPackage, we skip it. This will happen 8075 // when scannedPackage is an update of an existing package. Without this check, 8076 // we will never be able to change the ABI of any package belonging to a shared 8077 // user, even if it's compatible with other packages. 8078 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8079 if (ps.primaryCpuAbiString == null) { 8080 continue; 8081 } 8082 8083 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8084 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8085 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8086 // this but there's not much we can do. 8087 String errorMessage = "Instruction set mismatch, " 8088 + ((requirer == null) ? "[caller]" : requirer) 8089 + " requires " + requiredInstructionSet + " whereas " + ps 8090 + " requires " + instructionSet; 8091 Slog.w(TAG, errorMessage); 8092 } 8093 8094 if (requiredInstructionSet == null) { 8095 requiredInstructionSet = instructionSet; 8096 requirer = ps; 8097 } 8098 } 8099 } 8100 8101 if (requiredInstructionSet != null) { 8102 String adjustedAbi; 8103 if (requirer != null) { 8104 // requirer != null implies that either scannedPackage was null or that scannedPackage 8105 // did not require an ABI, in which case we have to adjust scannedPackage to match 8106 // the ABI of the set (which is the same as requirer's ABI) 8107 adjustedAbi = requirer.primaryCpuAbiString; 8108 if (scannedPackage != null) { 8109 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8110 } 8111 } else { 8112 // requirer == null implies that we're updating all ABIs in the set to 8113 // match scannedPackage. 8114 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8115 } 8116 8117 for (PackageSetting ps : packagesForUser) { 8118 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8119 if (ps.primaryCpuAbiString != null) { 8120 continue; 8121 } 8122 8123 ps.primaryCpuAbiString = adjustedAbi; 8124 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 8125 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8126 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi); 8127 mInstaller.rmdex(ps.codePathString, 8128 getDexCodeInstructionSet(getPreferredInstructionSet())); 8129 } 8130 } 8131 } 8132 } 8133 } 8134 8135 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8136 synchronized (mPackages) { 8137 mResolverReplaced = true; 8138 // Set up information for custom user intent resolution activity. 8139 mResolveActivity.applicationInfo = pkg.applicationInfo; 8140 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8141 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8142 mResolveActivity.processName = pkg.applicationInfo.packageName; 8143 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8144 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8145 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8146 mResolveActivity.theme = 0; 8147 mResolveActivity.exported = true; 8148 mResolveActivity.enabled = true; 8149 mResolveInfo.activityInfo = mResolveActivity; 8150 mResolveInfo.priority = 0; 8151 mResolveInfo.preferredOrder = 0; 8152 mResolveInfo.match = 0; 8153 mResolveComponentName = mCustomResolverComponentName; 8154 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8155 mResolveComponentName); 8156 } 8157 } 8158 8159 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8160 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8161 8162 // Set up information for ephemeral installer activity 8163 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8164 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8165 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8166 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8167 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8168 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8169 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8170 mEphemeralInstallerActivity.theme = 0; 8171 mEphemeralInstallerActivity.exported = true; 8172 mEphemeralInstallerActivity.enabled = true; 8173 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8174 mEphemeralInstallerInfo.priority = 0; 8175 mEphemeralInstallerInfo.preferredOrder = 0; 8176 mEphemeralInstallerInfo.match = 0; 8177 8178 if (DEBUG_EPHEMERAL) { 8179 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8180 } 8181 } 8182 8183 private static String calculateBundledApkRoot(final String codePathString) { 8184 final File codePath = new File(codePathString); 8185 final File codeRoot; 8186 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8187 codeRoot = Environment.getRootDirectory(); 8188 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8189 codeRoot = Environment.getOemDirectory(); 8190 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8191 codeRoot = Environment.getVendorDirectory(); 8192 } else { 8193 // Unrecognized code path; take its top real segment as the apk root: 8194 // e.g. /something/app/blah.apk => /something 8195 try { 8196 File f = codePath.getCanonicalFile(); 8197 File parent = f.getParentFile(); // non-null because codePath is a file 8198 File tmp; 8199 while ((tmp = parent.getParentFile()) != null) { 8200 f = parent; 8201 parent = tmp; 8202 } 8203 codeRoot = f; 8204 Slog.w(TAG, "Unrecognized code path " 8205 + codePath + " - using " + codeRoot); 8206 } catch (IOException e) { 8207 // Can't canonicalize the code path -- shenanigans? 8208 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8209 return Environment.getRootDirectory().getPath(); 8210 } 8211 } 8212 return codeRoot.getPath(); 8213 } 8214 8215 /** 8216 * Derive and set the location of native libraries for the given package, 8217 * which varies depending on where and how the package was installed. 8218 */ 8219 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8220 final ApplicationInfo info = pkg.applicationInfo; 8221 final String codePath = pkg.codePath; 8222 final File codeFile = new File(codePath); 8223 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8224 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8225 8226 info.nativeLibraryRootDir = null; 8227 info.nativeLibraryRootRequiresIsa = false; 8228 info.nativeLibraryDir = null; 8229 info.secondaryNativeLibraryDir = null; 8230 8231 if (isApkFile(codeFile)) { 8232 // Monolithic install 8233 if (bundledApp) { 8234 // If "/system/lib64/apkname" exists, assume that is the per-package 8235 // native library directory to use; otherwise use "/system/lib/apkname". 8236 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8237 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8238 getPrimaryInstructionSet(info)); 8239 8240 // This is a bundled system app so choose the path based on the ABI. 8241 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8242 // is just the default path. 8243 final String apkName = deriveCodePathName(codePath); 8244 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8245 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8246 apkName).getAbsolutePath(); 8247 8248 if (info.secondaryCpuAbi != null) { 8249 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8250 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8251 secondaryLibDir, apkName).getAbsolutePath(); 8252 } 8253 } else if (asecApp) { 8254 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8255 .getAbsolutePath(); 8256 } else { 8257 final String apkName = deriveCodePathName(codePath); 8258 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8259 .getAbsolutePath(); 8260 } 8261 8262 info.nativeLibraryRootRequiresIsa = false; 8263 info.nativeLibraryDir = info.nativeLibraryRootDir; 8264 } else { 8265 // Cluster install 8266 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8267 info.nativeLibraryRootRequiresIsa = true; 8268 8269 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8270 getPrimaryInstructionSet(info)).getAbsolutePath(); 8271 8272 if (info.secondaryCpuAbi != null) { 8273 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8274 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8275 } 8276 } 8277 } 8278 8279 /** 8280 * Calculate the abis and roots for a bundled app. These can uniquely 8281 * be determined from the contents of the system partition, i.e whether 8282 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8283 * of this information, and instead assume that the system was built 8284 * sensibly. 8285 */ 8286 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8287 PackageSetting pkgSetting) { 8288 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8289 8290 // If "/system/lib64/apkname" exists, assume that is the per-package 8291 // native library directory to use; otherwise use "/system/lib/apkname". 8292 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8293 setBundledAppAbi(pkg, apkRoot, apkName); 8294 // pkgSetting might be null during rescan following uninstall of updates 8295 // to a bundled app, so accommodate that possibility. The settings in 8296 // that case will be established later from the parsed package. 8297 // 8298 // If the settings aren't null, sync them up with what we've just derived. 8299 // note that apkRoot isn't stored in the package settings. 8300 if (pkgSetting != null) { 8301 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8302 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8303 } 8304 } 8305 8306 /** 8307 * Deduces the ABI of a bundled app and sets the relevant fields on the 8308 * parsed pkg object. 8309 * 8310 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8311 * under which system libraries are installed. 8312 * @param apkName the name of the installed package. 8313 */ 8314 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8315 final File codeFile = new File(pkg.codePath); 8316 8317 final boolean has64BitLibs; 8318 final boolean has32BitLibs; 8319 if (isApkFile(codeFile)) { 8320 // Monolithic install 8321 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8322 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8323 } else { 8324 // Cluster install 8325 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8326 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8327 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8328 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8329 has64BitLibs = (new File(rootDir, isa)).exists(); 8330 } else { 8331 has64BitLibs = false; 8332 } 8333 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8334 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8335 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8336 has32BitLibs = (new File(rootDir, isa)).exists(); 8337 } else { 8338 has32BitLibs = false; 8339 } 8340 } 8341 8342 if (has64BitLibs && !has32BitLibs) { 8343 // The package has 64 bit libs, but not 32 bit libs. Its primary 8344 // ABI should be 64 bit. We can safely assume here that the bundled 8345 // native libraries correspond to the most preferred ABI in the list. 8346 8347 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8348 pkg.applicationInfo.secondaryCpuAbi = null; 8349 } else if (has32BitLibs && !has64BitLibs) { 8350 // The package has 32 bit libs but not 64 bit libs. Its primary 8351 // ABI should be 32 bit. 8352 8353 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8354 pkg.applicationInfo.secondaryCpuAbi = null; 8355 } else if (has32BitLibs && has64BitLibs) { 8356 // The application has both 64 and 32 bit bundled libraries. We check 8357 // here that the app declares multiArch support, and warn if it doesn't. 8358 // 8359 // We will be lenient here and record both ABIs. The primary will be the 8360 // ABI that's higher on the list, i.e, a device that's configured to prefer 8361 // 64 bit apps will see a 64 bit primary ABI, 8362 8363 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8364 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8365 } 8366 8367 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8368 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8369 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8370 } else { 8371 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8372 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8373 } 8374 } else { 8375 pkg.applicationInfo.primaryCpuAbi = null; 8376 pkg.applicationInfo.secondaryCpuAbi = null; 8377 } 8378 } 8379 8380 private void killApplication(String pkgName, int appId, String reason) { 8381 // Request the ActivityManager to kill the process(only for existing packages) 8382 // so that we do not end up in a confused state while the user is still using the older 8383 // version of the application while the new one gets installed. 8384 IActivityManager am = ActivityManagerNative.getDefault(); 8385 if (am != null) { 8386 try { 8387 am.killApplicationWithAppId(pkgName, appId, reason); 8388 } catch (RemoteException e) { 8389 } 8390 } 8391 } 8392 8393 void removePackageLI(PackageSetting ps, boolean chatty) { 8394 if (DEBUG_INSTALL) { 8395 if (chatty) 8396 Log.d(TAG, "Removing package " + ps.name); 8397 } 8398 8399 // writer 8400 synchronized (mPackages) { 8401 mPackages.remove(ps.name); 8402 final PackageParser.Package pkg = ps.pkg; 8403 if (pkg != null) { 8404 cleanPackageDataStructuresLILPw(pkg, chatty); 8405 } 8406 } 8407 } 8408 8409 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8410 if (DEBUG_INSTALL) { 8411 if (chatty) 8412 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8413 } 8414 8415 // writer 8416 synchronized (mPackages) { 8417 mPackages.remove(pkg.applicationInfo.packageName); 8418 cleanPackageDataStructuresLILPw(pkg, chatty); 8419 } 8420 } 8421 8422 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8423 int N = pkg.providers.size(); 8424 StringBuilder r = null; 8425 int i; 8426 for (i=0; i<N; i++) { 8427 PackageParser.Provider p = pkg.providers.get(i); 8428 mProviders.removeProvider(p); 8429 if (p.info.authority == null) { 8430 8431 /* There was another ContentProvider with this authority when 8432 * this app was installed so this authority is null, 8433 * Ignore it as we don't have to unregister the provider. 8434 */ 8435 continue; 8436 } 8437 String names[] = p.info.authority.split(";"); 8438 for (int j = 0; j < names.length; j++) { 8439 if (mProvidersByAuthority.get(names[j]) == p) { 8440 mProvidersByAuthority.remove(names[j]); 8441 if (DEBUG_REMOVE) { 8442 if (chatty) 8443 Log.d(TAG, "Unregistered content provider: " + names[j] 8444 + ", className = " + p.info.name + ", isSyncable = " 8445 + p.info.isSyncable); 8446 } 8447 } 8448 } 8449 if (DEBUG_REMOVE && chatty) { 8450 if (r == null) { 8451 r = new StringBuilder(256); 8452 } else { 8453 r.append(' '); 8454 } 8455 r.append(p.info.name); 8456 } 8457 } 8458 if (r != null) { 8459 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8460 } 8461 8462 N = pkg.services.size(); 8463 r = null; 8464 for (i=0; i<N; i++) { 8465 PackageParser.Service s = pkg.services.get(i); 8466 mServices.removeService(s); 8467 if (chatty) { 8468 if (r == null) { 8469 r = new StringBuilder(256); 8470 } else { 8471 r.append(' '); 8472 } 8473 r.append(s.info.name); 8474 } 8475 } 8476 if (r != null) { 8477 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8478 } 8479 8480 N = pkg.receivers.size(); 8481 r = null; 8482 for (i=0; i<N; i++) { 8483 PackageParser.Activity a = pkg.receivers.get(i); 8484 mReceivers.removeActivity(a, "receiver"); 8485 if (DEBUG_REMOVE && chatty) { 8486 if (r == null) { 8487 r = new StringBuilder(256); 8488 } else { 8489 r.append(' '); 8490 } 8491 r.append(a.info.name); 8492 } 8493 } 8494 if (r != null) { 8495 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8496 } 8497 8498 N = pkg.activities.size(); 8499 r = null; 8500 for (i=0; i<N; i++) { 8501 PackageParser.Activity a = pkg.activities.get(i); 8502 mActivities.removeActivity(a, "activity"); 8503 if (DEBUG_REMOVE && chatty) { 8504 if (r == null) { 8505 r = new StringBuilder(256); 8506 } else { 8507 r.append(' '); 8508 } 8509 r.append(a.info.name); 8510 } 8511 } 8512 if (r != null) { 8513 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8514 } 8515 8516 N = pkg.permissions.size(); 8517 r = null; 8518 for (i=0; i<N; i++) { 8519 PackageParser.Permission p = pkg.permissions.get(i); 8520 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8521 if (bp == null) { 8522 bp = mSettings.mPermissionTrees.get(p.info.name); 8523 } 8524 if (bp != null && bp.perm == p) { 8525 bp.perm = null; 8526 if (DEBUG_REMOVE && chatty) { 8527 if (r == null) { 8528 r = new StringBuilder(256); 8529 } else { 8530 r.append(' '); 8531 } 8532 r.append(p.info.name); 8533 } 8534 } 8535 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8536 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8537 if (appOpPkgs != null) { 8538 appOpPkgs.remove(pkg.packageName); 8539 } 8540 } 8541 } 8542 if (r != null) { 8543 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8544 } 8545 8546 N = pkg.requestedPermissions.size(); 8547 r = null; 8548 for (i=0; i<N; i++) { 8549 String perm = pkg.requestedPermissions.get(i); 8550 BasePermission bp = mSettings.mPermissions.get(perm); 8551 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8552 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8553 if (appOpPkgs != null) { 8554 appOpPkgs.remove(pkg.packageName); 8555 if (appOpPkgs.isEmpty()) { 8556 mAppOpPermissionPackages.remove(perm); 8557 } 8558 } 8559 } 8560 } 8561 if (r != null) { 8562 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8563 } 8564 8565 N = pkg.instrumentation.size(); 8566 r = null; 8567 for (i=0; i<N; i++) { 8568 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8569 mInstrumentation.remove(a.getComponentName()); 8570 if (DEBUG_REMOVE && chatty) { 8571 if (r == null) { 8572 r = new StringBuilder(256); 8573 } else { 8574 r.append(' '); 8575 } 8576 r.append(a.info.name); 8577 } 8578 } 8579 if (r != null) { 8580 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8581 } 8582 8583 r = null; 8584 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8585 // Only system apps can hold shared libraries. 8586 if (pkg.libraryNames != null) { 8587 for (i=0; i<pkg.libraryNames.size(); i++) { 8588 String name = pkg.libraryNames.get(i); 8589 SharedLibraryEntry cur = mSharedLibraries.get(name); 8590 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8591 mSharedLibraries.remove(name); 8592 if (DEBUG_REMOVE && chatty) { 8593 if (r == null) { 8594 r = new StringBuilder(256); 8595 } else { 8596 r.append(' '); 8597 } 8598 r.append(name); 8599 } 8600 } 8601 } 8602 } 8603 } 8604 if (r != null) { 8605 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8606 } 8607 } 8608 8609 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8610 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8611 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8612 return true; 8613 } 8614 } 8615 return false; 8616 } 8617 8618 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8619 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8620 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8621 8622 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8623 int flags) { 8624 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8625 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8626 } 8627 8628 private void updatePermissionsLPw(String changingPkg, 8629 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8630 // Make sure there are no dangling permission trees. 8631 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8632 while (it.hasNext()) { 8633 final BasePermission bp = it.next(); 8634 if (bp.packageSetting == null) { 8635 // We may not yet have parsed the package, so just see if 8636 // we still know about its settings. 8637 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8638 } 8639 if (bp.packageSetting == null) { 8640 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8641 + " from package " + bp.sourcePackage); 8642 it.remove(); 8643 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8644 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8645 Slog.i(TAG, "Removing old permission tree: " + bp.name 8646 + " from package " + bp.sourcePackage); 8647 flags |= UPDATE_PERMISSIONS_ALL; 8648 it.remove(); 8649 } 8650 } 8651 } 8652 8653 // Make sure all dynamic permissions have been assigned to a package, 8654 // and make sure there are no dangling permissions. 8655 it = mSettings.mPermissions.values().iterator(); 8656 while (it.hasNext()) { 8657 final BasePermission bp = it.next(); 8658 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8659 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8660 + bp.name + " pkg=" + bp.sourcePackage 8661 + " info=" + bp.pendingInfo); 8662 if (bp.packageSetting == null && bp.pendingInfo != null) { 8663 final BasePermission tree = findPermissionTreeLP(bp.name); 8664 if (tree != null && tree.perm != null) { 8665 bp.packageSetting = tree.packageSetting; 8666 bp.perm = new PackageParser.Permission(tree.perm.owner, 8667 new PermissionInfo(bp.pendingInfo)); 8668 bp.perm.info.packageName = tree.perm.info.packageName; 8669 bp.perm.info.name = bp.name; 8670 bp.uid = tree.uid; 8671 } 8672 } 8673 } 8674 if (bp.packageSetting == null) { 8675 // We may not yet have parsed the package, so just see if 8676 // we still know about its settings. 8677 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8678 } 8679 if (bp.packageSetting == null) { 8680 Slog.w(TAG, "Removing dangling permission: " + bp.name 8681 + " from package " + bp.sourcePackage); 8682 it.remove(); 8683 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8684 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8685 Slog.i(TAG, "Removing old permission: " + bp.name 8686 + " from package " + bp.sourcePackage); 8687 flags |= UPDATE_PERMISSIONS_ALL; 8688 it.remove(); 8689 } 8690 } 8691 } 8692 8693 // Now update the permissions for all packages, in particular 8694 // replace the granted permissions of the system packages. 8695 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8696 for (PackageParser.Package pkg : mPackages.values()) { 8697 if (pkg != pkgInfo) { 8698 // Only replace for packages on requested volume 8699 final String volumeUuid = getVolumeUuidForPackage(pkg); 8700 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8701 && Objects.equals(replaceVolumeUuid, volumeUuid); 8702 grantPermissionsLPw(pkg, replace, changingPkg); 8703 } 8704 } 8705 } 8706 8707 if (pkgInfo != null) { 8708 // Only replace for packages on requested volume 8709 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8710 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8711 && Objects.equals(replaceVolumeUuid, volumeUuid); 8712 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8713 } 8714 } 8715 8716 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8717 String packageOfInterest) { 8718 // IMPORTANT: There are two types of permissions: install and runtime. 8719 // Install time permissions are granted when the app is installed to 8720 // all device users and users added in the future. Runtime permissions 8721 // are granted at runtime explicitly to specific users. Normal and signature 8722 // protected permissions are install time permissions. Dangerous permissions 8723 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8724 // otherwise they are runtime permissions. This function does not manage 8725 // runtime permissions except for the case an app targeting Lollipop MR1 8726 // being upgraded to target a newer SDK, in which case dangerous permissions 8727 // are transformed from install time to runtime ones. 8728 8729 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8730 if (ps == null) { 8731 return; 8732 } 8733 8734 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8735 8736 PermissionsState permissionsState = ps.getPermissionsState(); 8737 PermissionsState origPermissions = permissionsState; 8738 8739 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8740 8741 boolean runtimePermissionsRevoked = false; 8742 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8743 8744 boolean changedInstallPermission = false; 8745 8746 if (replace) { 8747 ps.installPermissionsFixed = false; 8748 if (!ps.isSharedUser()) { 8749 origPermissions = new PermissionsState(permissionsState); 8750 permissionsState.reset(); 8751 } else { 8752 // We need to know only about runtime permission changes since the 8753 // calling code always writes the install permissions state but 8754 // the runtime ones are written only if changed. The only cases of 8755 // changed runtime permissions here are promotion of an install to 8756 // runtime and revocation of a runtime from a shared user. 8757 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8758 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8759 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8760 runtimePermissionsRevoked = true; 8761 } 8762 } 8763 } 8764 8765 permissionsState.setGlobalGids(mGlobalGids); 8766 8767 final int N = pkg.requestedPermissions.size(); 8768 for (int i=0; i<N; i++) { 8769 final String name = pkg.requestedPermissions.get(i); 8770 final BasePermission bp = mSettings.mPermissions.get(name); 8771 8772 if (DEBUG_INSTALL) { 8773 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8774 } 8775 8776 if (bp == null || bp.packageSetting == null) { 8777 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8778 Slog.w(TAG, "Unknown permission " + name 8779 + " in package " + pkg.packageName); 8780 } 8781 continue; 8782 } 8783 8784 final String perm = bp.name; 8785 boolean allowedSig = false; 8786 int grant = GRANT_DENIED; 8787 8788 // Keep track of app op permissions. 8789 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8790 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8791 if (pkgs == null) { 8792 pkgs = new ArraySet<>(); 8793 mAppOpPermissionPackages.put(bp.name, pkgs); 8794 } 8795 pkgs.add(pkg.packageName); 8796 } 8797 8798 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8799 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8800 >= Build.VERSION_CODES.M; 8801 switch (level) { 8802 case PermissionInfo.PROTECTION_NORMAL: { 8803 // For all apps normal permissions are install time ones. 8804 grant = GRANT_INSTALL; 8805 } break; 8806 8807 case PermissionInfo.PROTECTION_DANGEROUS: { 8808 // If a permission review is required for legacy apps we represent 8809 // their permissions as always granted runtime ones since we need 8810 // to keep the review required permission flag per user while an 8811 // install permission's state is shared across all users. 8812 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8813 // For legacy apps dangerous permissions are install time ones. 8814 grant = GRANT_INSTALL; 8815 } else if (origPermissions.hasInstallPermission(bp.name)) { 8816 // For legacy apps that became modern, install becomes runtime. 8817 grant = GRANT_UPGRADE; 8818 } else if (mPromoteSystemApps 8819 && isSystemApp(ps) 8820 && mExistingSystemPackages.contains(ps.name)) { 8821 // For legacy system apps, install becomes runtime. 8822 // We cannot check hasInstallPermission() for system apps since those 8823 // permissions were granted implicitly and not persisted pre-M. 8824 grant = GRANT_UPGRADE; 8825 } else { 8826 // For modern apps keep runtime permissions unchanged. 8827 grant = GRANT_RUNTIME; 8828 } 8829 } break; 8830 8831 case PermissionInfo.PROTECTION_SIGNATURE: { 8832 // For all apps signature permissions are install time ones. 8833 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8834 if (allowedSig) { 8835 grant = GRANT_INSTALL; 8836 } 8837 } break; 8838 } 8839 8840 if (DEBUG_INSTALL) { 8841 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8842 } 8843 8844 if (grant != GRANT_DENIED) { 8845 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8846 // If this is an existing, non-system package, then 8847 // we can't add any new permissions to it. 8848 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8849 // Except... if this is a permission that was added 8850 // to the platform (note: need to only do this when 8851 // updating the platform). 8852 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8853 grant = GRANT_DENIED; 8854 } 8855 } 8856 } 8857 8858 switch (grant) { 8859 case GRANT_INSTALL: { 8860 // Revoke this as runtime permission to handle the case of 8861 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8862 for (int userId : UserManagerService.getInstance().getUserIds()) { 8863 if (origPermissions.getRuntimePermissionState( 8864 bp.name, userId) != null) { 8865 // Revoke the runtime permission and clear the flags. 8866 origPermissions.revokeRuntimePermission(bp, userId); 8867 origPermissions.updatePermissionFlags(bp, userId, 8868 PackageManager.MASK_PERMISSION_FLAGS, 0); 8869 // If we revoked a permission permission, we have to write. 8870 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8871 changedRuntimePermissionUserIds, userId); 8872 } 8873 } 8874 // Grant an install permission. 8875 if (permissionsState.grantInstallPermission(bp) != 8876 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8877 changedInstallPermission = true; 8878 } 8879 } break; 8880 8881 case GRANT_RUNTIME: { 8882 // Grant previously granted runtime permissions. 8883 for (int userId : UserManagerService.getInstance().getUserIds()) { 8884 PermissionState permissionState = origPermissions 8885 .getRuntimePermissionState(bp.name, userId); 8886 int flags = permissionState != null 8887 ? permissionState.getFlags() : 0; 8888 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8889 if (permissionsState.grantRuntimePermission(bp, userId) == 8890 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8891 // If we cannot put the permission as it was, we have to write. 8892 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8893 changedRuntimePermissionUserIds, userId); 8894 } 8895 // If the app supports runtime permissions no need for a review. 8896 if (Build.PERMISSIONS_REVIEW_REQUIRED 8897 && appSupportsRuntimePermissions 8898 && (flags & PackageManager 8899 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8900 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8901 // Since we changed the flags, we have to write. 8902 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8903 changedRuntimePermissionUserIds, userId); 8904 } 8905 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8906 && !appSupportsRuntimePermissions) { 8907 // For legacy apps that need a permission review, every new 8908 // runtime permission is granted but it is pending a review. 8909 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8910 permissionsState.grantRuntimePermission(bp, userId); 8911 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8912 // We changed the permission and flags, hence have to write. 8913 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8914 changedRuntimePermissionUserIds, userId); 8915 } 8916 } 8917 // Propagate the permission flags. 8918 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8919 } 8920 } break; 8921 8922 case GRANT_UPGRADE: { 8923 // Grant runtime permissions for a previously held install permission. 8924 PermissionState permissionState = origPermissions 8925 .getInstallPermissionState(bp.name); 8926 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8927 8928 if (origPermissions.revokeInstallPermission(bp) 8929 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8930 // We will be transferring the permission flags, so clear them. 8931 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8932 PackageManager.MASK_PERMISSION_FLAGS, 0); 8933 changedInstallPermission = true; 8934 } 8935 8936 // If the permission is not to be promoted to runtime we ignore it and 8937 // also its other flags as they are not applicable to install permissions. 8938 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8939 for (int userId : currentUserIds) { 8940 if (permissionsState.grantRuntimePermission(bp, userId) != 8941 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8942 // Transfer the permission flags. 8943 permissionsState.updatePermissionFlags(bp, userId, 8944 flags, flags); 8945 // If we granted the permission, we have to write. 8946 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8947 changedRuntimePermissionUserIds, userId); 8948 } 8949 } 8950 } 8951 } break; 8952 8953 default: { 8954 if (packageOfInterest == null 8955 || packageOfInterest.equals(pkg.packageName)) { 8956 Slog.w(TAG, "Not granting permission " + perm 8957 + " to package " + pkg.packageName 8958 + " because it was previously installed without"); 8959 } 8960 } break; 8961 } 8962 } else { 8963 if (permissionsState.revokeInstallPermission(bp) != 8964 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8965 // Also drop the permission flags. 8966 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8967 PackageManager.MASK_PERMISSION_FLAGS, 0); 8968 changedInstallPermission = true; 8969 Slog.i(TAG, "Un-granting permission " + perm 8970 + " from package " + pkg.packageName 8971 + " (protectionLevel=" + bp.protectionLevel 8972 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8973 + ")"); 8974 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8975 // Don't print warning for app op permissions, since it is fine for them 8976 // not to be granted, there is a UI for the user to decide. 8977 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8978 Slog.w(TAG, "Not granting permission " + perm 8979 + " to package " + pkg.packageName 8980 + " (protectionLevel=" + bp.protectionLevel 8981 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8982 + ")"); 8983 } 8984 } 8985 } 8986 } 8987 8988 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8989 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8990 // This is the first that we have heard about this package, so the 8991 // permissions we have now selected are fixed until explicitly 8992 // changed. 8993 ps.installPermissionsFixed = true; 8994 } 8995 8996 // Persist the runtime permissions state for users with changes. If permissions 8997 // were revoked because no app in the shared user declares them we have to 8998 // write synchronously to avoid losing runtime permissions state. 8999 for (int userId : changedRuntimePermissionUserIds) { 9000 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9001 } 9002 9003 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9004 } 9005 9006 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9007 boolean allowed = false; 9008 final int NP = PackageParser.NEW_PERMISSIONS.length; 9009 for (int ip=0; ip<NP; ip++) { 9010 final PackageParser.NewPermissionInfo npi 9011 = PackageParser.NEW_PERMISSIONS[ip]; 9012 if (npi.name.equals(perm) 9013 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9014 allowed = true; 9015 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9016 + pkg.packageName); 9017 break; 9018 } 9019 } 9020 return allowed; 9021 } 9022 9023 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9024 BasePermission bp, PermissionsState origPermissions) { 9025 boolean allowed; 9026 allowed = (compareSignatures( 9027 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9028 == PackageManager.SIGNATURE_MATCH) 9029 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9030 == PackageManager.SIGNATURE_MATCH); 9031 if (!allowed && (bp.protectionLevel 9032 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9033 if (isSystemApp(pkg)) { 9034 // For updated system applications, a system permission 9035 // is granted only if it had been defined by the original application. 9036 if (pkg.isUpdatedSystemApp()) { 9037 final PackageSetting sysPs = mSettings 9038 .getDisabledSystemPkgLPr(pkg.packageName); 9039 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9040 // If the original was granted this permission, we take 9041 // that grant decision as read and propagate it to the 9042 // update. 9043 if (sysPs.isPrivileged()) { 9044 allowed = true; 9045 } 9046 } else { 9047 // The system apk may have been updated with an older 9048 // version of the one on the data partition, but which 9049 // granted a new system permission that it didn't have 9050 // before. In this case we do want to allow the app to 9051 // now get the new permission if the ancestral apk is 9052 // privileged to get it. 9053 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9054 for (int j=0; 9055 j<sysPs.pkg.requestedPermissions.size(); j++) { 9056 if (perm.equals( 9057 sysPs.pkg.requestedPermissions.get(j))) { 9058 allowed = true; 9059 break; 9060 } 9061 } 9062 } 9063 } 9064 } else { 9065 allowed = isPrivilegedApp(pkg); 9066 } 9067 } 9068 } 9069 if (!allowed) { 9070 if (!allowed && (bp.protectionLevel 9071 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9072 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9073 // If this was a previously normal/dangerous permission that got moved 9074 // to a system permission as part of the runtime permission redesign, then 9075 // we still want to blindly grant it to old apps. 9076 allowed = true; 9077 } 9078 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9079 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9080 // If this permission is to be granted to the system installer and 9081 // this app is an installer, then it gets the permission. 9082 allowed = true; 9083 } 9084 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9085 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9086 // If this permission is to be granted to the system verifier and 9087 // this app is a verifier, then it gets the permission. 9088 allowed = true; 9089 } 9090 if (!allowed && (bp.protectionLevel 9091 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9092 && isSystemApp(pkg)) { 9093 // Any pre-installed system app is allowed to get this permission. 9094 allowed = true; 9095 } 9096 if (!allowed && (bp.protectionLevel 9097 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9098 // For development permissions, a development permission 9099 // is granted only if it was already granted. 9100 allowed = origPermissions.hasInstallPermission(perm); 9101 } 9102 } 9103 return allowed; 9104 } 9105 9106 final class ActivityIntentResolver 9107 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9108 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9109 boolean defaultOnly, int userId) { 9110 if (!sUserManager.exists(userId)) return null; 9111 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9112 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9113 } 9114 9115 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9116 int userId) { 9117 if (!sUserManager.exists(userId)) return null; 9118 mFlags = flags; 9119 return super.queryIntent(intent, resolvedType, 9120 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9121 } 9122 9123 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9124 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9125 if (!sUserManager.exists(userId)) return null; 9126 if (packageActivities == null) { 9127 return null; 9128 } 9129 mFlags = flags; 9130 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9131 final int N = packageActivities.size(); 9132 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9133 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9134 9135 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9136 for (int i = 0; i < N; ++i) { 9137 intentFilters = packageActivities.get(i).intents; 9138 if (intentFilters != null && intentFilters.size() > 0) { 9139 PackageParser.ActivityIntentInfo[] array = 9140 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9141 intentFilters.toArray(array); 9142 listCut.add(array); 9143 } 9144 } 9145 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9146 } 9147 9148 public final void addActivity(PackageParser.Activity a, String type) { 9149 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9150 mActivities.put(a.getComponentName(), a); 9151 if (DEBUG_SHOW_INFO) 9152 Log.v( 9153 TAG, " " + type + " " + 9154 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9155 if (DEBUG_SHOW_INFO) 9156 Log.v(TAG, " Class=" + a.info.name); 9157 final int NI = a.intents.size(); 9158 for (int j=0; j<NI; j++) { 9159 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9160 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9161 intent.setPriority(0); 9162 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9163 + a.className + " with priority > 0, forcing to 0"); 9164 } 9165 if (DEBUG_SHOW_INFO) { 9166 Log.v(TAG, " IntentFilter:"); 9167 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9168 } 9169 if (!intent.debugCheck()) { 9170 Log.w(TAG, "==> For Activity " + a.info.name); 9171 } 9172 addFilter(intent); 9173 } 9174 } 9175 9176 public final void removeActivity(PackageParser.Activity a, String type) { 9177 mActivities.remove(a.getComponentName()); 9178 if (DEBUG_SHOW_INFO) { 9179 Log.v(TAG, " " + type + " " 9180 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9181 : a.info.name) + ":"); 9182 Log.v(TAG, " Class=" + a.info.name); 9183 } 9184 final int NI = a.intents.size(); 9185 for (int j=0; j<NI; j++) { 9186 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9187 if (DEBUG_SHOW_INFO) { 9188 Log.v(TAG, " IntentFilter:"); 9189 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9190 } 9191 removeFilter(intent); 9192 } 9193 } 9194 9195 @Override 9196 protected boolean allowFilterResult( 9197 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9198 ActivityInfo filterAi = filter.activity.info; 9199 for (int i=dest.size()-1; i>=0; i--) { 9200 ActivityInfo destAi = dest.get(i).activityInfo; 9201 if (destAi.name == filterAi.name 9202 && destAi.packageName == filterAi.packageName) { 9203 return false; 9204 } 9205 } 9206 return true; 9207 } 9208 9209 @Override 9210 protected ActivityIntentInfo[] newArray(int size) { 9211 return new ActivityIntentInfo[size]; 9212 } 9213 9214 @Override 9215 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9216 if (!sUserManager.exists(userId)) return true; 9217 PackageParser.Package p = filter.activity.owner; 9218 if (p != null) { 9219 PackageSetting ps = (PackageSetting)p.mExtras; 9220 if (ps != null) { 9221 // System apps are never considered stopped for purposes of 9222 // filtering, because there may be no way for the user to 9223 // actually re-launch them. 9224 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9225 && ps.getStopped(userId); 9226 } 9227 } 9228 return false; 9229 } 9230 9231 @Override 9232 protected boolean isPackageForFilter(String packageName, 9233 PackageParser.ActivityIntentInfo info) { 9234 return packageName.equals(info.activity.owner.packageName); 9235 } 9236 9237 @Override 9238 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9239 int match, int userId) { 9240 if (!sUserManager.exists(userId)) return null; 9241 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9242 return null; 9243 } 9244 final PackageParser.Activity activity = info.activity; 9245 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9246 if (ps == null) { 9247 return null; 9248 } 9249 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9250 ps.readUserState(userId), userId); 9251 if (ai == null) { 9252 return null; 9253 } 9254 final ResolveInfo res = new ResolveInfo(); 9255 res.activityInfo = ai; 9256 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9257 res.filter = info; 9258 } 9259 if (info != null) { 9260 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9261 } 9262 res.priority = info.getPriority(); 9263 res.preferredOrder = activity.owner.mPreferredOrder; 9264 //System.out.println("Result: " + res.activityInfo.className + 9265 // " = " + res.priority); 9266 res.match = match; 9267 res.isDefault = info.hasDefault; 9268 res.labelRes = info.labelRes; 9269 res.nonLocalizedLabel = info.nonLocalizedLabel; 9270 if (userNeedsBadging(userId)) { 9271 res.noResourceId = true; 9272 } else { 9273 res.icon = info.icon; 9274 } 9275 res.iconResourceId = info.icon; 9276 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9277 return res; 9278 } 9279 9280 @Override 9281 protected void sortResults(List<ResolveInfo> results) { 9282 Collections.sort(results, mResolvePrioritySorter); 9283 } 9284 9285 @Override 9286 protected void dumpFilter(PrintWriter out, String prefix, 9287 PackageParser.ActivityIntentInfo filter) { 9288 out.print(prefix); out.print( 9289 Integer.toHexString(System.identityHashCode(filter.activity))); 9290 out.print(' '); 9291 filter.activity.printComponentShortName(out); 9292 out.print(" filter "); 9293 out.println(Integer.toHexString(System.identityHashCode(filter))); 9294 } 9295 9296 @Override 9297 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9298 return filter.activity; 9299 } 9300 9301 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9302 PackageParser.Activity activity = (PackageParser.Activity)label; 9303 out.print(prefix); out.print( 9304 Integer.toHexString(System.identityHashCode(activity))); 9305 out.print(' '); 9306 activity.printComponentShortName(out); 9307 if (count > 1) { 9308 out.print(" ("); out.print(count); out.print(" filters)"); 9309 } 9310 out.println(); 9311 } 9312 9313// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9314// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9315// final List<ResolveInfo> retList = Lists.newArrayList(); 9316// while (i.hasNext()) { 9317// final ResolveInfo resolveInfo = i.next(); 9318// if (isEnabledLP(resolveInfo.activityInfo)) { 9319// retList.add(resolveInfo); 9320// } 9321// } 9322// return retList; 9323// } 9324 9325 // Keys are String (activity class name), values are Activity. 9326 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9327 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9328 private int mFlags; 9329 } 9330 9331 private final class ServiceIntentResolver 9332 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9333 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9334 boolean defaultOnly, int userId) { 9335 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9336 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9337 } 9338 9339 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9340 int userId) { 9341 if (!sUserManager.exists(userId)) return null; 9342 mFlags = flags; 9343 return super.queryIntent(intent, resolvedType, 9344 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9345 } 9346 9347 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9348 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9349 if (!sUserManager.exists(userId)) return null; 9350 if (packageServices == null) { 9351 return null; 9352 } 9353 mFlags = flags; 9354 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9355 final int N = packageServices.size(); 9356 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9357 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9358 9359 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9360 for (int i = 0; i < N; ++i) { 9361 intentFilters = packageServices.get(i).intents; 9362 if (intentFilters != null && intentFilters.size() > 0) { 9363 PackageParser.ServiceIntentInfo[] array = 9364 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9365 intentFilters.toArray(array); 9366 listCut.add(array); 9367 } 9368 } 9369 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9370 } 9371 9372 public final void addService(PackageParser.Service s) { 9373 mServices.put(s.getComponentName(), s); 9374 if (DEBUG_SHOW_INFO) { 9375 Log.v(TAG, " " 9376 + (s.info.nonLocalizedLabel != null 9377 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9378 Log.v(TAG, " Class=" + s.info.name); 9379 } 9380 final int NI = s.intents.size(); 9381 int j; 9382 for (j=0; j<NI; j++) { 9383 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9384 if (DEBUG_SHOW_INFO) { 9385 Log.v(TAG, " IntentFilter:"); 9386 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9387 } 9388 if (!intent.debugCheck()) { 9389 Log.w(TAG, "==> For Service " + s.info.name); 9390 } 9391 addFilter(intent); 9392 } 9393 } 9394 9395 public final void removeService(PackageParser.Service s) { 9396 mServices.remove(s.getComponentName()); 9397 if (DEBUG_SHOW_INFO) { 9398 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9399 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9400 Log.v(TAG, " Class=" + s.info.name); 9401 } 9402 final int NI = s.intents.size(); 9403 int j; 9404 for (j=0; j<NI; j++) { 9405 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9406 if (DEBUG_SHOW_INFO) { 9407 Log.v(TAG, " IntentFilter:"); 9408 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9409 } 9410 removeFilter(intent); 9411 } 9412 } 9413 9414 @Override 9415 protected boolean allowFilterResult( 9416 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9417 ServiceInfo filterSi = filter.service.info; 9418 for (int i=dest.size()-1; i>=0; i--) { 9419 ServiceInfo destAi = dest.get(i).serviceInfo; 9420 if (destAi.name == filterSi.name 9421 && destAi.packageName == filterSi.packageName) { 9422 return false; 9423 } 9424 } 9425 return true; 9426 } 9427 9428 @Override 9429 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9430 return new PackageParser.ServiceIntentInfo[size]; 9431 } 9432 9433 @Override 9434 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9435 if (!sUserManager.exists(userId)) return true; 9436 PackageParser.Package p = filter.service.owner; 9437 if (p != null) { 9438 PackageSetting ps = (PackageSetting)p.mExtras; 9439 if (ps != null) { 9440 // System apps are never considered stopped for purposes of 9441 // filtering, because there may be no way for the user to 9442 // actually re-launch them. 9443 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9444 && ps.getStopped(userId); 9445 } 9446 } 9447 return false; 9448 } 9449 9450 @Override 9451 protected boolean isPackageForFilter(String packageName, 9452 PackageParser.ServiceIntentInfo info) { 9453 return packageName.equals(info.service.owner.packageName); 9454 } 9455 9456 @Override 9457 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9458 int match, int userId) { 9459 if (!sUserManager.exists(userId)) return null; 9460 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9461 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9462 return null; 9463 } 9464 final PackageParser.Service service = info.service; 9465 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9466 if (ps == null) { 9467 return null; 9468 } 9469 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9470 ps.readUserState(userId), userId); 9471 if (si == null) { 9472 return null; 9473 } 9474 final ResolveInfo res = new ResolveInfo(); 9475 res.serviceInfo = si; 9476 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9477 res.filter = filter; 9478 } 9479 res.priority = info.getPriority(); 9480 res.preferredOrder = service.owner.mPreferredOrder; 9481 res.match = match; 9482 res.isDefault = info.hasDefault; 9483 res.labelRes = info.labelRes; 9484 res.nonLocalizedLabel = info.nonLocalizedLabel; 9485 res.icon = info.icon; 9486 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9487 return res; 9488 } 9489 9490 @Override 9491 protected void sortResults(List<ResolveInfo> results) { 9492 Collections.sort(results, mResolvePrioritySorter); 9493 } 9494 9495 @Override 9496 protected void dumpFilter(PrintWriter out, String prefix, 9497 PackageParser.ServiceIntentInfo filter) { 9498 out.print(prefix); out.print( 9499 Integer.toHexString(System.identityHashCode(filter.service))); 9500 out.print(' '); 9501 filter.service.printComponentShortName(out); 9502 out.print(" filter "); 9503 out.println(Integer.toHexString(System.identityHashCode(filter))); 9504 } 9505 9506 @Override 9507 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9508 return filter.service; 9509 } 9510 9511 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9512 PackageParser.Service service = (PackageParser.Service)label; 9513 out.print(prefix); out.print( 9514 Integer.toHexString(System.identityHashCode(service))); 9515 out.print(' '); 9516 service.printComponentShortName(out); 9517 if (count > 1) { 9518 out.print(" ("); out.print(count); out.print(" filters)"); 9519 } 9520 out.println(); 9521 } 9522 9523// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9524// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9525// final List<ResolveInfo> retList = Lists.newArrayList(); 9526// while (i.hasNext()) { 9527// final ResolveInfo resolveInfo = (ResolveInfo) i; 9528// if (isEnabledLP(resolveInfo.serviceInfo)) { 9529// retList.add(resolveInfo); 9530// } 9531// } 9532// return retList; 9533// } 9534 9535 // Keys are String (activity class name), values are Activity. 9536 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9537 = new ArrayMap<ComponentName, PackageParser.Service>(); 9538 private int mFlags; 9539 }; 9540 9541 private final class ProviderIntentResolver 9542 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9543 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9544 boolean defaultOnly, int userId) { 9545 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9546 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9547 } 9548 9549 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9550 int userId) { 9551 if (!sUserManager.exists(userId)) 9552 return null; 9553 mFlags = flags; 9554 return super.queryIntent(intent, resolvedType, 9555 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9556 } 9557 9558 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9559 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9560 if (!sUserManager.exists(userId)) 9561 return null; 9562 if (packageProviders == null) { 9563 return null; 9564 } 9565 mFlags = flags; 9566 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9567 final int N = packageProviders.size(); 9568 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9569 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9570 9571 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9572 for (int i = 0; i < N; ++i) { 9573 intentFilters = packageProviders.get(i).intents; 9574 if (intentFilters != null && intentFilters.size() > 0) { 9575 PackageParser.ProviderIntentInfo[] array = 9576 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9577 intentFilters.toArray(array); 9578 listCut.add(array); 9579 } 9580 } 9581 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9582 } 9583 9584 public final void addProvider(PackageParser.Provider p) { 9585 if (mProviders.containsKey(p.getComponentName())) { 9586 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9587 return; 9588 } 9589 9590 mProviders.put(p.getComponentName(), p); 9591 if (DEBUG_SHOW_INFO) { 9592 Log.v(TAG, " " 9593 + (p.info.nonLocalizedLabel != null 9594 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9595 Log.v(TAG, " Class=" + p.info.name); 9596 } 9597 final int NI = p.intents.size(); 9598 int j; 9599 for (j = 0; j < NI; j++) { 9600 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9601 if (DEBUG_SHOW_INFO) { 9602 Log.v(TAG, " IntentFilter:"); 9603 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9604 } 9605 if (!intent.debugCheck()) { 9606 Log.w(TAG, "==> For Provider " + p.info.name); 9607 } 9608 addFilter(intent); 9609 } 9610 } 9611 9612 public final void removeProvider(PackageParser.Provider p) { 9613 mProviders.remove(p.getComponentName()); 9614 if (DEBUG_SHOW_INFO) { 9615 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9616 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9617 Log.v(TAG, " Class=" + p.info.name); 9618 } 9619 final int NI = p.intents.size(); 9620 int j; 9621 for (j = 0; j < NI; j++) { 9622 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9623 if (DEBUG_SHOW_INFO) { 9624 Log.v(TAG, " IntentFilter:"); 9625 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9626 } 9627 removeFilter(intent); 9628 } 9629 } 9630 9631 @Override 9632 protected boolean allowFilterResult( 9633 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9634 ProviderInfo filterPi = filter.provider.info; 9635 for (int i = dest.size() - 1; i >= 0; i--) { 9636 ProviderInfo destPi = dest.get(i).providerInfo; 9637 if (destPi.name == filterPi.name 9638 && destPi.packageName == filterPi.packageName) { 9639 return false; 9640 } 9641 } 9642 return true; 9643 } 9644 9645 @Override 9646 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9647 return new PackageParser.ProviderIntentInfo[size]; 9648 } 9649 9650 @Override 9651 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9652 if (!sUserManager.exists(userId)) 9653 return true; 9654 PackageParser.Package p = filter.provider.owner; 9655 if (p != null) { 9656 PackageSetting ps = (PackageSetting) p.mExtras; 9657 if (ps != null) { 9658 // System apps are never considered stopped for purposes of 9659 // filtering, because there may be no way for the user to 9660 // actually re-launch them. 9661 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9662 && ps.getStopped(userId); 9663 } 9664 } 9665 return false; 9666 } 9667 9668 @Override 9669 protected boolean isPackageForFilter(String packageName, 9670 PackageParser.ProviderIntentInfo info) { 9671 return packageName.equals(info.provider.owner.packageName); 9672 } 9673 9674 @Override 9675 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9676 int match, int userId) { 9677 if (!sUserManager.exists(userId)) 9678 return null; 9679 final PackageParser.ProviderIntentInfo info = filter; 9680 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9681 return null; 9682 } 9683 final PackageParser.Provider provider = info.provider; 9684 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9685 if (ps == null) { 9686 return null; 9687 } 9688 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9689 ps.readUserState(userId), userId); 9690 if (pi == null) { 9691 return null; 9692 } 9693 final ResolveInfo res = new ResolveInfo(); 9694 res.providerInfo = pi; 9695 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9696 res.filter = filter; 9697 } 9698 res.priority = info.getPriority(); 9699 res.preferredOrder = provider.owner.mPreferredOrder; 9700 res.match = match; 9701 res.isDefault = info.hasDefault; 9702 res.labelRes = info.labelRes; 9703 res.nonLocalizedLabel = info.nonLocalizedLabel; 9704 res.icon = info.icon; 9705 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9706 return res; 9707 } 9708 9709 @Override 9710 protected void sortResults(List<ResolveInfo> results) { 9711 Collections.sort(results, mResolvePrioritySorter); 9712 } 9713 9714 @Override 9715 protected void dumpFilter(PrintWriter out, String prefix, 9716 PackageParser.ProviderIntentInfo filter) { 9717 out.print(prefix); 9718 out.print( 9719 Integer.toHexString(System.identityHashCode(filter.provider))); 9720 out.print(' '); 9721 filter.provider.printComponentShortName(out); 9722 out.print(" filter "); 9723 out.println(Integer.toHexString(System.identityHashCode(filter))); 9724 } 9725 9726 @Override 9727 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9728 return filter.provider; 9729 } 9730 9731 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9732 PackageParser.Provider provider = (PackageParser.Provider)label; 9733 out.print(prefix); out.print( 9734 Integer.toHexString(System.identityHashCode(provider))); 9735 out.print(' '); 9736 provider.printComponentShortName(out); 9737 if (count > 1) { 9738 out.print(" ("); out.print(count); out.print(" filters)"); 9739 } 9740 out.println(); 9741 } 9742 9743 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9744 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9745 private int mFlags; 9746 } 9747 9748 private static final class EphemeralIntentResolver 9749 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9750 @Override 9751 protected EphemeralResolveIntentInfo[] newArray(int size) { 9752 return new EphemeralResolveIntentInfo[size]; 9753 } 9754 9755 @Override 9756 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9757 return true; 9758 } 9759 9760 @Override 9761 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9762 int userId) { 9763 if (!sUserManager.exists(userId)) { 9764 return null; 9765 } 9766 return info.getEphemeralResolveInfo(); 9767 } 9768 } 9769 9770 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9771 new Comparator<ResolveInfo>() { 9772 public int compare(ResolveInfo r1, ResolveInfo r2) { 9773 int v1 = r1.priority; 9774 int v2 = r2.priority; 9775 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9776 if (v1 != v2) { 9777 return (v1 > v2) ? -1 : 1; 9778 } 9779 v1 = r1.preferredOrder; 9780 v2 = r2.preferredOrder; 9781 if (v1 != v2) { 9782 return (v1 > v2) ? -1 : 1; 9783 } 9784 if (r1.isDefault != r2.isDefault) { 9785 return r1.isDefault ? -1 : 1; 9786 } 9787 v1 = r1.match; 9788 v2 = r2.match; 9789 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9790 if (v1 != v2) { 9791 return (v1 > v2) ? -1 : 1; 9792 } 9793 if (r1.system != r2.system) { 9794 return r1.system ? -1 : 1; 9795 } 9796 if (r1.activityInfo != null) { 9797 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9798 } 9799 if (r1.serviceInfo != null) { 9800 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9801 } 9802 if (r1.providerInfo != null) { 9803 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9804 } 9805 return 0; 9806 } 9807 }; 9808 9809 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9810 new Comparator<ProviderInfo>() { 9811 public int compare(ProviderInfo p1, ProviderInfo p2) { 9812 final int v1 = p1.initOrder; 9813 final int v2 = p2.initOrder; 9814 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9815 } 9816 }; 9817 9818 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9819 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9820 final int[] userIds) { 9821 mHandler.post(new Runnable() { 9822 @Override 9823 public void run() { 9824 try { 9825 final IActivityManager am = ActivityManagerNative.getDefault(); 9826 if (am == null) return; 9827 final int[] resolvedUserIds; 9828 if (userIds == null) { 9829 resolvedUserIds = am.getRunningUserIds(); 9830 } else { 9831 resolvedUserIds = userIds; 9832 } 9833 for (int id : resolvedUserIds) { 9834 final Intent intent = new Intent(action, 9835 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9836 if (extras != null) { 9837 intent.putExtras(extras); 9838 } 9839 if (targetPkg != null) { 9840 intent.setPackage(targetPkg); 9841 } 9842 // Modify the UID when posting to other users 9843 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9844 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9845 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9846 intent.putExtra(Intent.EXTRA_UID, uid); 9847 } 9848 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9849 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9850 if (DEBUG_BROADCASTS) { 9851 RuntimeException here = new RuntimeException("here"); 9852 here.fillInStackTrace(); 9853 Slog.d(TAG, "Sending to user " + id + ": " 9854 + intent.toShortString(false, true, false, false) 9855 + " " + intent.getExtras(), here); 9856 } 9857 am.broadcastIntent(null, intent, null, finishedReceiver, 9858 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9859 null, finishedReceiver != null, false, id); 9860 } 9861 } catch (RemoteException ex) { 9862 } 9863 } 9864 }); 9865 } 9866 9867 /** 9868 * Check if the external storage media is available. This is true if there 9869 * is a mounted external storage medium or if the external storage is 9870 * emulated. 9871 */ 9872 private boolean isExternalMediaAvailable() { 9873 return mMediaMounted || Environment.isExternalStorageEmulated(); 9874 } 9875 9876 @Override 9877 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9878 // writer 9879 synchronized (mPackages) { 9880 if (!isExternalMediaAvailable()) { 9881 // If the external storage is no longer mounted at this point, 9882 // the caller may not have been able to delete all of this 9883 // packages files and can not delete any more. Bail. 9884 return null; 9885 } 9886 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9887 if (lastPackage != null) { 9888 pkgs.remove(lastPackage); 9889 } 9890 if (pkgs.size() > 0) { 9891 return pkgs.get(0); 9892 } 9893 } 9894 return null; 9895 } 9896 9897 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9898 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9899 userId, andCode ? 1 : 0, packageName); 9900 if (mSystemReady) { 9901 msg.sendToTarget(); 9902 } else { 9903 if (mPostSystemReadyMessages == null) { 9904 mPostSystemReadyMessages = new ArrayList<>(); 9905 } 9906 mPostSystemReadyMessages.add(msg); 9907 } 9908 } 9909 9910 void startCleaningPackages() { 9911 // reader 9912 synchronized (mPackages) { 9913 if (!isExternalMediaAvailable()) { 9914 return; 9915 } 9916 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9917 return; 9918 } 9919 } 9920 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9921 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9922 IActivityManager am = ActivityManagerNative.getDefault(); 9923 if (am != null) { 9924 try { 9925 am.startService(null, intent, null, mContext.getOpPackageName(), 9926 UserHandle.USER_SYSTEM); 9927 } catch (RemoteException e) { 9928 } 9929 } 9930 } 9931 9932 @Override 9933 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9934 int installFlags, String installerPackageName, VerificationParams verificationParams, 9935 String packageAbiOverride) { 9936 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9937 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9938 } 9939 9940 @Override 9941 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9942 int installFlags, String installerPackageName, VerificationParams verificationParams, 9943 String packageAbiOverride, int userId) { 9944 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9945 9946 final int callingUid = Binder.getCallingUid(); 9947 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9948 9949 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9950 try { 9951 if (observer != null) { 9952 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9953 } 9954 } catch (RemoteException re) { 9955 } 9956 return; 9957 } 9958 9959 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9960 installFlags |= PackageManager.INSTALL_FROM_ADB; 9961 9962 } else { 9963 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9964 // about installerPackageName. 9965 9966 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9967 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9968 } 9969 9970 UserHandle user; 9971 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9972 user = UserHandle.ALL; 9973 } else { 9974 user = new UserHandle(userId); 9975 } 9976 9977 // Only system components can circumvent runtime permissions when installing. 9978 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9979 && mContext.checkCallingOrSelfPermission(Manifest.permission 9980 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9981 throw new SecurityException("You need the " 9982 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9983 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9984 } 9985 9986 verificationParams.setInstallerUid(callingUid); 9987 9988 final File originFile = new File(originPath); 9989 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9990 9991 final Message msg = mHandler.obtainMessage(INIT_COPY); 9992 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9993 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9994 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9995 msg.obj = params; 9996 9997 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9998 System.identityHashCode(msg.obj)); 9999 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10000 System.identityHashCode(msg.obj)); 10001 10002 mHandler.sendMessage(msg); 10003 } 10004 10005 void installStage(String packageName, File stagedDir, String stagedCid, 10006 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10007 String installerPackageName, int installerUid, UserHandle user) { 10008 if (DEBUG_EPHEMERAL) { 10009 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10010 Slog.d(TAG, "Ephemeral install of " + packageName); 10011 } 10012 } 10013 final VerificationParams verifParams = new VerificationParams( 10014 null, sessionParams.originatingUri, sessionParams.referrerUri, 10015 sessionParams.originatingUid); 10016 verifParams.setInstallerUid(installerUid); 10017 10018 final OriginInfo origin; 10019 if (stagedDir != null) { 10020 origin = OriginInfo.fromStagedFile(stagedDir); 10021 } else { 10022 origin = OriginInfo.fromStagedContainer(stagedCid); 10023 } 10024 10025 final Message msg = mHandler.obtainMessage(INIT_COPY); 10026 final InstallParams params = new InstallParams(origin, null, observer, 10027 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10028 verifParams, user, sessionParams.abiOverride, 10029 sessionParams.grantedRuntimePermissions); 10030 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10031 msg.obj = params; 10032 10033 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10034 System.identityHashCode(msg.obj)); 10035 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10036 System.identityHashCode(msg.obj)); 10037 10038 mHandler.sendMessage(msg); 10039 } 10040 10041 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10042 Bundle extras = new Bundle(1); 10043 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10044 10045 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10046 packageName, extras, 0, null, null, new int[] {userId}); 10047 try { 10048 IActivityManager am = ActivityManagerNative.getDefault(); 10049 final boolean isSystem = 10050 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10051 if (isSystem && am.isUserRunning(userId, 0)) { 10052 // The just-installed/enabled app is bundled on the system, so presumed 10053 // to be able to run automatically without needing an explicit launch. 10054 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10055 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10056 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10057 .setPackage(packageName); 10058 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10059 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10060 } 10061 } catch (RemoteException e) { 10062 // shouldn't happen 10063 Slog.w(TAG, "Unable to bootstrap installed package", e); 10064 } 10065 } 10066 10067 @Override 10068 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10069 int userId) { 10070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10071 PackageSetting pkgSetting; 10072 final int uid = Binder.getCallingUid(); 10073 enforceCrossUserPermission(uid, userId, true, true, 10074 "setApplicationHiddenSetting for user " + userId); 10075 10076 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10077 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10078 return false; 10079 } 10080 10081 long callingId = Binder.clearCallingIdentity(); 10082 try { 10083 boolean sendAdded = false; 10084 boolean sendRemoved = false; 10085 // writer 10086 synchronized (mPackages) { 10087 pkgSetting = mSettings.mPackages.get(packageName); 10088 if (pkgSetting == null) { 10089 return false; 10090 } 10091 if (pkgSetting.getHidden(userId) != hidden) { 10092 pkgSetting.setHidden(hidden, userId); 10093 mSettings.writePackageRestrictionsLPr(userId); 10094 if (hidden) { 10095 sendRemoved = true; 10096 } else { 10097 sendAdded = true; 10098 } 10099 } 10100 } 10101 if (sendAdded) { 10102 sendPackageAddedForUser(packageName, pkgSetting, userId); 10103 return true; 10104 } 10105 if (sendRemoved) { 10106 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10107 "hiding pkg"); 10108 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10109 return true; 10110 } 10111 } finally { 10112 Binder.restoreCallingIdentity(callingId); 10113 } 10114 return false; 10115 } 10116 10117 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10118 int userId) { 10119 final PackageRemovedInfo info = new PackageRemovedInfo(); 10120 info.removedPackage = packageName; 10121 info.removedUsers = new int[] {userId}; 10122 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10123 info.sendBroadcast(false, false, false); 10124 } 10125 10126 /** 10127 * Returns true if application is not found or there was an error. Otherwise it returns 10128 * the hidden state of the package for the given user. 10129 */ 10130 @Override 10131 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10132 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10133 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10134 false, "getApplicationHidden for user " + userId); 10135 PackageSetting pkgSetting; 10136 long callingId = Binder.clearCallingIdentity(); 10137 try { 10138 // writer 10139 synchronized (mPackages) { 10140 pkgSetting = mSettings.mPackages.get(packageName); 10141 if (pkgSetting == null) { 10142 return true; 10143 } 10144 return pkgSetting.getHidden(userId); 10145 } 10146 } finally { 10147 Binder.restoreCallingIdentity(callingId); 10148 } 10149 } 10150 10151 /** 10152 * @hide 10153 */ 10154 @Override 10155 public int installExistingPackageAsUser(String packageName, int userId) { 10156 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10157 null); 10158 PackageSetting pkgSetting; 10159 final int uid = Binder.getCallingUid(); 10160 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10161 + userId); 10162 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10163 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10164 } 10165 10166 long callingId = Binder.clearCallingIdentity(); 10167 try { 10168 boolean sendAdded = false; 10169 10170 // writer 10171 synchronized (mPackages) { 10172 pkgSetting = mSettings.mPackages.get(packageName); 10173 if (pkgSetting == null) { 10174 return PackageManager.INSTALL_FAILED_INVALID_URI; 10175 } 10176 if (!pkgSetting.getInstalled(userId)) { 10177 pkgSetting.setInstalled(true, userId); 10178 pkgSetting.setHidden(false, userId); 10179 mSettings.writePackageRestrictionsLPr(userId); 10180 sendAdded = true; 10181 } 10182 } 10183 10184 if (sendAdded) { 10185 sendPackageAddedForUser(packageName, pkgSetting, userId); 10186 } 10187 } finally { 10188 Binder.restoreCallingIdentity(callingId); 10189 } 10190 10191 return PackageManager.INSTALL_SUCCEEDED; 10192 } 10193 10194 boolean isUserRestricted(int userId, String restrictionKey) { 10195 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10196 if (restrictions.getBoolean(restrictionKey, false)) { 10197 Log.w(TAG, "User is restricted: " + restrictionKey); 10198 return true; 10199 } 10200 return false; 10201 } 10202 10203 @Override 10204 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10205 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10206 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10207 "setPackageSuspended for user " + userId); 10208 10209 long callingId = Binder.clearCallingIdentity(); 10210 try { 10211 synchronized (mPackages) { 10212 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10213 if (pkgSetting != null) { 10214 if (pkgSetting.getSuspended(userId) != suspended) { 10215 pkgSetting.setSuspended(suspended, userId); 10216 mSettings.writePackageRestrictionsLPr(userId); 10217 } 10218 10219 // TODO: 10220 // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up 10221 // * remove app from recents (kill app it if it is running) 10222 // * erase existing notifications for this app 10223 return true; 10224 } 10225 10226 return false; 10227 } 10228 } finally { 10229 Binder.restoreCallingIdentity(callingId); 10230 } 10231 } 10232 10233 @Override 10234 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10235 mContext.enforceCallingOrSelfPermission( 10236 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10237 "Only package verification agents can verify applications"); 10238 10239 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10240 final PackageVerificationResponse response = new PackageVerificationResponse( 10241 verificationCode, Binder.getCallingUid()); 10242 msg.arg1 = id; 10243 msg.obj = response; 10244 mHandler.sendMessage(msg); 10245 } 10246 10247 @Override 10248 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10249 long millisecondsToDelay) { 10250 mContext.enforceCallingOrSelfPermission( 10251 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10252 "Only package verification agents can extend verification timeouts"); 10253 10254 final PackageVerificationState state = mPendingVerification.get(id); 10255 final PackageVerificationResponse response = new PackageVerificationResponse( 10256 verificationCodeAtTimeout, Binder.getCallingUid()); 10257 10258 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10259 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10260 } 10261 if (millisecondsToDelay < 0) { 10262 millisecondsToDelay = 0; 10263 } 10264 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10265 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10266 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10267 } 10268 10269 if ((state != null) && !state.timeoutExtended()) { 10270 state.extendTimeout(); 10271 10272 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10273 msg.arg1 = id; 10274 msg.obj = response; 10275 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10276 } 10277 } 10278 10279 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10280 int verificationCode, UserHandle user) { 10281 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10282 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10283 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10284 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10285 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10286 10287 mContext.sendBroadcastAsUser(intent, user, 10288 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10289 } 10290 10291 private ComponentName matchComponentForVerifier(String packageName, 10292 List<ResolveInfo> receivers) { 10293 ActivityInfo targetReceiver = null; 10294 10295 final int NR = receivers.size(); 10296 for (int i = 0; i < NR; i++) { 10297 final ResolveInfo info = receivers.get(i); 10298 if (info.activityInfo == null) { 10299 continue; 10300 } 10301 10302 if (packageName.equals(info.activityInfo.packageName)) { 10303 targetReceiver = info.activityInfo; 10304 break; 10305 } 10306 } 10307 10308 if (targetReceiver == null) { 10309 return null; 10310 } 10311 10312 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10313 } 10314 10315 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10316 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10317 if (pkgInfo.verifiers.length == 0) { 10318 return null; 10319 } 10320 10321 final int N = pkgInfo.verifiers.length; 10322 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10323 for (int i = 0; i < N; i++) { 10324 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10325 10326 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10327 receivers); 10328 if (comp == null) { 10329 continue; 10330 } 10331 10332 final int verifierUid = getUidForVerifier(verifierInfo); 10333 if (verifierUid == -1) { 10334 continue; 10335 } 10336 10337 if (DEBUG_VERIFY) { 10338 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10339 + " with the correct signature"); 10340 } 10341 sufficientVerifiers.add(comp); 10342 verificationState.addSufficientVerifier(verifierUid); 10343 } 10344 10345 return sufficientVerifiers; 10346 } 10347 10348 private int getUidForVerifier(VerifierInfo verifierInfo) { 10349 synchronized (mPackages) { 10350 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10351 if (pkg == null) { 10352 return -1; 10353 } else if (pkg.mSignatures.length != 1) { 10354 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10355 + " has more than one signature; ignoring"); 10356 return -1; 10357 } 10358 10359 /* 10360 * If the public key of the package's signature does not match 10361 * our expected public key, then this is a different package and 10362 * we should skip. 10363 */ 10364 10365 final byte[] expectedPublicKey; 10366 try { 10367 final Signature verifierSig = pkg.mSignatures[0]; 10368 final PublicKey publicKey = verifierSig.getPublicKey(); 10369 expectedPublicKey = publicKey.getEncoded(); 10370 } catch (CertificateException e) { 10371 return -1; 10372 } 10373 10374 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10375 10376 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10377 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10378 + " does not have the expected public key; ignoring"); 10379 return -1; 10380 } 10381 10382 return pkg.applicationInfo.uid; 10383 } 10384 } 10385 10386 @Override 10387 public void finishPackageInstall(int token) { 10388 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10389 10390 if (DEBUG_INSTALL) { 10391 Slog.v(TAG, "BM finishing package install for " + token); 10392 } 10393 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10394 10395 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10396 mHandler.sendMessage(msg); 10397 } 10398 10399 /** 10400 * Get the verification agent timeout. 10401 * 10402 * @return verification timeout in milliseconds 10403 */ 10404 private long getVerificationTimeout() { 10405 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10406 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10407 DEFAULT_VERIFICATION_TIMEOUT); 10408 } 10409 10410 /** 10411 * Get the default verification agent response code. 10412 * 10413 * @return default verification response code 10414 */ 10415 private int getDefaultVerificationResponse() { 10416 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10417 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10418 DEFAULT_VERIFICATION_RESPONSE); 10419 } 10420 10421 /** 10422 * Check whether or not package verification has been enabled. 10423 * 10424 * @return true if verification should be performed 10425 */ 10426 private boolean isVerificationEnabled(int userId, int installFlags) { 10427 if (!DEFAULT_VERIFY_ENABLE) { 10428 return false; 10429 } 10430 // Ephemeral apps don't get the full verification treatment 10431 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10432 if (DEBUG_EPHEMERAL) { 10433 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10434 } 10435 return false; 10436 } 10437 10438 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10439 10440 // Check if installing from ADB 10441 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10442 // Do not run verification in a test harness environment 10443 if (ActivityManager.isRunningInTestHarness()) { 10444 return false; 10445 } 10446 if (ensureVerifyAppsEnabled) { 10447 return true; 10448 } 10449 // Check if the developer does not want package verification for ADB installs 10450 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10451 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10452 return false; 10453 } 10454 } 10455 10456 if (ensureVerifyAppsEnabled) { 10457 return true; 10458 } 10459 10460 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10461 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10462 } 10463 10464 @Override 10465 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10466 throws RemoteException { 10467 mContext.enforceCallingOrSelfPermission( 10468 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10469 "Only intentfilter verification agents can verify applications"); 10470 10471 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10472 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10473 Binder.getCallingUid(), verificationCode, failedDomains); 10474 msg.arg1 = id; 10475 msg.obj = response; 10476 mHandler.sendMessage(msg); 10477 } 10478 10479 @Override 10480 public int getIntentVerificationStatus(String packageName, int userId) { 10481 synchronized (mPackages) { 10482 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10483 } 10484 } 10485 10486 @Override 10487 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10488 mContext.enforceCallingOrSelfPermission( 10489 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10490 10491 boolean result = false; 10492 synchronized (mPackages) { 10493 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10494 } 10495 if (result) { 10496 scheduleWritePackageRestrictionsLocked(userId); 10497 } 10498 return result; 10499 } 10500 10501 @Override 10502 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10503 synchronized (mPackages) { 10504 return mSettings.getIntentFilterVerificationsLPr(packageName); 10505 } 10506 } 10507 10508 @Override 10509 public List<IntentFilter> getAllIntentFilters(String packageName) { 10510 if (TextUtils.isEmpty(packageName)) { 10511 return Collections.<IntentFilter>emptyList(); 10512 } 10513 synchronized (mPackages) { 10514 PackageParser.Package pkg = mPackages.get(packageName); 10515 if (pkg == null || pkg.activities == null) { 10516 return Collections.<IntentFilter>emptyList(); 10517 } 10518 final int count = pkg.activities.size(); 10519 ArrayList<IntentFilter> result = new ArrayList<>(); 10520 for (int n=0; n<count; n++) { 10521 PackageParser.Activity activity = pkg.activities.get(n); 10522 if (activity.intents != null && activity.intents.size() > 0) { 10523 result.addAll(activity.intents); 10524 } 10525 } 10526 return result; 10527 } 10528 } 10529 10530 @Override 10531 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10532 mContext.enforceCallingOrSelfPermission( 10533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10534 10535 synchronized (mPackages) { 10536 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10537 if (packageName != null) { 10538 result |= updateIntentVerificationStatus(packageName, 10539 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10540 userId); 10541 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10542 packageName, userId); 10543 } 10544 return result; 10545 } 10546 } 10547 10548 @Override 10549 public String getDefaultBrowserPackageName(int userId) { 10550 synchronized (mPackages) { 10551 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10552 } 10553 } 10554 10555 /** 10556 * Get the "allow unknown sources" setting. 10557 * 10558 * @return the current "allow unknown sources" setting 10559 */ 10560 private int getUnknownSourcesSettings() { 10561 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10562 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10563 -1); 10564 } 10565 10566 @Override 10567 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10568 final int uid = Binder.getCallingUid(); 10569 // writer 10570 synchronized (mPackages) { 10571 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10572 if (targetPackageSetting == null) { 10573 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10574 } 10575 10576 PackageSetting installerPackageSetting; 10577 if (installerPackageName != null) { 10578 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10579 if (installerPackageSetting == null) { 10580 throw new IllegalArgumentException("Unknown installer package: " 10581 + installerPackageName); 10582 } 10583 } else { 10584 installerPackageSetting = null; 10585 } 10586 10587 Signature[] callerSignature; 10588 Object obj = mSettings.getUserIdLPr(uid); 10589 if (obj != null) { 10590 if (obj instanceof SharedUserSetting) { 10591 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10592 } else if (obj instanceof PackageSetting) { 10593 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10594 } else { 10595 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10596 } 10597 } else { 10598 throw new SecurityException("Unknown calling UID: " + uid); 10599 } 10600 10601 // Verify: can't set installerPackageName to a package that is 10602 // not signed with the same cert as the caller. 10603 if (installerPackageSetting != null) { 10604 if (compareSignatures(callerSignature, 10605 installerPackageSetting.signatures.mSignatures) 10606 != PackageManager.SIGNATURE_MATCH) { 10607 throw new SecurityException( 10608 "Caller does not have same cert as new installer package " 10609 + installerPackageName); 10610 } 10611 } 10612 10613 // Verify: if target already has an installer package, it must 10614 // be signed with the same cert as the caller. 10615 if (targetPackageSetting.installerPackageName != null) { 10616 PackageSetting setting = mSettings.mPackages.get( 10617 targetPackageSetting.installerPackageName); 10618 // If the currently set package isn't valid, then it's always 10619 // okay to change it. 10620 if (setting != null) { 10621 if (compareSignatures(callerSignature, 10622 setting.signatures.mSignatures) 10623 != PackageManager.SIGNATURE_MATCH) { 10624 throw new SecurityException( 10625 "Caller does not have same cert as old installer package " 10626 + targetPackageSetting.installerPackageName); 10627 } 10628 } 10629 } 10630 10631 // Okay! 10632 targetPackageSetting.installerPackageName = installerPackageName; 10633 scheduleWriteSettingsLocked(); 10634 } 10635 } 10636 10637 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10638 // Queue up an async operation since the package installation may take a little while. 10639 mHandler.post(new Runnable() { 10640 public void run() { 10641 mHandler.removeCallbacks(this); 10642 // Result object to be returned 10643 PackageInstalledInfo res = new PackageInstalledInfo(); 10644 res.returnCode = currentStatus; 10645 res.uid = -1; 10646 res.pkg = null; 10647 res.removedInfo = new PackageRemovedInfo(); 10648 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10649 args.doPreInstall(res.returnCode); 10650 synchronized (mInstallLock) { 10651 installPackageTracedLI(args, res); 10652 } 10653 args.doPostInstall(res.returnCode, res.uid); 10654 } 10655 10656 // A restore should be performed at this point if (a) the install 10657 // succeeded, (b) the operation is not an update, and (c) the new 10658 // package has not opted out of backup participation. 10659 final boolean update = res.removedInfo.removedPackage != null; 10660 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10661 boolean doRestore = !update 10662 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10663 10664 // Set up the post-install work request bookkeeping. This will be used 10665 // and cleaned up by the post-install event handling regardless of whether 10666 // there's a restore pass performed. Token values are >= 1. 10667 int token; 10668 if (mNextInstallToken < 0) mNextInstallToken = 1; 10669 token = mNextInstallToken++; 10670 10671 PostInstallData data = new PostInstallData(args, res); 10672 mRunningInstalls.put(token, data); 10673 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10674 10675 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10676 // Pass responsibility to the Backup Manager. It will perform a 10677 // restore if appropriate, then pass responsibility back to the 10678 // Package Manager to run the post-install observer callbacks 10679 // and broadcasts. 10680 IBackupManager bm = IBackupManager.Stub.asInterface( 10681 ServiceManager.getService(Context.BACKUP_SERVICE)); 10682 if (bm != null) { 10683 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10684 + " to BM for possible restore"); 10685 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10686 try { 10687 // TODO: http://b/22388012 10688 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10689 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10690 } else { 10691 doRestore = false; 10692 } 10693 } catch (RemoteException e) { 10694 // can't happen; the backup manager is local 10695 } catch (Exception e) { 10696 Slog.e(TAG, "Exception trying to enqueue restore", e); 10697 doRestore = false; 10698 } 10699 } else { 10700 Slog.e(TAG, "Backup Manager not found!"); 10701 doRestore = false; 10702 } 10703 } 10704 10705 if (!doRestore) { 10706 // No restore possible, or the Backup Manager was mysteriously not 10707 // available -- just fire the post-install work request directly. 10708 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10709 10710 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10711 10712 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10713 mHandler.sendMessage(msg); 10714 } 10715 } 10716 }); 10717 } 10718 10719 private abstract class HandlerParams { 10720 private static final int MAX_RETRIES = 4; 10721 10722 /** 10723 * Number of times startCopy() has been attempted and had a non-fatal 10724 * error. 10725 */ 10726 private int mRetries = 0; 10727 10728 /** User handle for the user requesting the information or installation. */ 10729 private final UserHandle mUser; 10730 String traceMethod; 10731 int traceCookie; 10732 10733 HandlerParams(UserHandle user) { 10734 mUser = user; 10735 } 10736 10737 UserHandle getUser() { 10738 return mUser; 10739 } 10740 10741 HandlerParams setTraceMethod(String traceMethod) { 10742 this.traceMethod = traceMethod; 10743 return this; 10744 } 10745 10746 HandlerParams setTraceCookie(int traceCookie) { 10747 this.traceCookie = traceCookie; 10748 return this; 10749 } 10750 10751 final boolean startCopy() { 10752 boolean res; 10753 try { 10754 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10755 10756 if (++mRetries > MAX_RETRIES) { 10757 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10758 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10759 handleServiceError(); 10760 return false; 10761 } else { 10762 handleStartCopy(); 10763 res = true; 10764 } 10765 } catch (RemoteException e) { 10766 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10767 mHandler.sendEmptyMessage(MCS_RECONNECT); 10768 res = false; 10769 } 10770 handleReturnCode(); 10771 return res; 10772 } 10773 10774 final void serviceError() { 10775 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10776 handleServiceError(); 10777 handleReturnCode(); 10778 } 10779 10780 abstract void handleStartCopy() throws RemoteException; 10781 abstract void handleServiceError(); 10782 abstract void handleReturnCode(); 10783 } 10784 10785 class MeasureParams extends HandlerParams { 10786 private final PackageStats mStats; 10787 private boolean mSuccess; 10788 10789 private final IPackageStatsObserver mObserver; 10790 10791 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10792 super(new UserHandle(stats.userHandle)); 10793 mObserver = observer; 10794 mStats = stats; 10795 } 10796 10797 @Override 10798 public String toString() { 10799 return "MeasureParams{" 10800 + Integer.toHexString(System.identityHashCode(this)) 10801 + " " + mStats.packageName + "}"; 10802 } 10803 10804 @Override 10805 void handleStartCopy() throws RemoteException { 10806 synchronized (mInstallLock) { 10807 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10808 } 10809 10810 if (mSuccess) { 10811 final boolean mounted; 10812 if (Environment.isExternalStorageEmulated()) { 10813 mounted = true; 10814 } else { 10815 final String status = Environment.getExternalStorageState(); 10816 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10817 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10818 } 10819 10820 if (mounted) { 10821 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10822 10823 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10824 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10825 10826 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10827 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10828 10829 // Always subtract cache size, since it's a subdirectory 10830 mStats.externalDataSize -= mStats.externalCacheSize; 10831 10832 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10833 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10834 10835 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10836 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10837 } 10838 } 10839 } 10840 10841 @Override 10842 void handleReturnCode() { 10843 if (mObserver != null) { 10844 try { 10845 mObserver.onGetStatsCompleted(mStats, mSuccess); 10846 } catch (RemoteException e) { 10847 Slog.i(TAG, "Observer no longer exists."); 10848 } 10849 } 10850 } 10851 10852 @Override 10853 void handleServiceError() { 10854 Slog.e(TAG, "Could not measure application " + mStats.packageName 10855 + " external storage"); 10856 } 10857 } 10858 10859 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10860 throws RemoteException { 10861 long result = 0; 10862 for (File path : paths) { 10863 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10864 } 10865 return result; 10866 } 10867 10868 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10869 for (File path : paths) { 10870 try { 10871 mcs.clearDirectory(path.getAbsolutePath()); 10872 } catch (RemoteException e) { 10873 } 10874 } 10875 } 10876 10877 static class OriginInfo { 10878 /** 10879 * Location where install is coming from, before it has been 10880 * copied/renamed into place. This could be a single monolithic APK 10881 * file, or a cluster directory. This location may be untrusted. 10882 */ 10883 final File file; 10884 final String cid; 10885 10886 /** 10887 * Flag indicating that {@link #file} or {@link #cid} has already been 10888 * staged, meaning downstream users don't need to defensively copy the 10889 * contents. 10890 */ 10891 final boolean staged; 10892 10893 /** 10894 * Flag indicating that {@link #file} or {@link #cid} is an already 10895 * installed app that is being moved. 10896 */ 10897 final boolean existing; 10898 10899 final String resolvedPath; 10900 final File resolvedFile; 10901 10902 static OriginInfo fromNothing() { 10903 return new OriginInfo(null, null, false, false); 10904 } 10905 10906 static OriginInfo fromUntrustedFile(File file) { 10907 return new OriginInfo(file, null, false, false); 10908 } 10909 10910 static OriginInfo fromExistingFile(File file) { 10911 return new OriginInfo(file, null, false, true); 10912 } 10913 10914 static OriginInfo fromStagedFile(File file) { 10915 return new OriginInfo(file, null, true, false); 10916 } 10917 10918 static OriginInfo fromStagedContainer(String cid) { 10919 return new OriginInfo(null, cid, true, false); 10920 } 10921 10922 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10923 this.file = file; 10924 this.cid = cid; 10925 this.staged = staged; 10926 this.existing = existing; 10927 10928 if (cid != null) { 10929 resolvedPath = PackageHelper.getSdDir(cid); 10930 resolvedFile = new File(resolvedPath); 10931 } else if (file != null) { 10932 resolvedPath = file.getAbsolutePath(); 10933 resolvedFile = file; 10934 } else { 10935 resolvedPath = null; 10936 resolvedFile = null; 10937 } 10938 } 10939 } 10940 10941 static class MoveInfo { 10942 final int moveId; 10943 final String fromUuid; 10944 final String toUuid; 10945 final String packageName; 10946 final String dataAppName; 10947 final int appId; 10948 final String seinfo; 10949 10950 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10951 String dataAppName, int appId, String seinfo) { 10952 this.moveId = moveId; 10953 this.fromUuid = fromUuid; 10954 this.toUuid = toUuid; 10955 this.packageName = packageName; 10956 this.dataAppName = dataAppName; 10957 this.appId = appId; 10958 this.seinfo = seinfo; 10959 } 10960 } 10961 10962 class InstallParams extends HandlerParams { 10963 final OriginInfo origin; 10964 final MoveInfo move; 10965 final IPackageInstallObserver2 observer; 10966 int installFlags; 10967 final String installerPackageName; 10968 final String volumeUuid; 10969 final VerificationParams verificationParams; 10970 private InstallArgs mArgs; 10971 private int mRet; 10972 final String packageAbiOverride; 10973 final String[] grantedRuntimePermissions; 10974 10975 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10976 int installFlags, String installerPackageName, String volumeUuid, 10977 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 10978 String[] grantedPermissions) { 10979 super(user); 10980 this.origin = origin; 10981 this.move = move; 10982 this.observer = observer; 10983 this.installFlags = installFlags; 10984 this.installerPackageName = installerPackageName; 10985 this.volumeUuid = volumeUuid; 10986 this.verificationParams = verificationParams; 10987 this.packageAbiOverride = packageAbiOverride; 10988 this.grantedRuntimePermissions = grantedPermissions; 10989 } 10990 10991 @Override 10992 public String toString() { 10993 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 10994 + " file=" + origin.file + " cid=" + origin.cid + "}"; 10995 } 10996 10997 private int installLocationPolicy(PackageInfoLite pkgLite) { 10998 String packageName = pkgLite.packageName; 10999 int installLocation = pkgLite.installLocation; 11000 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11001 // reader 11002 synchronized (mPackages) { 11003 PackageParser.Package pkg = mPackages.get(packageName); 11004 if (pkg != null) { 11005 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11006 // Check for downgrading. 11007 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11008 try { 11009 checkDowngrade(pkg, pkgLite); 11010 } catch (PackageManagerException e) { 11011 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11012 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11013 } 11014 } 11015 // Check for updated system application. 11016 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11017 if (onSd) { 11018 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11019 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11020 } 11021 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11022 } else { 11023 if (onSd) { 11024 // Install flag overrides everything. 11025 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11026 } 11027 // If current upgrade specifies particular preference 11028 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11029 // Application explicitly specified internal. 11030 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11031 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11032 // App explictly prefers external. Let policy decide 11033 } else { 11034 // Prefer previous location 11035 if (isExternal(pkg)) { 11036 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11037 } 11038 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11039 } 11040 } 11041 } else { 11042 // Invalid install. Return error code 11043 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11044 } 11045 } 11046 } 11047 // All the special cases have been taken care of. 11048 // Return result based on recommended install location. 11049 if (onSd) { 11050 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11051 } 11052 return pkgLite.recommendedInstallLocation; 11053 } 11054 11055 /* 11056 * Invoke remote method to get package information and install 11057 * location values. Override install location based on default 11058 * policy if needed and then create install arguments based 11059 * on the install location. 11060 */ 11061 public void handleStartCopy() throws RemoteException { 11062 int ret = PackageManager.INSTALL_SUCCEEDED; 11063 11064 // If we're already staged, we've firmly committed to an install location 11065 if (origin.staged) { 11066 if (origin.file != null) { 11067 installFlags |= PackageManager.INSTALL_INTERNAL; 11068 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11069 } else if (origin.cid != null) { 11070 installFlags |= PackageManager.INSTALL_EXTERNAL; 11071 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11072 } else { 11073 throw new IllegalStateException("Invalid stage location"); 11074 } 11075 } 11076 11077 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11078 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11079 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11080 PackageInfoLite pkgLite = null; 11081 11082 if (onInt && onSd) { 11083 // Check if both bits are set. 11084 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11085 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11086 } else if (onSd && ephemeral) { 11087 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11088 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11089 } else { 11090 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11091 packageAbiOverride); 11092 11093 if (DEBUG_EPHEMERAL && ephemeral) { 11094 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11095 } 11096 11097 /* 11098 * If we have too little free space, try to free cache 11099 * before giving up. 11100 */ 11101 if (!origin.staged && pkgLite.recommendedInstallLocation 11102 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11103 // TODO: focus freeing disk space on the target device 11104 final StorageManager storage = StorageManager.from(mContext); 11105 final long lowThreshold = storage.getStorageLowBytes( 11106 Environment.getDataDirectory()); 11107 11108 final long sizeBytes = mContainerService.calculateInstalledSize( 11109 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11110 11111 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 11112 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11113 installFlags, packageAbiOverride); 11114 } 11115 11116 /* 11117 * The cache free must have deleted the file we 11118 * downloaded to install. 11119 * 11120 * TODO: fix the "freeCache" call to not delete 11121 * the file we care about. 11122 */ 11123 if (pkgLite.recommendedInstallLocation 11124 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11125 pkgLite.recommendedInstallLocation 11126 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11127 } 11128 } 11129 } 11130 11131 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11132 int loc = pkgLite.recommendedInstallLocation; 11133 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11134 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11135 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11136 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11137 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11138 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11139 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11140 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11141 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11142 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11143 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11144 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11145 } else { 11146 // Override with defaults if needed. 11147 loc = installLocationPolicy(pkgLite); 11148 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11149 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11150 } else if (!onSd && !onInt) { 11151 // Override install location with flags 11152 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11153 // Set the flag to install on external media. 11154 installFlags |= PackageManager.INSTALL_EXTERNAL; 11155 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11156 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11157 if (DEBUG_EPHEMERAL) { 11158 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11159 } 11160 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11161 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11162 |PackageManager.INSTALL_INTERNAL); 11163 } else { 11164 // Make sure the flag for installing on external 11165 // media is unset 11166 installFlags |= PackageManager.INSTALL_INTERNAL; 11167 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11168 } 11169 } 11170 } 11171 } 11172 11173 final InstallArgs args = createInstallArgs(this); 11174 mArgs = args; 11175 11176 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11177 // TODO: http://b/22976637 11178 // Apps installed for "all" users use the device owner to verify the app 11179 UserHandle verifierUser = getUser(); 11180 if (verifierUser == UserHandle.ALL) { 11181 verifierUser = UserHandle.SYSTEM; 11182 } 11183 11184 /* 11185 * Determine if we have any installed package verifiers. If we 11186 * do, then we'll defer to them to verify the packages. 11187 */ 11188 final int requiredUid = mRequiredVerifierPackage == null ? -1 11189 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11190 verifierUser.getIdentifier()); 11191 if (!origin.existing && requiredUid != -1 11192 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11193 final Intent verification = new Intent( 11194 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11195 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11196 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11197 PACKAGE_MIME_TYPE); 11198 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11199 11200 // Query all live verifiers based on current user state 11201 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11202 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11203 11204 if (DEBUG_VERIFY) { 11205 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11206 + verification.toString() + " with " + pkgLite.verifiers.length 11207 + " optional verifiers"); 11208 } 11209 11210 final int verificationId = mPendingVerificationToken++; 11211 11212 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11213 11214 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11215 installerPackageName); 11216 11217 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11218 installFlags); 11219 11220 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11221 pkgLite.packageName); 11222 11223 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11224 pkgLite.versionCode); 11225 11226 if (verificationParams != null) { 11227 if (verificationParams.getVerificationURI() != null) { 11228 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11229 verificationParams.getVerificationURI()); 11230 } 11231 if (verificationParams.getOriginatingURI() != null) { 11232 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11233 verificationParams.getOriginatingURI()); 11234 } 11235 if (verificationParams.getReferrer() != null) { 11236 verification.putExtra(Intent.EXTRA_REFERRER, 11237 verificationParams.getReferrer()); 11238 } 11239 if (verificationParams.getOriginatingUid() >= 0) { 11240 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11241 verificationParams.getOriginatingUid()); 11242 } 11243 if (verificationParams.getInstallerUid() >= 0) { 11244 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11245 verificationParams.getInstallerUid()); 11246 } 11247 } 11248 11249 final PackageVerificationState verificationState = new PackageVerificationState( 11250 requiredUid, args); 11251 11252 mPendingVerification.append(verificationId, verificationState); 11253 11254 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11255 receivers, verificationState); 11256 11257 /* 11258 * If any sufficient verifiers were listed in the package 11259 * manifest, attempt to ask them. 11260 */ 11261 if (sufficientVerifiers != null) { 11262 final int N = sufficientVerifiers.size(); 11263 if (N == 0) { 11264 Slog.i(TAG, "Additional verifiers required, but none installed."); 11265 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11266 } else { 11267 for (int i = 0; i < N; i++) { 11268 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11269 11270 final Intent sufficientIntent = new Intent(verification); 11271 sufficientIntent.setComponent(verifierComponent); 11272 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11273 } 11274 } 11275 } 11276 11277 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11278 mRequiredVerifierPackage, receivers); 11279 if (ret == PackageManager.INSTALL_SUCCEEDED 11280 && mRequiredVerifierPackage != null) { 11281 Trace.asyncTraceBegin( 11282 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11283 /* 11284 * Send the intent to the required verification agent, 11285 * but only start the verification timeout after the 11286 * target BroadcastReceivers have run. 11287 */ 11288 verification.setComponent(requiredVerifierComponent); 11289 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11290 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11291 new BroadcastReceiver() { 11292 @Override 11293 public void onReceive(Context context, Intent intent) { 11294 final Message msg = mHandler 11295 .obtainMessage(CHECK_PENDING_VERIFICATION); 11296 msg.arg1 = verificationId; 11297 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11298 } 11299 }, null, 0, null, null); 11300 11301 /* 11302 * We don't want the copy to proceed until verification 11303 * succeeds, so null out this field. 11304 */ 11305 mArgs = null; 11306 } 11307 } else { 11308 /* 11309 * No package verification is enabled, so immediately start 11310 * the remote call to initiate copy using temporary file. 11311 */ 11312 ret = args.copyApk(mContainerService, true); 11313 } 11314 } 11315 11316 mRet = ret; 11317 } 11318 11319 @Override 11320 void handleReturnCode() { 11321 // If mArgs is null, then MCS couldn't be reached. When it 11322 // reconnects, it will try again to install. At that point, this 11323 // will succeed. 11324 if (mArgs != null) { 11325 processPendingInstall(mArgs, mRet); 11326 } 11327 } 11328 11329 @Override 11330 void handleServiceError() { 11331 mArgs = createInstallArgs(this); 11332 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11333 } 11334 11335 public boolean isForwardLocked() { 11336 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11337 } 11338 } 11339 11340 /** 11341 * Used during creation of InstallArgs 11342 * 11343 * @param installFlags package installation flags 11344 * @return true if should be installed on external storage 11345 */ 11346 private static boolean installOnExternalAsec(int installFlags) { 11347 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11348 return false; 11349 } 11350 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11351 return true; 11352 } 11353 return false; 11354 } 11355 11356 /** 11357 * Used during creation of InstallArgs 11358 * 11359 * @param installFlags package installation flags 11360 * @return true if should be installed as forward locked 11361 */ 11362 private static boolean installForwardLocked(int installFlags) { 11363 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11364 } 11365 11366 private InstallArgs createInstallArgs(InstallParams params) { 11367 if (params.move != null) { 11368 return new MoveInstallArgs(params); 11369 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11370 return new AsecInstallArgs(params); 11371 } else { 11372 return new FileInstallArgs(params); 11373 } 11374 } 11375 11376 /** 11377 * Create args that describe an existing installed package. Typically used 11378 * when cleaning up old installs, or used as a move source. 11379 */ 11380 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11381 String resourcePath, String[] instructionSets) { 11382 final boolean isInAsec; 11383 if (installOnExternalAsec(installFlags)) { 11384 /* Apps on SD card are always in ASEC containers. */ 11385 isInAsec = true; 11386 } else if (installForwardLocked(installFlags) 11387 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11388 /* 11389 * Forward-locked apps are only in ASEC containers if they're the 11390 * new style 11391 */ 11392 isInAsec = true; 11393 } else { 11394 isInAsec = false; 11395 } 11396 11397 if (isInAsec) { 11398 return new AsecInstallArgs(codePath, instructionSets, 11399 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11400 } else { 11401 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11402 } 11403 } 11404 11405 static abstract class InstallArgs { 11406 /** @see InstallParams#origin */ 11407 final OriginInfo origin; 11408 /** @see InstallParams#move */ 11409 final MoveInfo move; 11410 11411 final IPackageInstallObserver2 observer; 11412 // Always refers to PackageManager flags only 11413 final int installFlags; 11414 final String installerPackageName; 11415 final String volumeUuid; 11416 final UserHandle user; 11417 final String abiOverride; 11418 final String[] installGrantPermissions; 11419 /** If non-null, drop an async trace when the install completes */ 11420 final String traceMethod; 11421 final int traceCookie; 11422 11423 // The list of instruction sets supported by this app. This is currently 11424 // only used during the rmdex() phase to clean up resources. We can get rid of this 11425 // if we move dex files under the common app path. 11426 /* nullable */ String[] instructionSets; 11427 11428 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11429 int installFlags, String installerPackageName, String volumeUuid, 11430 UserHandle user, String[] instructionSets, 11431 String abiOverride, String[] installGrantPermissions, 11432 String traceMethod, int traceCookie) { 11433 this.origin = origin; 11434 this.move = move; 11435 this.installFlags = installFlags; 11436 this.observer = observer; 11437 this.installerPackageName = installerPackageName; 11438 this.volumeUuid = volumeUuid; 11439 this.user = user; 11440 this.instructionSets = instructionSets; 11441 this.abiOverride = abiOverride; 11442 this.installGrantPermissions = installGrantPermissions; 11443 this.traceMethod = traceMethod; 11444 this.traceCookie = traceCookie; 11445 } 11446 11447 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11448 abstract int doPreInstall(int status); 11449 11450 /** 11451 * Rename package into final resting place. All paths on the given 11452 * scanned package should be updated to reflect the rename. 11453 */ 11454 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11455 abstract int doPostInstall(int status, int uid); 11456 11457 /** @see PackageSettingBase#codePathString */ 11458 abstract String getCodePath(); 11459 /** @see PackageSettingBase#resourcePathString */ 11460 abstract String getResourcePath(); 11461 11462 // Need installer lock especially for dex file removal. 11463 abstract void cleanUpResourcesLI(); 11464 abstract boolean doPostDeleteLI(boolean delete); 11465 11466 /** 11467 * Called before the source arguments are copied. This is used mostly 11468 * for MoveParams when it needs to read the source file to put it in the 11469 * destination. 11470 */ 11471 int doPreCopy() { 11472 return PackageManager.INSTALL_SUCCEEDED; 11473 } 11474 11475 /** 11476 * Called after the source arguments are copied. This is used mostly for 11477 * MoveParams when it needs to read the source file to put it in the 11478 * destination. 11479 * 11480 * @return 11481 */ 11482 int doPostCopy(int uid) { 11483 return PackageManager.INSTALL_SUCCEEDED; 11484 } 11485 11486 protected boolean isFwdLocked() { 11487 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11488 } 11489 11490 protected boolean isExternalAsec() { 11491 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11492 } 11493 11494 protected boolean isEphemeral() { 11495 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11496 } 11497 11498 UserHandle getUser() { 11499 return user; 11500 } 11501 } 11502 11503 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11504 if (!allCodePaths.isEmpty()) { 11505 if (instructionSets == null) { 11506 throw new IllegalStateException("instructionSet == null"); 11507 } 11508 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11509 for (String codePath : allCodePaths) { 11510 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11511 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 11512 if (retCode < 0) { 11513 Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath 11514 + ", retcode=" + retCode); 11515 // we don't consider this to be a failure of the core package deletion 11516 } 11517 } 11518 } 11519 } 11520 } 11521 11522 /** 11523 * Logic to handle installation of non-ASEC applications, including copying 11524 * and renaming logic. 11525 */ 11526 class FileInstallArgs extends InstallArgs { 11527 private File codeFile; 11528 private File resourceFile; 11529 11530 // Example topology: 11531 // /data/app/com.example/base.apk 11532 // /data/app/com.example/split_foo.apk 11533 // /data/app/com.example/lib/arm/libfoo.so 11534 // /data/app/com.example/lib/arm64/libfoo.so 11535 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11536 11537 /** New install */ 11538 FileInstallArgs(InstallParams params) { 11539 super(params.origin, params.move, params.observer, params.installFlags, 11540 params.installerPackageName, params.volumeUuid, 11541 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11542 params.grantedRuntimePermissions, 11543 params.traceMethod, params.traceCookie); 11544 if (isFwdLocked()) { 11545 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11546 } 11547 } 11548 11549 /** Existing install */ 11550 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11551 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11552 null, null, null, 0); 11553 this.codeFile = (codePath != null) ? new File(codePath) : null; 11554 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11555 } 11556 11557 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11559 try { 11560 return doCopyApk(imcs, temp); 11561 } finally { 11562 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11563 } 11564 } 11565 11566 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11567 if (origin.staged) { 11568 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11569 codeFile = origin.file; 11570 resourceFile = origin.file; 11571 return PackageManager.INSTALL_SUCCEEDED; 11572 } 11573 11574 try { 11575 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11576 final File tempDir = 11577 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11578 codeFile = tempDir; 11579 resourceFile = tempDir; 11580 } catch (IOException e) { 11581 Slog.w(TAG, "Failed to create copy file: " + e); 11582 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11583 } 11584 11585 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11586 @Override 11587 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11588 if (!FileUtils.isValidExtFilename(name)) { 11589 throw new IllegalArgumentException("Invalid filename: " + name); 11590 } 11591 try { 11592 final File file = new File(codeFile, name); 11593 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11594 O_RDWR | O_CREAT, 0644); 11595 Os.chmod(file.getAbsolutePath(), 0644); 11596 return new ParcelFileDescriptor(fd); 11597 } catch (ErrnoException e) { 11598 throw new RemoteException("Failed to open: " + e.getMessage()); 11599 } 11600 } 11601 }; 11602 11603 int ret = PackageManager.INSTALL_SUCCEEDED; 11604 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11605 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11606 Slog.e(TAG, "Failed to copy package"); 11607 return ret; 11608 } 11609 11610 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11611 NativeLibraryHelper.Handle handle = null; 11612 try { 11613 handle = NativeLibraryHelper.Handle.create(codeFile); 11614 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11615 abiOverride); 11616 } catch (IOException e) { 11617 Slog.e(TAG, "Copying native libraries failed", e); 11618 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11619 } finally { 11620 IoUtils.closeQuietly(handle); 11621 } 11622 11623 return ret; 11624 } 11625 11626 int doPreInstall(int status) { 11627 if (status != PackageManager.INSTALL_SUCCEEDED) { 11628 cleanUp(); 11629 } 11630 return status; 11631 } 11632 11633 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11634 if (status != PackageManager.INSTALL_SUCCEEDED) { 11635 cleanUp(); 11636 return false; 11637 } 11638 11639 final File targetDir = codeFile.getParentFile(); 11640 final File beforeCodeFile = codeFile; 11641 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11642 11643 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11644 try { 11645 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11646 } catch (ErrnoException e) { 11647 Slog.w(TAG, "Failed to rename", e); 11648 return false; 11649 } 11650 11651 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11652 Slog.w(TAG, "Failed to restorecon"); 11653 return false; 11654 } 11655 11656 // Reflect the rename internally 11657 codeFile = afterCodeFile; 11658 resourceFile = afterCodeFile; 11659 11660 // Reflect the rename in scanned details 11661 pkg.codePath = afterCodeFile.getAbsolutePath(); 11662 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11663 pkg.baseCodePath); 11664 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11665 pkg.splitCodePaths); 11666 11667 // Reflect the rename in app info 11668 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11669 pkg.applicationInfo.setCodePath(pkg.codePath); 11670 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11671 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11672 pkg.applicationInfo.setResourcePath(pkg.codePath); 11673 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11674 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11675 11676 return true; 11677 } 11678 11679 int doPostInstall(int status, int uid) { 11680 if (status != PackageManager.INSTALL_SUCCEEDED) { 11681 cleanUp(); 11682 } 11683 return status; 11684 } 11685 11686 @Override 11687 String getCodePath() { 11688 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11689 } 11690 11691 @Override 11692 String getResourcePath() { 11693 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11694 } 11695 11696 private boolean cleanUp() { 11697 if (codeFile == null || !codeFile.exists()) { 11698 return false; 11699 } 11700 11701 if (codeFile.isDirectory()) { 11702 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11703 } else { 11704 codeFile.delete(); 11705 } 11706 11707 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11708 resourceFile.delete(); 11709 } 11710 11711 return true; 11712 } 11713 11714 void cleanUpResourcesLI() { 11715 // Try enumerating all code paths before deleting 11716 List<String> allCodePaths = Collections.EMPTY_LIST; 11717 if (codeFile != null && codeFile.exists()) { 11718 try { 11719 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11720 allCodePaths = pkg.getAllCodePaths(); 11721 } catch (PackageParserException e) { 11722 // Ignored; we tried our best 11723 } 11724 } 11725 11726 cleanUp(); 11727 removeDexFiles(allCodePaths, instructionSets); 11728 } 11729 11730 boolean doPostDeleteLI(boolean delete) { 11731 // XXX err, shouldn't we respect the delete flag? 11732 cleanUpResourcesLI(); 11733 return true; 11734 } 11735 } 11736 11737 private boolean isAsecExternal(String cid) { 11738 final String asecPath = PackageHelper.getSdFilesystem(cid); 11739 return !asecPath.startsWith(mAsecInternalPath); 11740 } 11741 11742 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11743 PackageManagerException { 11744 if (copyRet < 0) { 11745 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11746 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11747 throw new PackageManagerException(copyRet, message); 11748 } 11749 } 11750 } 11751 11752 /** 11753 * Extract the MountService "container ID" from the full code path of an 11754 * .apk. 11755 */ 11756 static String cidFromCodePath(String fullCodePath) { 11757 int eidx = fullCodePath.lastIndexOf("/"); 11758 String subStr1 = fullCodePath.substring(0, eidx); 11759 int sidx = subStr1.lastIndexOf("/"); 11760 return subStr1.substring(sidx+1, eidx); 11761 } 11762 11763 /** 11764 * Logic to handle installation of ASEC applications, including copying and 11765 * renaming logic. 11766 */ 11767 class AsecInstallArgs extends InstallArgs { 11768 static final String RES_FILE_NAME = "pkg.apk"; 11769 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11770 11771 String cid; 11772 String packagePath; 11773 String resourcePath; 11774 11775 /** New install */ 11776 AsecInstallArgs(InstallParams params) { 11777 super(params.origin, params.move, params.observer, params.installFlags, 11778 params.installerPackageName, params.volumeUuid, 11779 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11780 params.grantedRuntimePermissions, 11781 params.traceMethod, params.traceCookie); 11782 } 11783 11784 /** Existing install */ 11785 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11786 boolean isExternal, boolean isForwardLocked) { 11787 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11788 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11789 instructionSets, null, null, null, 0); 11790 // Hackily pretend we're still looking at a full code path 11791 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11792 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11793 } 11794 11795 // Extract cid from fullCodePath 11796 int eidx = fullCodePath.lastIndexOf("/"); 11797 String subStr1 = fullCodePath.substring(0, eidx); 11798 int sidx = subStr1.lastIndexOf("/"); 11799 cid = subStr1.substring(sidx+1, eidx); 11800 setMountPath(subStr1); 11801 } 11802 11803 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11804 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11805 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11806 instructionSets, null, null, null, 0); 11807 this.cid = cid; 11808 setMountPath(PackageHelper.getSdDir(cid)); 11809 } 11810 11811 void createCopyFile() { 11812 cid = mInstallerService.allocateExternalStageCidLegacy(); 11813 } 11814 11815 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11816 if (origin.staged && origin.cid != null) { 11817 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11818 cid = origin.cid; 11819 setMountPath(PackageHelper.getSdDir(cid)); 11820 return PackageManager.INSTALL_SUCCEEDED; 11821 } 11822 11823 if (temp) { 11824 createCopyFile(); 11825 } else { 11826 /* 11827 * Pre-emptively destroy the container since it's destroyed if 11828 * copying fails due to it existing anyway. 11829 */ 11830 PackageHelper.destroySdDir(cid); 11831 } 11832 11833 final String newMountPath = imcs.copyPackageToContainer( 11834 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11835 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11836 11837 if (newMountPath != null) { 11838 setMountPath(newMountPath); 11839 return PackageManager.INSTALL_SUCCEEDED; 11840 } else { 11841 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11842 } 11843 } 11844 11845 @Override 11846 String getCodePath() { 11847 return packagePath; 11848 } 11849 11850 @Override 11851 String getResourcePath() { 11852 return resourcePath; 11853 } 11854 11855 int doPreInstall(int status) { 11856 if (status != PackageManager.INSTALL_SUCCEEDED) { 11857 // Destroy container 11858 PackageHelper.destroySdDir(cid); 11859 } else { 11860 boolean mounted = PackageHelper.isContainerMounted(cid); 11861 if (!mounted) { 11862 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11863 Process.SYSTEM_UID); 11864 if (newMountPath != null) { 11865 setMountPath(newMountPath); 11866 } else { 11867 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11868 } 11869 } 11870 } 11871 return status; 11872 } 11873 11874 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11875 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11876 String newMountPath = null; 11877 if (PackageHelper.isContainerMounted(cid)) { 11878 // Unmount the container 11879 if (!PackageHelper.unMountSdDir(cid)) { 11880 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11881 return false; 11882 } 11883 } 11884 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11885 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11886 " which might be stale. Will try to clean up."); 11887 // Clean up the stale container and proceed to recreate. 11888 if (!PackageHelper.destroySdDir(newCacheId)) { 11889 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11890 return false; 11891 } 11892 // Successfully cleaned up stale container. Try to rename again. 11893 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11894 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11895 + " inspite of cleaning it up."); 11896 return false; 11897 } 11898 } 11899 if (!PackageHelper.isContainerMounted(newCacheId)) { 11900 Slog.w(TAG, "Mounting container " + newCacheId); 11901 newMountPath = PackageHelper.mountSdDir(newCacheId, 11902 getEncryptKey(), Process.SYSTEM_UID); 11903 } else { 11904 newMountPath = PackageHelper.getSdDir(newCacheId); 11905 } 11906 if (newMountPath == null) { 11907 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11908 return false; 11909 } 11910 Log.i(TAG, "Succesfully renamed " + cid + 11911 " to " + newCacheId + 11912 " at new path: " + newMountPath); 11913 cid = newCacheId; 11914 11915 final File beforeCodeFile = new File(packagePath); 11916 setMountPath(newMountPath); 11917 final File afterCodeFile = new File(packagePath); 11918 11919 // Reflect the rename in scanned details 11920 pkg.codePath = afterCodeFile.getAbsolutePath(); 11921 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11922 pkg.baseCodePath); 11923 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11924 pkg.splitCodePaths); 11925 11926 // Reflect the rename in app info 11927 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11928 pkg.applicationInfo.setCodePath(pkg.codePath); 11929 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11930 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11931 pkg.applicationInfo.setResourcePath(pkg.codePath); 11932 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11933 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11934 11935 return true; 11936 } 11937 11938 private void setMountPath(String mountPath) { 11939 final File mountFile = new File(mountPath); 11940 11941 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11942 if (monolithicFile.exists()) { 11943 packagePath = monolithicFile.getAbsolutePath(); 11944 if (isFwdLocked()) { 11945 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11946 } else { 11947 resourcePath = packagePath; 11948 } 11949 } else { 11950 packagePath = mountFile.getAbsolutePath(); 11951 resourcePath = packagePath; 11952 } 11953 } 11954 11955 int doPostInstall(int status, int uid) { 11956 if (status != PackageManager.INSTALL_SUCCEEDED) { 11957 cleanUp(); 11958 } else { 11959 final int groupOwner; 11960 final String protectedFile; 11961 if (isFwdLocked()) { 11962 groupOwner = UserHandle.getSharedAppGid(uid); 11963 protectedFile = RES_FILE_NAME; 11964 } else { 11965 groupOwner = -1; 11966 protectedFile = null; 11967 } 11968 11969 if (uid < Process.FIRST_APPLICATION_UID 11970 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11971 Slog.e(TAG, "Failed to finalize " + cid); 11972 PackageHelper.destroySdDir(cid); 11973 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11974 } 11975 11976 boolean mounted = PackageHelper.isContainerMounted(cid); 11977 if (!mounted) { 11978 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 11979 } 11980 } 11981 return status; 11982 } 11983 11984 private void cleanUp() { 11985 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 11986 11987 // Destroy secure container 11988 PackageHelper.destroySdDir(cid); 11989 } 11990 11991 private List<String> getAllCodePaths() { 11992 final File codeFile = new File(getCodePath()); 11993 if (codeFile != null && codeFile.exists()) { 11994 try { 11995 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11996 return pkg.getAllCodePaths(); 11997 } catch (PackageParserException e) { 11998 // Ignored; we tried our best 11999 } 12000 } 12001 return Collections.EMPTY_LIST; 12002 } 12003 12004 void cleanUpResourcesLI() { 12005 // Enumerate all code paths before deleting 12006 cleanUpResourcesLI(getAllCodePaths()); 12007 } 12008 12009 private void cleanUpResourcesLI(List<String> allCodePaths) { 12010 cleanUp(); 12011 removeDexFiles(allCodePaths, instructionSets); 12012 } 12013 12014 String getPackageName() { 12015 return getAsecPackageName(cid); 12016 } 12017 12018 boolean doPostDeleteLI(boolean delete) { 12019 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12020 final List<String> allCodePaths = getAllCodePaths(); 12021 boolean mounted = PackageHelper.isContainerMounted(cid); 12022 if (mounted) { 12023 // Unmount first 12024 if (PackageHelper.unMountSdDir(cid)) { 12025 mounted = false; 12026 } 12027 } 12028 if (!mounted && delete) { 12029 cleanUpResourcesLI(allCodePaths); 12030 } 12031 return !mounted; 12032 } 12033 12034 @Override 12035 int doPreCopy() { 12036 if (isFwdLocked()) { 12037 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12038 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12039 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12040 } 12041 } 12042 12043 return PackageManager.INSTALL_SUCCEEDED; 12044 } 12045 12046 @Override 12047 int doPostCopy(int uid) { 12048 if (isFwdLocked()) { 12049 if (uid < Process.FIRST_APPLICATION_UID 12050 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12051 RES_FILE_NAME)) { 12052 Slog.e(TAG, "Failed to finalize " + cid); 12053 PackageHelper.destroySdDir(cid); 12054 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12055 } 12056 } 12057 12058 return PackageManager.INSTALL_SUCCEEDED; 12059 } 12060 } 12061 12062 /** 12063 * Logic to handle movement of existing installed applications. 12064 */ 12065 class MoveInstallArgs extends InstallArgs { 12066 private File codeFile; 12067 private File resourceFile; 12068 12069 /** New install */ 12070 MoveInstallArgs(InstallParams params) { 12071 super(params.origin, params.move, params.observer, params.installFlags, 12072 params.installerPackageName, params.volumeUuid, 12073 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12074 params.grantedRuntimePermissions, 12075 params.traceMethod, params.traceCookie); 12076 } 12077 12078 int copyApk(IMediaContainerService imcs, boolean temp) { 12079 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12080 + move.fromUuid + " to " + move.toUuid); 12081 synchronized (mInstaller) { 12082 if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12083 move.dataAppName, move.appId, move.seinfo) != 0) { 12084 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12085 } 12086 } 12087 12088 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12089 resourceFile = codeFile; 12090 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12091 12092 return PackageManager.INSTALL_SUCCEEDED; 12093 } 12094 12095 int doPreInstall(int status) { 12096 if (status != PackageManager.INSTALL_SUCCEEDED) { 12097 cleanUp(move.toUuid); 12098 } 12099 return status; 12100 } 12101 12102 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12103 if (status != PackageManager.INSTALL_SUCCEEDED) { 12104 cleanUp(move.toUuid); 12105 return false; 12106 } 12107 12108 // Reflect the move in app info 12109 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12110 pkg.applicationInfo.setCodePath(pkg.codePath); 12111 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12112 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12113 pkg.applicationInfo.setResourcePath(pkg.codePath); 12114 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12115 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12116 12117 return true; 12118 } 12119 12120 int doPostInstall(int status, int uid) { 12121 if (status == PackageManager.INSTALL_SUCCEEDED) { 12122 cleanUp(move.fromUuid); 12123 } else { 12124 cleanUp(move.toUuid); 12125 } 12126 return status; 12127 } 12128 12129 @Override 12130 String getCodePath() { 12131 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12132 } 12133 12134 @Override 12135 String getResourcePath() { 12136 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12137 } 12138 12139 private boolean cleanUp(String volumeUuid) { 12140 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12141 move.dataAppName); 12142 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12143 synchronized (mInstallLock) { 12144 // Clean up both app data and code 12145 removeDataDirsLI(volumeUuid, move.packageName); 12146 if (codeFile.isDirectory()) { 12147 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 12148 } else { 12149 codeFile.delete(); 12150 } 12151 } 12152 return true; 12153 } 12154 12155 void cleanUpResourcesLI() { 12156 throw new UnsupportedOperationException(); 12157 } 12158 12159 boolean doPostDeleteLI(boolean delete) { 12160 throw new UnsupportedOperationException(); 12161 } 12162 } 12163 12164 static String getAsecPackageName(String packageCid) { 12165 int idx = packageCid.lastIndexOf("-"); 12166 if (idx == -1) { 12167 return packageCid; 12168 } 12169 return packageCid.substring(0, idx); 12170 } 12171 12172 // Utility method used to create code paths based on package name and available index. 12173 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12174 String idxStr = ""; 12175 int idx = 1; 12176 // Fall back to default value of idx=1 if prefix is not 12177 // part of oldCodePath 12178 if (oldCodePath != null) { 12179 String subStr = oldCodePath; 12180 // Drop the suffix right away 12181 if (suffix != null && subStr.endsWith(suffix)) { 12182 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12183 } 12184 // If oldCodePath already contains prefix find out the 12185 // ending index to either increment or decrement. 12186 int sidx = subStr.lastIndexOf(prefix); 12187 if (sidx != -1) { 12188 subStr = subStr.substring(sidx + prefix.length()); 12189 if (subStr != null) { 12190 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12191 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12192 } 12193 try { 12194 idx = Integer.parseInt(subStr); 12195 if (idx <= 1) { 12196 idx++; 12197 } else { 12198 idx--; 12199 } 12200 } catch(NumberFormatException e) { 12201 } 12202 } 12203 } 12204 } 12205 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12206 return prefix + idxStr; 12207 } 12208 12209 private File getNextCodePath(File targetDir, String packageName) { 12210 int suffix = 1; 12211 File result; 12212 do { 12213 result = new File(targetDir, packageName + "-" + suffix); 12214 suffix++; 12215 } while (result.exists()); 12216 return result; 12217 } 12218 12219 // Utility method that returns the relative package path with respect 12220 // to the installation directory. Like say for /data/data/com.test-1.apk 12221 // string com.test-1 is returned. 12222 static String deriveCodePathName(String codePath) { 12223 if (codePath == null) { 12224 return null; 12225 } 12226 final File codeFile = new File(codePath); 12227 final String name = codeFile.getName(); 12228 if (codeFile.isDirectory()) { 12229 return name; 12230 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12231 final int lastDot = name.lastIndexOf('.'); 12232 return name.substring(0, lastDot); 12233 } else { 12234 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12235 return null; 12236 } 12237 } 12238 12239 static class PackageInstalledInfo { 12240 String name; 12241 int uid; 12242 // The set of users that originally had this package installed. 12243 int[] origUsers; 12244 // The set of users that now have this package installed. 12245 int[] newUsers; 12246 PackageParser.Package pkg; 12247 int returnCode; 12248 String returnMsg; 12249 PackageRemovedInfo removedInfo; 12250 12251 public void setError(int code, String msg) { 12252 returnCode = code; 12253 returnMsg = msg; 12254 Slog.w(TAG, msg); 12255 } 12256 12257 public void setError(String msg, PackageParserException e) { 12258 returnCode = e.error; 12259 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12260 Slog.w(TAG, msg, e); 12261 } 12262 12263 public void setError(String msg, PackageManagerException e) { 12264 returnCode = e.error; 12265 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12266 Slog.w(TAG, msg, e); 12267 } 12268 12269 // In some error cases we want to convey more info back to the observer 12270 String origPackage; 12271 String origPermission; 12272 } 12273 12274 /* 12275 * Install a non-existing package. 12276 */ 12277 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12278 UserHandle user, String installerPackageName, String volumeUuid, 12279 PackageInstalledInfo res) { 12280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12281 12282 // Remember this for later, in case we need to rollback this install 12283 String pkgName = pkg.packageName; 12284 12285 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12286 // TODO: b/23350563 12287 final boolean dataDirExists = Environment 12288 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12289 12290 synchronized(mPackages) { 12291 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12292 // A package with the same name is already installed, though 12293 // it has been renamed to an older name. The package we 12294 // are trying to install should be installed as an update to 12295 // the existing one, but that has not been requested, so bail. 12296 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12297 + " without first uninstalling package running as " 12298 + mSettings.mRenamedPackages.get(pkgName)); 12299 return; 12300 } 12301 if (mPackages.containsKey(pkgName)) { 12302 // Don't allow installation over an existing package with the same name. 12303 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12304 + " without first uninstalling."); 12305 return; 12306 } 12307 } 12308 12309 try { 12310 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12311 System.currentTimeMillis(), user); 12312 12313 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12314 // delete the partially installed application. the data directory will have to be 12315 // restored if it was already existing 12316 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12317 // remove package from internal structures. Note that we want deletePackageX to 12318 // delete the package data and cache directories that it created in 12319 // scanPackageLocked, unless those directories existed before we even tried to 12320 // install. 12321 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12322 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12323 res.removedInfo, true); 12324 } 12325 12326 } catch (PackageManagerException e) { 12327 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12328 } 12329 12330 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12331 } 12332 12333 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12334 // Can't rotate keys during boot or if sharedUser. 12335 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12336 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12337 return false; 12338 } 12339 // app is using upgradeKeySets; make sure all are valid 12340 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12341 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12342 for (int i = 0; i < upgradeKeySets.length; i++) { 12343 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12344 Slog.wtf(TAG, "Package " 12345 + (oldPs.name != null ? oldPs.name : "<null>") 12346 + " contains upgrade-key-set reference to unknown key-set: " 12347 + upgradeKeySets[i] 12348 + " reverting to signatures check."); 12349 return false; 12350 } 12351 } 12352 return true; 12353 } 12354 12355 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12356 // Upgrade keysets are being used. Determine if new package has a superset of the 12357 // required keys. 12358 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12359 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12360 for (int i = 0; i < upgradeKeySets.length; i++) { 12361 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12362 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12363 return true; 12364 } 12365 } 12366 return false; 12367 } 12368 12369 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12370 UserHandle user, String installerPackageName, String volumeUuid, 12371 PackageInstalledInfo res) { 12372 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12373 12374 final PackageParser.Package oldPackage; 12375 final String pkgName = pkg.packageName; 12376 final int[] allUsers; 12377 final boolean[] perUserInstalled; 12378 12379 // First find the old package info and check signatures 12380 synchronized(mPackages) { 12381 oldPackage = mPackages.get(pkgName); 12382 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12383 if (isEphemeral && !oldIsEphemeral) { 12384 // can't downgrade from full to ephemeral 12385 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12386 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12387 return; 12388 } 12389 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12390 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12391 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12392 if(!checkUpgradeKeySetLP(ps, pkg)) { 12393 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12394 "New package not signed by keys specified by upgrade-keysets: " 12395 + pkgName); 12396 return; 12397 } 12398 } else { 12399 // default to original signature matching 12400 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12401 != PackageManager.SIGNATURE_MATCH) { 12402 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12403 "New package has a different signature: " + pkgName); 12404 return; 12405 } 12406 } 12407 12408 // In case of rollback, remember per-user/profile install state 12409 allUsers = sUserManager.getUserIds(); 12410 perUserInstalled = new boolean[allUsers.length]; 12411 for (int i = 0; i < allUsers.length; i++) { 12412 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12413 } 12414 } 12415 12416 boolean sysPkg = (isSystemApp(oldPackage)); 12417 if (sysPkg) { 12418 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12419 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12420 } else { 12421 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12422 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12423 } 12424 } 12425 12426 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12427 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12428 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12429 String volumeUuid, PackageInstalledInfo res) { 12430 String pkgName = deletedPackage.packageName; 12431 boolean deletedPkg = true; 12432 boolean updatedSettings = false; 12433 12434 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12435 + deletedPackage); 12436 long origUpdateTime; 12437 if (pkg.mExtras != null) { 12438 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12439 } else { 12440 origUpdateTime = 0; 12441 } 12442 12443 // First delete the existing package while retaining the data directory 12444 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12445 res.removedInfo, true)) { 12446 // If the existing package wasn't successfully deleted 12447 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12448 deletedPkg = false; 12449 } else { 12450 // Successfully deleted the old package; proceed with replace. 12451 12452 // If deleted package lived in a container, give users a chance to 12453 // relinquish resources before killing. 12454 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12455 if (DEBUG_INSTALL) { 12456 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12457 } 12458 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12459 final ArrayList<String> pkgList = new ArrayList<String>(1); 12460 pkgList.add(deletedPackage.applicationInfo.packageName); 12461 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12462 } 12463 12464 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12465 try { 12466 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12467 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12468 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12469 perUserInstalled, res, user); 12470 updatedSettings = true; 12471 } catch (PackageManagerException e) { 12472 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12473 } 12474 } 12475 12476 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12477 // remove package from internal structures. Note that we want deletePackageX to 12478 // delete the package data and cache directories that it created in 12479 // scanPackageLocked, unless those directories existed before we even tried to 12480 // install. 12481 if(updatedSettings) { 12482 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12483 deletePackageLI( 12484 pkgName, null, true, allUsers, perUserInstalled, 12485 PackageManager.DELETE_KEEP_DATA, 12486 res.removedInfo, true); 12487 } 12488 // Since we failed to install the new package we need to restore the old 12489 // package that we deleted. 12490 if (deletedPkg) { 12491 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12492 File restoreFile = new File(deletedPackage.codePath); 12493 // Parse old package 12494 boolean oldExternal = isExternal(deletedPackage); 12495 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12496 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12497 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12498 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12499 try { 12500 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12501 null); 12502 } catch (PackageManagerException e) { 12503 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12504 + e.getMessage()); 12505 return; 12506 } 12507 // Restore of old package succeeded. Update permissions. 12508 // writer 12509 synchronized (mPackages) { 12510 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12511 UPDATE_PERMISSIONS_ALL); 12512 // can downgrade to reader 12513 mSettings.writeLPr(); 12514 } 12515 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12516 } 12517 } 12518 } 12519 12520 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12521 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12522 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12523 String volumeUuid, PackageInstalledInfo res) { 12524 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12525 + ", old=" + deletedPackage); 12526 boolean disabledSystem = false; 12527 boolean updatedSettings = false; 12528 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12529 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12530 != 0) { 12531 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12532 } 12533 String packageName = deletedPackage.packageName; 12534 if (packageName == null) { 12535 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12536 "Attempt to delete null packageName."); 12537 return; 12538 } 12539 PackageParser.Package oldPkg; 12540 PackageSetting oldPkgSetting; 12541 // reader 12542 synchronized (mPackages) { 12543 oldPkg = mPackages.get(packageName); 12544 oldPkgSetting = mSettings.mPackages.get(packageName); 12545 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12546 (oldPkgSetting == null)) { 12547 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12548 "Couldn't find package " + packageName + " information"); 12549 return; 12550 } 12551 } 12552 12553 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12554 12555 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12556 res.removedInfo.removedPackage = packageName; 12557 // Remove existing system package 12558 removePackageLI(oldPkgSetting, true); 12559 // writer 12560 synchronized (mPackages) { 12561 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12562 if (!disabledSystem && deletedPackage != null) { 12563 // We didn't need to disable the .apk as a current system package, 12564 // which means we are replacing another update that is already 12565 // installed. We need to make sure to delete the older one's .apk. 12566 res.removedInfo.args = createInstallArgsForExisting(0, 12567 deletedPackage.applicationInfo.getCodePath(), 12568 deletedPackage.applicationInfo.getResourcePath(), 12569 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12570 } else { 12571 res.removedInfo.args = null; 12572 } 12573 } 12574 12575 // Successfully disabled the old package. Now proceed with re-installation 12576 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12577 12578 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12579 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12580 12581 PackageParser.Package newPackage = null; 12582 try { 12583 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12584 if (newPackage.mExtras != null) { 12585 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12586 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12587 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12588 12589 // is the update attempting to change shared user? that isn't going to work... 12590 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12591 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12592 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12593 + " to " + newPkgSetting.sharedUser); 12594 updatedSettings = true; 12595 } 12596 } 12597 12598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12599 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12600 perUserInstalled, res, user); 12601 updatedSettings = true; 12602 } 12603 12604 } catch (PackageManagerException e) { 12605 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12606 } 12607 12608 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12609 // Re installation failed. Restore old information 12610 // Remove new pkg information 12611 if (newPackage != null) { 12612 removeInstalledPackageLI(newPackage, true); 12613 } 12614 // Add back the old system package 12615 try { 12616 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12617 } catch (PackageManagerException e) { 12618 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12619 } 12620 // Restore the old system information in Settings 12621 synchronized (mPackages) { 12622 if (disabledSystem) { 12623 mSettings.enableSystemPackageLPw(packageName); 12624 } 12625 if (updatedSettings) { 12626 mSettings.setInstallerPackageName(packageName, 12627 oldPkgSetting.installerPackageName); 12628 } 12629 mSettings.writeLPr(); 12630 } 12631 } 12632 } 12633 12634 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12635 // Collect all used permissions in the UID 12636 ArraySet<String> usedPermissions = new ArraySet<>(); 12637 final int packageCount = su.packages.size(); 12638 for (int i = 0; i < packageCount; i++) { 12639 PackageSetting ps = su.packages.valueAt(i); 12640 if (ps.pkg == null) { 12641 continue; 12642 } 12643 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12644 for (int j = 0; j < requestedPermCount; j++) { 12645 String permission = ps.pkg.requestedPermissions.get(j); 12646 BasePermission bp = mSettings.mPermissions.get(permission); 12647 if (bp != null) { 12648 usedPermissions.add(permission); 12649 } 12650 } 12651 } 12652 12653 PermissionsState permissionsState = su.getPermissionsState(); 12654 // Prune install permissions 12655 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12656 final int installPermCount = installPermStates.size(); 12657 for (int i = installPermCount - 1; i >= 0; i--) { 12658 PermissionState permissionState = installPermStates.get(i); 12659 if (!usedPermissions.contains(permissionState.getName())) { 12660 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12661 if (bp != null) { 12662 permissionsState.revokeInstallPermission(bp); 12663 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12664 PackageManager.MASK_PERMISSION_FLAGS, 0); 12665 } 12666 } 12667 } 12668 12669 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12670 12671 // Prune runtime permissions 12672 for (int userId : allUserIds) { 12673 List<PermissionState> runtimePermStates = permissionsState 12674 .getRuntimePermissionStates(userId); 12675 final int runtimePermCount = runtimePermStates.size(); 12676 for (int i = runtimePermCount - 1; i >= 0; i--) { 12677 PermissionState permissionState = runtimePermStates.get(i); 12678 if (!usedPermissions.contains(permissionState.getName())) { 12679 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12680 if (bp != null) { 12681 permissionsState.revokeRuntimePermission(bp, userId); 12682 permissionsState.updatePermissionFlags(bp, userId, 12683 PackageManager.MASK_PERMISSION_FLAGS, 0); 12684 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12685 runtimePermissionChangedUserIds, userId); 12686 } 12687 } 12688 } 12689 } 12690 12691 return runtimePermissionChangedUserIds; 12692 } 12693 12694 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12695 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12696 UserHandle user) { 12697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12698 12699 String pkgName = newPackage.packageName; 12700 synchronized (mPackages) { 12701 //write settings. the installStatus will be incomplete at this stage. 12702 //note that the new package setting would have already been 12703 //added to mPackages. It hasn't been persisted yet. 12704 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12705 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12706 mSettings.writeLPr(); 12707 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12708 } 12709 12710 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12711 synchronized (mPackages) { 12712 updatePermissionsLPw(newPackage.packageName, newPackage, 12713 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12714 ? UPDATE_PERMISSIONS_ALL : 0)); 12715 // For system-bundled packages, we assume that installing an upgraded version 12716 // of the package implies that the user actually wants to run that new code, 12717 // so we enable the package. 12718 PackageSetting ps = mSettings.mPackages.get(pkgName); 12719 if (ps != null) { 12720 if (isSystemApp(newPackage)) { 12721 // NB: implicit assumption that system package upgrades apply to all users 12722 if (DEBUG_INSTALL) { 12723 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12724 } 12725 if (res.origUsers != null) { 12726 for (int userHandle : res.origUsers) { 12727 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12728 userHandle, installerPackageName); 12729 } 12730 } 12731 // Also convey the prior install/uninstall state 12732 if (allUsers != null && perUserInstalled != null) { 12733 for (int i = 0; i < allUsers.length; i++) { 12734 if (DEBUG_INSTALL) { 12735 Slog.d(TAG, " user " + allUsers[i] 12736 + " => " + perUserInstalled[i]); 12737 } 12738 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12739 } 12740 // these install state changes will be persisted in the 12741 // upcoming call to mSettings.writeLPr(). 12742 } 12743 } 12744 // It's implied that when a user requests installation, they want the app to be 12745 // installed and enabled. 12746 int userId = user.getIdentifier(); 12747 if (userId != UserHandle.USER_ALL) { 12748 ps.setInstalled(true, userId); 12749 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12750 } 12751 } 12752 res.name = pkgName; 12753 res.uid = newPackage.applicationInfo.uid; 12754 res.pkg = newPackage; 12755 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12756 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12757 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12758 //to update install status 12759 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12760 mSettings.writeLPr(); 12761 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12762 } 12763 12764 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12765 } 12766 12767 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12768 try { 12769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12770 installPackageLI(args, res); 12771 } finally { 12772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12773 } 12774 } 12775 12776 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12777 final int installFlags = args.installFlags; 12778 final String installerPackageName = args.installerPackageName; 12779 final String volumeUuid = args.volumeUuid; 12780 final File tmpPackageFile = new File(args.getCodePath()); 12781 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12782 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12783 || (args.volumeUuid != null)); 12784 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12785 boolean replace = false; 12786 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12787 if (args.move != null) { 12788 // moving a complete application; perfom an initial scan on the new install location 12789 scanFlags |= SCAN_INITIAL; 12790 } 12791 // Result object to be returned 12792 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12793 12794 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12795 12796 // Sanity check 12797 if (ephemeral && (forwardLocked || onExternal)) { 12798 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12799 + " external=" + onExternal); 12800 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12801 return; 12802 } 12803 12804 // Retrieve PackageSettings and parse package 12805 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12806 | PackageParser.PARSE_ENFORCE_CODE 12807 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12808 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12809 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12810 PackageParser pp = new PackageParser(); 12811 pp.setSeparateProcesses(mSeparateProcesses); 12812 pp.setDisplayMetrics(mMetrics); 12813 12814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12815 final PackageParser.Package pkg; 12816 try { 12817 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12818 } catch (PackageParserException e) { 12819 res.setError("Failed parse during installPackageLI", e); 12820 return; 12821 } finally { 12822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12823 } 12824 12825 // Mark that we have an install time CPU ABI override. 12826 pkg.cpuAbiOverride = args.abiOverride; 12827 12828 String pkgName = res.name = pkg.packageName; 12829 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12830 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12831 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12832 return; 12833 } 12834 } 12835 12836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12837 try { 12838 pp.collectCertificates(pkg, parseFlags); 12839 } catch (PackageParserException e) { 12840 res.setError("Failed collect during installPackageLI", e); 12841 return; 12842 } finally { 12843 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12844 } 12845 12846 // Get rid of all references to package scan path via parser. 12847 pp = null; 12848 String oldCodePath = null; 12849 boolean systemApp = false; 12850 synchronized (mPackages) { 12851 // Check if installing already existing package 12852 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12853 String oldName = mSettings.mRenamedPackages.get(pkgName); 12854 if (pkg.mOriginalPackages != null 12855 && pkg.mOriginalPackages.contains(oldName) 12856 && mPackages.containsKey(oldName)) { 12857 // This package is derived from an original package, 12858 // and this device has been updating from that original 12859 // name. We must continue using the original name, so 12860 // rename the new package here. 12861 pkg.setPackageName(oldName); 12862 pkgName = pkg.packageName; 12863 replace = true; 12864 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12865 + oldName + " pkgName=" + pkgName); 12866 } else if (mPackages.containsKey(pkgName)) { 12867 // This package, under its official name, already exists 12868 // on the device; we should replace it. 12869 replace = true; 12870 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12871 } 12872 12873 // Prevent apps opting out from runtime permissions 12874 if (replace) { 12875 PackageParser.Package oldPackage = mPackages.get(pkgName); 12876 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12877 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12878 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12879 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12880 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12881 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12882 + " doesn't support runtime permissions but the old" 12883 + " target SDK " + oldTargetSdk + " does."); 12884 return; 12885 } 12886 } 12887 } 12888 12889 PackageSetting ps = mSettings.mPackages.get(pkgName); 12890 if (ps != null) { 12891 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12892 12893 // Quick sanity check that we're signed correctly if updating; 12894 // we'll check this again later when scanning, but we want to 12895 // bail early here before tripping over redefined permissions. 12896 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12897 if (!checkUpgradeKeySetLP(ps, pkg)) { 12898 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12899 + pkg.packageName + " upgrade keys do not match the " 12900 + "previously installed version"); 12901 return; 12902 } 12903 } else { 12904 try { 12905 verifySignaturesLP(ps, pkg); 12906 } catch (PackageManagerException e) { 12907 res.setError(e.error, e.getMessage()); 12908 return; 12909 } 12910 } 12911 12912 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12913 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12914 systemApp = (ps.pkg.applicationInfo.flags & 12915 ApplicationInfo.FLAG_SYSTEM) != 0; 12916 } 12917 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12918 } 12919 12920 // Check whether the newly-scanned package wants to define an already-defined perm 12921 int N = pkg.permissions.size(); 12922 for (int i = N-1; i >= 0; i--) { 12923 PackageParser.Permission perm = pkg.permissions.get(i); 12924 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12925 if (bp != null) { 12926 // If the defining package is signed with our cert, it's okay. This 12927 // also includes the "updating the same package" case, of course. 12928 // "updating same package" could also involve key-rotation. 12929 final boolean sigsOk; 12930 if (bp.sourcePackage.equals(pkg.packageName) 12931 && (bp.packageSetting instanceof PackageSetting) 12932 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12933 scanFlags))) { 12934 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12935 } else { 12936 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12937 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12938 } 12939 if (!sigsOk) { 12940 // If the owning package is the system itself, we log but allow 12941 // install to proceed; we fail the install on all other permission 12942 // redefinitions. 12943 if (!bp.sourcePackage.equals("android")) { 12944 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12945 + pkg.packageName + " attempting to redeclare permission " 12946 + perm.info.name + " already owned by " + bp.sourcePackage); 12947 res.origPermission = perm.info.name; 12948 res.origPackage = bp.sourcePackage; 12949 return; 12950 } else { 12951 Slog.w(TAG, "Package " + pkg.packageName 12952 + " attempting to redeclare system permission " 12953 + perm.info.name + "; ignoring new declaration"); 12954 pkg.permissions.remove(i); 12955 } 12956 } 12957 } 12958 } 12959 12960 } 12961 12962 if (systemApp) { 12963 if (onExternal) { 12964 // Abort update; system app can't be replaced with app on sdcard 12965 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12966 "Cannot install updates to system apps on sdcard"); 12967 return; 12968 } else if (ephemeral) { 12969 // Abort update; system app can't be replaced with an ephemeral app 12970 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12971 "Cannot update a system app with an ephemeral app"); 12972 return; 12973 } 12974 } 12975 12976 if (args.move != null) { 12977 // We did an in-place move, so dex is ready to roll 12978 scanFlags |= SCAN_NO_DEX; 12979 scanFlags |= SCAN_MOVE; 12980 12981 synchronized (mPackages) { 12982 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12983 if (ps == null) { 12984 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 12985 "Missing settings for moved package " + pkgName); 12986 } 12987 12988 // We moved the entire application as-is, so bring over the 12989 // previously derived ABI information. 12990 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 12991 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 12992 } 12993 12994 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 12995 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 12996 scanFlags |= SCAN_NO_DEX; 12997 12998 try { 12999 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 13000 true /* extract libs */); 13001 } catch (PackageManagerException pme) { 13002 Slog.e(TAG, "Error deriving application ABI", pme); 13003 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13004 return; 13005 } 13006 } 13007 13008 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13009 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13010 return; 13011 } 13012 13013 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13014 13015 if (replace) { 13016 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13017 installerPackageName, volumeUuid, res); 13018 } else { 13019 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13020 args.user, installerPackageName, volumeUuid, res); 13021 } 13022 synchronized (mPackages) { 13023 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13024 if (ps != null) { 13025 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13026 } 13027 } 13028 } 13029 13030 private void startIntentFilterVerifications(int userId, boolean replacing, 13031 PackageParser.Package pkg) { 13032 if (mIntentFilterVerifierComponent == null) { 13033 Slog.w(TAG, "No IntentFilter verification will not be done as " 13034 + "there is no IntentFilterVerifier available!"); 13035 return; 13036 } 13037 13038 final int verifierUid = getPackageUid( 13039 mIntentFilterVerifierComponent.getPackageName(), 13040 MATCH_DEBUG_TRIAGED_MISSING, 13041 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13042 13043 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13044 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13045 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13046 mHandler.sendMessage(msg); 13047 } 13048 13049 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13050 PackageParser.Package pkg) { 13051 int size = pkg.activities.size(); 13052 if (size == 0) { 13053 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13054 "No activity, so no need to verify any IntentFilter!"); 13055 return; 13056 } 13057 13058 final boolean hasDomainURLs = hasDomainURLs(pkg); 13059 if (!hasDomainURLs) { 13060 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13061 "No domain URLs, so no need to verify any IntentFilter!"); 13062 return; 13063 } 13064 13065 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13066 + " if any IntentFilter from the " + size 13067 + " Activities needs verification ..."); 13068 13069 int count = 0; 13070 final String packageName = pkg.packageName; 13071 13072 synchronized (mPackages) { 13073 // If this is a new install and we see that we've already run verification for this 13074 // package, we have nothing to do: it means the state was restored from backup. 13075 if (!replacing) { 13076 IntentFilterVerificationInfo ivi = 13077 mSettings.getIntentFilterVerificationLPr(packageName); 13078 if (ivi != null) { 13079 if (DEBUG_DOMAIN_VERIFICATION) { 13080 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13081 + ivi.getStatusString()); 13082 } 13083 return; 13084 } 13085 } 13086 13087 // If any filters need to be verified, then all need to be. 13088 boolean needToVerify = false; 13089 for (PackageParser.Activity a : pkg.activities) { 13090 for (ActivityIntentInfo filter : a.intents) { 13091 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13092 if (DEBUG_DOMAIN_VERIFICATION) { 13093 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13094 } 13095 needToVerify = true; 13096 break; 13097 } 13098 } 13099 } 13100 13101 if (needToVerify) { 13102 final int verificationId = mIntentFilterVerificationToken++; 13103 for (PackageParser.Activity a : pkg.activities) { 13104 for (ActivityIntentInfo filter : a.intents) { 13105 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13106 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13107 "Verification needed for IntentFilter:" + filter.toString()); 13108 mIntentFilterVerifier.addOneIntentFilterVerification( 13109 verifierUid, userId, verificationId, filter, packageName); 13110 count++; 13111 } 13112 } 13113 } 13114 } 13115 } 13116 13117 if (count > 0) { 13118 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13119 + " IntentFilter verification" + (count > 1 ? "s" : "") 13120 + " for userId:" + userId); 13121 mIntentFilterVerifier.startVerifications(userId); 13122 } else { 13123 if (DEBUG_DOMAIN_VERIFICATION) { 13124 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13125 } 13126 } 13127 } 13128 13129 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13130 final ComponentName cn = filter.activity.getComponentName(); 13131 final String packageName = cn.getPackageName(); 13132 13133 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13134 packageName); 13135 if (ivi == null) { 13136 return true; 13137 } 13138 int status = ivi.getStatus(); 13139 switch (status) { 13140 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13141 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13142 return true; 13143 13144 default: 13145 // Nothing to do 13146 return false; 13147 } 13148 } 13149 13150 private static boolean isMultiArch(ApplicationInfo info) { 13151 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13152 } 13153 13154 private static boolean isExternal(PackageParser.Package pkg) { 13155 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13156 } 13157 13158 private static boolean isExternal(PackageSetting ps) { 13159 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13160 } 13161 13162 private static boolean isEphemeral(PackageParser.Package pkg) { 13163 return pkg.applicationInfo.isEphemeralApp(); 13164 } 13165 13166 private static boolean isEphemeral(PackageSetting ps) { 13167 return ps.pkg != null && isEphemeral(ps.pkg); 13168 } 13169 13170 private static boolean isSystemApp(PackageParser.Package pkg) { 13171 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13172 } 13173 13174 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13175 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13176 } 13177 13178 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13179 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13180 } 13181 13182 private static boolean isSystemApp(PackageSetting ps) { 13183 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13184 } 13185 13186 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13187 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13188 } 13189 13190 private int packageFlagsToInstallFlags(PackageSetting ps) { 13191 int installFlags = 0; 13192 if (isEphemeral(ps)) { 13193 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13194 } 13195 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13196 // This existing package was an external ASEC install when we have 13197 // the external flag without a UUID 13198 installFlags |= PackageManager.INSTALL_EXTERNAL; 13199 } 13200 if (ps.isForwardLocked()) { 13201 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13202 } 13203 return installFlags; 13204 } 13205 13206 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13207 if (isExternal(pkg)) { 13208 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13209 return StorageManager.UUID_PRIMARY_PHYSICAL; 13210 } else { 13211 return pkg.volumeUuid; 13212 } 13213 } else { 13214 return StorageManager.UUID_PRIVATE_INTERNAL; 13215 } 13216 } 13217 13218 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13219 if (isExternal(pkg)) { 13220 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13221 return mSettings.getExternalVersion(); 13222 } else { 13223 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13224 } 13225 } else { 13226 return mSettings.getInternalVersion(); 13227 } 13228 } 13229 13230 private void deleteTempPackageFiles() { 13231 final FilenameFilter filter = new FilenameFilter() { 13232 public boolean accept(File dir, String name) { 13233 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13234 } 13235 }; 13236 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13237 file.delete(); 13238 } 13239 } 13240 13241 @Override 13242 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13243 int flags) { 13244 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13245 flags); 13246 } 13247 13248 @Override 13249 public void deletePackage(final String packageName, 13250 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13251 mContext.enforceCallingOrSelfPermission( 13252 android.Manifest.permission.DELETE_PACKAGES, null); 13253 Preconditions.checkNotNull(packageName); 13254 Preconditions.checkNotNull(observer); 13255 final int uid = Binder.getCallingUid(); 13256 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13257 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13258 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13259 mContext.enforceCallingOrSelfPermission( 13260 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13261 "deletePackage for user " + userId); 13262 } 13263 13264 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13265 try { 13266 observer.onPackageDeleted(packageName, 13267 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13268 } catch (RemoteException re) { 13269 } 13270 return; 13271 } 13272 13273 for (int currentUserId : users) { 13274 if (getBlockUninstallForUser(packageName, currentUserId)) { 13275 try { 13276 observer.onPackageDeleted(packageName, 13277 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13278 } catch (RemoteException re) { 13279 } 13280 return; 13281 } 13282 } 13283 13284 if (DEBUG_REMOVE) { 13285 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13286 } 13287 // Queue up an async operation since the package deletion may take a little while. 13288 mHandler.post(new Runnable() { 13289 public void run() { 13290 mHandler.removeCallbacks(this); 13291 final int returnCode = deletePackageX(packageName, userId, flags); 13292 try { 13293 observer.onPackageDeleted(packageName, returnCode, null); 13294 } catch (RemoteException e) { 13295 Log.i(TAG, "Observer no longer exists."); 13296 } //end catch 13297 } //end run 13298 }); 13299 } 13300 13301 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13302 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13303 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13304 try { 13305 if (dpm != null) { 13306 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13307 /* callingUserOnly =*/ false); 13308 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13309 : deviceOwnerComponentName.getPackageName(); 13310 // Does the package contains the device owner? 13311 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13312 // this check is probably not needed, since DO should be registered as a device 13313 // admin on some user too. (Original bug for this: b/17657954) 13314 if (packageName.equals(deviceOwnerPackageName)) { 13315 return true; 13316 } 13317 // Does it contain a device admin for any user? 13318 int[] users; 13319 if (userId == UserHandle.USER_ALL) { 13320 users = sUserManager.getUserIds(); 13321 } else { 13322 users = new int[]{userId}; 13323 } 13324 for (int i = 0; i < users.length; ++i) { 13325 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13326 return true; 13327 } 13328 } 13329 } 13330 } catch (RemoteException e) { 13331 } 13332 return false; 13333 } 13334 13335 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13336 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13337 } 13338 13339 /** 13340 * This method is an internal method that could be get invoked either 13341 * to delete an installed package or to clean up a failed installation. 13342 * After deleting an installed package, a broadcast is sent to notify any 13343 * listeners that the package has been installed. For cleaning up a failed 13344 * installation, the broadcast is not necessary since the package's 13345 * installation wouldn't have sent the initial broadcast either 13346 * The key steps in deleting a package are 13347 * deleting the package information in internal structures like mPackages, 13348 * deleting the packages base directories through installd 13349 * updating mSettings to reflect current status 13350 * persisting settings for later use 13351 * sending a broadcast if necessary 13352 */ 13353 private int deletePackageX(String packageName, int userId, int flags) { 13354 final PackageRemovedInfo info = new PackageRemovedInfo(); 13355 final boolean res; 13356 13357 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13358 ? UserHandle.ALL : new UserHandle(userId); 13359 13360 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13361 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13362 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13363 } 13364 13365 boolean removedForAllUsers = false; 13366 boolean systemUpdate = false; 13367 13368 PackageParser.Package uninstalledPkg; 13369 13370 // for the uninstall-updates case and restricted profiles, remember the per- 13371 // userhandle installed state 13372 int[] allUsers; 13373 boolean[] perUserInstalled; 13374 synchronized (mPackages) { 13375 uninstalledPkg = mPackages.get(packageName); 13376 PackageSetting ps = mSettings.mPackages.get(packageName); 13377 allUsers = sUserManager.getUserIds(); 13378 perUserInstalled = new boolean[allUsers.length]; 13379 for (int i = 0; i < allUsers.length; i++) { 13380 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13381 } 13382 } 13383 13384 synchronized (mInstallLock) { 13385 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13386 res = deletePackageLI(packageName, removeForUser, 13387 true, allUsers, perUserInstalled, 13388 flags | REMOVE_CHATTY, info, true); 13389 systemUpdate = info.isRemovedPackageSystemUpdate; 13390 synchronized (mPackages) { 13391 if (res) { 13392 if (!systemUpdate && mPackages.get(packageName) == null) { 13393 removedForAllUsers = true; 13394 } 13395 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13396 } 13397 } 13398 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13399 + " removedForAllUsers=" + removedForAllUsers); 13400 } 13401 13402 if (res) { 13403 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13404 13405 // If the removed package was a system update, the old system package 13406 // was re-enabled; we need to broadcast this information 13407 if (systemUpdate) { 13408 Bundle extras = new Bundle(1); 13409 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13410 ? info.removedAppId : info.uid); 13411 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13412 13413 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13414 extras, 0, null, null, null); 13415 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13416 extras, 0, null, null, null); 13417 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13418 null, 0, packageName, null, null); 13419 } 13420 } 13421 // Force a gc here. 13422 Runtime.getRuntime().gc(); 13423 // Delete the resources here after sending the broadcast to let 13424 // other processes clean up before deleting resources. 13425 if (info.args != null) { 13426 synchronized (mInstallLock) { 13427 info.args.doPostDeleteLI(true); 13428 } 13429 } 13430 13431 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13432 } 13433 13434 class PackageRemovedInfo { 13435 String removedPackage; 13436 int uid = -1; 13437 int removedAppId = -1; 13438 int[] removedUsers = null; 13439 boolean isRemovedPackageSystemUpdate = false; 13440 // Clean up resources deleted packages. 13441 InstallArgs args = null; 13442 13443 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13444 Bundle extras = new Bundle(1); 13445 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13446 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13447 if (replacing) { 13448 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13449 } 13450 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13451 if (removedPackage != null) { 13452 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13453 extras, 0, null, null, removedUsers); 13454 if (fullRemove && !replacing) { 13455 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13456 extras, 0, null, null, removedUsers); 13457 } 13458 } 13459 if (removedAppId >= 0) { 13460 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13461 removedUsers); 13462 } 13463 } 13464 } 13465 13466 /* 13467 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13468 * flag is not set, the data directory is removed as well. 13469 * make sure this flag is set for partially installed apps. If not its meaningless to 13470 * delete a partially installed application. 13471 */ 13472 private void removePackageDataLI(PackageSetting ps, 13473 int[] allUserHandles, boolean[] perUserInstalled, 13474 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13475 String packageName = ps.name; 13476 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13477 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13478 // Retrieve object to delete permissions for shared user later on 13479 final PackageSetting deletedPs; 13480 // reader 13481 synchronized (mPackages) { 13482 deletedPs = mSettings.mPackages.get(packageName); 13483 if (outInfo != null) { 13484 outInfo.removedPackage = packageName; 13485 outInfo.removedUsers = deletedPs != null 13486 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13487 : null; 13488 } 13489 } 13490 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13491 removeDataDirsLI(ps.volumeUuid, packageName); 13492 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13493 } 13494 // writer 13495 synchronized (mPackages) { 13496 if (deletedPs != null) { 13497 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13498 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13499 clearDefaultBrowserIfNeeded(packageName); 13500 if (outInfo != null) { 13501 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13502 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13503 } 13504 updatePermissionsLPw(deletedPs.name, null, 0); 13505 if (deletedPs.sharedUser != null) { 13506 // Remove permissions associated with package. Since runtime 13507 // permissions are per user we have to kill the removed package 13508 // or packages running under the shared user of the removed 13509 // package if revoking the permissions requested only by the removed 13510 // package is successful and this causes a change in gids. 13511 for (int userId : UserManagerService.getInstance().getUserIds()) { 13512 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13513 userId); 13514 if (userIdToKill == UserHandle.USER_ALL 13515 || userIdToKill >= UserHandle.USER_SYSTEM) { 13516 // If gids changed for this user, kill all affected packages. 13517 mHandler.post(new Runnable() { 13518 @Override 13519 public void run() { 13520 // This has to happen with no lock held. 13521 killApplication(deletedPs.name, deletedPs.appId, 13522 KILL_APP_REASON_GIDS_CHANGED); 13523 } 13524 }); 13525 break; 13526 } 13527 } 13528 } 13529 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13530 } 13531 // make sure to preserve per-user disabled state if this removal was just 13532 // a downgrade of a system app to the factory package 13533 if (allUserHandles != null && perUserInstalled != null) { 13534 if (DEBUG_REMOVE) { 13535 Slog.d(TAG, "Propagating install state across downgrade"); 13536 } 13537 for (int i = 0; i < allUserHandles.length; i++) { 13538 if (DEBUG_REMOVE) { 13539 Slog.d(TAG, " user " + allUserHandles[i] 13540 + " => " + perUserInstalled[i]); 13541 } 13542 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13543 } 13544 } 13545 } 13546 // can downgrade to reader 13547 if (writeSettings) { 13548 // Save settings now 13549 mSettings.writeLPr(); 13550 } 13551 } 13552 if (outInfo != null) { 13553 // A user ID was deleted here. Go through all users and remove it 13554 // from KeyStore. 13555 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13556 } 13557 } 13558 13559 static boolean locationIsPrivileged(File path) { 13560 try { 13561 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13562 .getCanonicalPath(); 13563 return path.getCanonicalPath().startsWith(privilegedAppDir); 13564 } catch (IOException e) { 13565 Slog.e(TAG, "Unable to access code path " + path); 13566 } 13567 return false; 13568 } 13569 13570 /* 13571 * Tries to delete system package. 13572 */ 13573 private boolean deleteSystemPackageLI(PackageSetting newPs, 13574 int[] allUserHandles, boolean[] perUserInstalled, 13575 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13576 final boolean applyUserRestrictions 13577 = (allUserHandles != null) && (perUserInstalled != null); 13578 PackageSetting disabledPs = null; 13579 // Confirm if the system package has been updated 13580 // An updated system app can be deleted. This will also have to restore 13581 // the system pkg from system partition 13582 // reader 13583 synchronized (mPackages) { 13584 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13585 } 13586 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13587 + " disabledPs=" + disabledPs); 13588 if (disabledPs == null) { 13589 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13590 return false; 13591 } else if (DEBUG_REMOVE) { 13592 Slog.d(TAG, "Deleting system pkg from data partition"); 13593 } 13594 if (DEBUG_REMOVE) { 13595 if (applyUserRestrictions) { 13596 Slog.d(TAG, "Remembering install states:"); 13597 for (int i = 0; i < allUserHandles.length; i++) { 13598 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13599 } 13600 } 13601 } 13602 // Delete the updated package 13603 outInfo.isRemovedPackageSystemUpdate = true; 13604 if (disabledPs.versionCode < newPs.versionCode) { 13605 // Delete data for downgrades 13606 flags &= ~PackageManager.DELETE_KEEP_DATA; 13607 } else { 13608 // Preserve data by setting flag 13609 flags |= PackageManager.DELETE_KEEP_DATA; 13610 } 13611 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13612 allUserHandles, perUserInstalled, outInfo, writeSettings); 13613 if (!ret) { 13614 return false; 13615 } 13616 // writer 13617 synchronized (mPackages) { 13618 // Reinstate the old system package 13619 mSettings.enableSystemPackageLPw(newPs.name); 13620 // Remove any native libraries from the upgraded package. 13621 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13622 } 13623 // Install the system package 13624 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13625 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13626 if (locationIsPrivileged(disabledPs.codePath)) { 13627 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13628 } 13629 13630 final PackageParser.Package newPkg; 13631 try { 13632 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13633 } catch (PackageManagerException e) { 13634 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13635 return false; 13636 } 13637 13638 // writer 13639 synchronized (mPackages) { 13640 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13641 13642 // Propagate the permissions state as we do not want to drop on the floor 13643 // runtime permissions. The update permissions method below will take 13644 // care of removing obsolete permissions and grant install permissions. 13645 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13646 updatePermissionsLPw(newPkg.packageName, newPkg, 13647 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13648 13649 if (applyUserRestrictions) { 13650 if (DEBUG_REMOVE) { 13651 Slog.d(TAG, "Propagating install state across reinstall"); 13652 } 13653 for (int i = 0; i < allUserHandles.length; i++) { 13654 if (DEBUG_REMOVE) { 13655 Slog.d(TAG, " user " + allUserHandles[i] 13656 + " => " + perUserInstalled[i]); 13657 } 13658 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13659 13660 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13661 } 13662 // Regardless of writeSettings we need to ensure that this restriction 13663 // state propagation is persisted 13664 mSettings.writeAllUsersPackageRestrictionsLPr(); 13665 } 13666 // can downgrade to reader here 13667 if (writeSettings) { 13668 mSettings.writeLPr(); 13669 } 13670 } 13671 return true; 13672 } 13673 13674 private boolean deleteInstalledPackageLI(PackageSetting ps, 13675 boolean deleteCodeAndResources, int flags, 13676 int[] allUserHandles, boolean[] perUserInstalled, 13677 PackageRemovedInfo outInfo, boolean writeSettings) { 13678 if (outInfo != null) { 13679 outInfo.uid = ps.appId; 13680 } 13681 13682 // Delete package data from internal structures and also remove data if flag is set 13683 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13684 13685 // Delete application code and resources 13686 if (deleteCodeAndResources && (outInfo != null)) { 13687 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13688 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13689 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13690 } 13691 return true; 13692 } 13693 13694 @Override 13695 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13696 int userId) { 13697 mContext.enforceCallingOrSelfPermission( 13698 android.Manifest.permission.DELETE_PACKAGES, null); 13699 synchronized (mPackages) { 13700 PackageSetting ps = mSettings.mPackages.get(packageName); 13701 if (ps == null) { 13702 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13703 return false; 13704 } 13705 if (!ps.getInstalled(userId)) { 13706 // Can't block uninstall for an app that is not installed or enabled. 13707 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13708 return false; 13709 } 13710 ps.setBlockUninstall(blockUninstall, userId); 13711 mSettings.writePackageRestrictionsLPr(userId); 13712 } 13713 return true; 13714 } 13715 13716 @Override 13717 public boolean getBlockUninstallForUser(String packageName, int userId) { 13718 synchronized (mPackages) { 13719 PackageSetting ps = mSettings.mPackages.get(packageName); 13720 if (ps == null) { 13721 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13722 return false; 13723 } 13724 return ps.getBlockUninstall(userId); 13725 } 13726 } 13727 13728 @Override 13729 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13730 int callingUid = Binder.getCallingUid(); 13731 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13732 throw new SecurityException( 13733 "setRequiredForSystemUser can only be run by the system or root"); 13734 } 13735 synchronized (mPackages) { 13736 PackageSetting ps = mSettings.mPackages.get(packageName); 13737 if (ps == null) { 13738 Log.w(TAG, "Package doesn't exist: " + packageName); 13739 return false; 13740 } 13741 if (systemUserApp) { 13742 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13743 } else { 13744 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13745 } 13746 mSettings.writeLPr(); 13747 } 13748 return true; 13749 } 13750 13751 /* 13752 * This method handles package deletion in general 13753 */ 13754 private boolean deletePackageLI(String packageName, UserHandle user, 13755 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13756 int flags, PackageRemovedInfo outInfo, 13757 boolean writeSettings) { 13758 if (packageName == null) { 13759 Slog.w(TAG, "Attempt to delete null packageName."); 13760 return false; 13761 } 13762 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13763 PackageSetting ps; 13764 boolean dataOnly = false; 13765 int removeUser = -1; 13766 int appId = -1; 13767 synchronized (mPackages) { 13768 ps = mSettings.mPackages.get(packageName); 13769 if (ps == null) { 13770 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13771 return false; 13772 } 13773 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13774 && user.getIdentifier() != UserHandle.USER_ALL) { 13775 // The caller is asking that the package only be deleted for a single 13776 // user. To do this, we just mark its uninstalled state and delete 13777 // its data. If this is a system app, we only allow this to happen if 13778 // they have set the special DELETE_SYSTEM_APP which requests different 13779 // semantics than normal for uninstalling system apps. 13780 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13781 final int userId = user.getIdentifier(); 13782 ps.setUserState(userId, 13783 COMPONENT_ENABLED_STATE_DEFAULT, 13784 false, //installed 13785 true, //stopped 13786 true, //notLaunched 13787 false, //hidden 13788 false, //suspended 13789 null, null, null, 13790 false, // blockUninstall 13791 ps.readUserState(userId).domainVerificationStatus, 0); 13792 if (!isSystemApp(ps)) { 13793 // Do not uninstall the APK if an app should be cached 13794 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13795 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13796 // Other user still have this package installed, so all 13797 // we need to do is clear this user's data and save that 13798 // it is uninstalled. 13799 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13800 removeUser = user.getIdentifier(); 13801 appId = ps.appId; 13802 scheduleWritePackageRestrictionsLocked(removeUser); 13803 } else { 13804 // We need to set it back to 'installed' so the uninstall 13805 // broadcasts will be sent correctly. 13806 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13807 ps.setInstalled(true, user.getIdentifier()); 13808 } 13809 } else { 13810 // This is a system app, so we assume that the 13811 // other users still have this package installed, so all 13812 // we need to do is clear this user's data and save that 13813 // it is uninstalled. 13814 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13815 removeUser = user.getIdentifier(); 13816 appId = ps.appId; 13817 scheduleWritePackageRestrictionsLocked(removeUser); 13818 } 13819 } 13820 } 13821 13822 if (removeUser >= 0) { 13823 // From above, we determined that we are deleting this only 13824 // for a single user. Continue the work here. 13825 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13826 if (outInfo != null) { 13827 outInfo.removedPackage = packageName; 13828 outInfo.removedAppId = appId; 13829 outInfo.removedUsers = new int[] {removeUser}; 13830 } 13831 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 13832 removeKeystoreDataIfNeeded(removeUser, appId); 13833 schedulePackageCleaning(packageName, removeUser, false); 13834 synchronized (mPackages) { 13835 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13836 scheduleWritePackageRestrictionsLocked(removeUser); 13837 } 13838 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13839 } 13840 return true; 13841 } 13842 13843 if (dataOnly) { 13844 // Delete application data first 13845 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13846 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13847 return true; 13848 } 13849 13850 boolean ret = false; 13851 if (isSystemApp(ps)) { 13852 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13853 // When an updated system application is deleted we delete the existing resources as well and 13854 // fall back to existing code in system partition 13855 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13856 flags, outInfo, writeSettings); 13857 } else { 13858 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13859 // Kill application pre-emptively especially for apps on sd. 13860 killApplication(packageName, ps.appId, "uninstall pkg"); 13861 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13862 allUserHandles, perUserInstalled, 13863 outInfo, writeSettings); 13864 } 13865 13866 return ret; 13867 } 13868 13869 private final static class ClearStorageConnection implements ServiceConnection { 13870 IMediaContainerService mContainerService; 13871 13872 @Override 13873 public void onServiceConnected(ComponentName name, IBinder service) { 13874 synchronized (this) { 13875 mContainerService = IMediaContainerService.Stub.asInterface(service); 13876 notifyAll(); 13877 } 13878 } 13879 13880 @Override 13881 public void onServiceDisconnected(ComponentName name) { 13882 } 13883 } 13884 13885 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13886 final boolean mounted; 13887 if (Environment.isExternalStorageEmulated()) { 13888 mounted = true; 13889 } else { 13890 final String status = Environment.getExternalStorageState(); 13891 13892 mounted = status.equals(Environment.MEDIA_MOUNTED) 13893 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13894 } 13895 13896 if (!mounted) { 13897 return; 13898 } 13899 13900 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13901 int[] users; 13902 if (userId == UserHandle.USER_ALL) { 13903 users = sUserManager.getUserIds(); 13904 } else { 13905 users = new int[] { userId }; 13906 } 13907 final ClearStorageConnection conn = new ClearStorageConnection(); 13908 if (mContext.bindServiceAsUser( 13909 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13910 try { 13911 for (int curUser : users) { 13912 long timeout = SystemClock.uptimeMillis() + 5000; 13913 synchronized (conn) { 13914 long now = SystemClock.uptimeMillis(); 13915 while (conn.mContainerService == null && now < timeout) { 13916 try { 13917 conn.wait(timeout - now); 13918 } catch (InterruptedException e) { 13919 } 13920 } 13921 } 13922 if (conn.mContainerService == null) { 13923 return; 13924 } 13925 13926 final UserEnvironment userEnv = new UserEnvironment(curUser); 13927 clearDirectory(conn.mContainerService, 13928 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13929 if (allData) { 13930 clearDirectory(conn.mContainerService, 13931 userEnv.buildExternalStorageAppDataDirs(packageName)); 13932 clearDirectory(conn.mContainerService, 13933 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13934 } 13935 } 13936 } finally { 13937 mContext.unbindService(conn); 13938 } 13939 } 13940 } 13941 13942 @Override 13943 public void clearApplicationUserData(final String packageName, 13944 final IPackageDataObserver observer, final int userId) { 13945 mContext.enforceCallingOrSelfPermission( 13946 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 13947 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 13948 // Queue up an async operation since the package deletion may take a little while. 13949 mHandler.post(new Runnable() { 13950 public void run() { 13951 mHandler.removeCallbacks(this); 13952 final boolean succeeded; 13953 synchronized (mInstallLock) { 13954 succeeded = clearApplicationUserDataLI(packageName, userId); 13955 } 13956 clearExternalStorageDataSync(packageName, userId, true); 13957 if (succeeded) { 13958 // invoke DeviceStorageMonitor's update method to clear any notifications 13959 DeviceStorageMonitorInternal 13960 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13961 if (dsm != null) { 13962 dsm.checkMemory(); 13963 } 13964 } 13965 if(observer != null) { 13966 try { 13967 observer.onRemoveCompleted(packageName, succeeded); 13968 } catch (RemoteException e) { 13969 Log.i(TAG, "Observer no longer exists."); 13970 } 13971 } //end if observer 13972 } //end run 13973 }); 13974 } 13975 13976 private boolean clearApplicationUserDataLI(String packageName, int userId) { 13977 if (packageName == null) { 13978 Slog.w(TAG, "Attempt to delete null packageName."); 13979 return false; 13980 } 13981 13982 // Try finding details about the requested package 13983 PackageParser.Package pkg; 13984 synchronized (mPackages) { 13985 pkg = mPackages.get(packageName); 13986 if (pkg == null) { 13987 final PackageSetting ps = mSettings.mPackages.get(packageName); 13988 if (ps != null) { 13989 pkg = ps.pkg; 13990 } 13991 } 13992 13993 if (pkg == null) { 13994 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13995 return false; 13996 } 13997 13998 PackageSetting ps = (PackageSetting) pkg.mExtras; 13999 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14000 } 14001 14002 // Always delete data directories for package, even if we found no other 14003 // record of app. This helps users recover from UID mismatches without 14004 // resorting to a full data wipe. 14005 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 14006 if (retCode < 0) { 14007 Slog.w(TAG, "Couldn't remove cache files for package " + packageName); 14008 return false; 14009 } 14010 14011 final int appId = pkg.applicationInfo.uid; 14012 removeKeystoreDataIfNeeded(userId, appId); 14013 14014 // Create a native library symlink only if we have native libraries 14015 // and if the native libraries are 32 bit libraries. We do not provide 14016 // this symlink for 64 bit libraries. 14017 if (pkg.applicationInfo.primaryCpuAbi != null && 14018 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14019 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14020 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14021 nativeLibPath, userId) < 0) { 14022 Slog.w(TAG, "Failed linking native library dir"); 14023 return false; 14024 } 14025 } 14026 14027 return true; 14028 } 14029 14030 /** 14031 * Reverts user permission state changes (permissions and flags) in 14032 * all packages for a given user. 14033 * 14034 * @param userId The device user for which to do a reset. 14035 */ 14036 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14037 final int packageCount = mPackages.size(); 14038 for (int i = 0; i < packageCount; i++) { 14039 PackageParser.Package pkg = mPackages.valueAt(i); 14040 PackageSetting ps = (PackageSetting) pkg.mExtras; 14041 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14042 } 14043 } 14044 14045 /** 14046 * Reverts user permission state changes (permissions and flags). 14047 * 14048 * @param ps The package for which to reset. 14049 * @param userId The device user for which to do a reset. 14050 */ 14051 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14052 final PackageSetting ps, final int userId) { 14053 if (ps.pkg == null) { 14054 return; 14055 } 14056 14057 // These are flags that can change base on user actions. 14058 final int userSettableMask = FLAG_PERMISSION_USER_SET 14059 | FLAG_PERMISSION_USER_FIXED 14060 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14061 | FLAG_PERMISSION_REVIEW_REQUIRED; 14062 14063 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14064 | FLAG_PERMISSION_POLICY_FIXED; 14065 14066 boolean writeInstallPermissions = false; 14067 boolean writeRuntimePermissions = false; 14068 14069 final int permissionCount = ps.pkg.requestedPermissions.size(); 14070 for (int i = 0; i < permissionCount; i++) { 14071 String permission = ps.pkg.requestedPermissions.get(i); 14072 14073 BasePermission bp = mSettings.mPermissions.get(permission); 14074 if (bp == null) { 14075 continue; 14076 } 14077 14078 // If shared user we just reset the state to which only this app contributed. 14079 if (ps.sharedUser != null) { 14080 boolean used = false; 14081 final int packageCount = ps.sharedUser.packages.size(); 14082 for (int j = 0; j < packageCount; j++) { 14083 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14084 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14085 && pkg.pkg.requestedPermissions.contains(permission)) { 14086 used = true; 14087 break; 14088 } 14089 } 14090 if (used) { 14091 continue; 14092 } 14093 } 14094 14095 PermissionsState permissionsState = ps.getPermissionsState(); 14096 14097 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14098 14099 // Always clear the user settable flags. 14100 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14101 bp.name) != null; 14102 // If permission review is enabled and this is a legacy app, mark the 14103 // permission as requiring a review as this is the initial state. 14104 int flags = 0; 14105 if (Build.PERMISSIONS_REVIEW_REQUIRED 14106 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14107 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14108 } 14109 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14110 if (hasInstallState) { 14111 writeInstallPermissions = true; 14112 } else { 14113 writeRuntimePermissions = true; 14114 } 14115 } 14116 14117 // Below is only runtime permission handling. 14118 if (!bp.isRuntime()) { 14119 continue; 14120 } 14121 14122 // Never clobber system or policy. 14123 if ((oldFlags & policyOrSystemFlags) != 0) { 14124 continue; 14125 } 14126 14127 // If this permission was granted by default, make sure it is. 14128 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14129 if (permissionsState.grantRuntimePermission(bp, userId) 14130 != PERMISSION_OPERATION_FAILURE) { 14131 writeRuntimePermissions = true; 14132 } 14133 // If permission review is enabled the permissions for a legacy apps 14134 // are represented as constantly granted runtime ones, so don't revoke. 14135 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14136 // Otherwise, reset the permission. 14137 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14138 switch (revokeResult) { 14139 case PERMISSION_OPERATION_SUCCESS: { 14140 writeRuntimePermissions = true; 14141 } break; 14142 14143 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14144 writeRuntimePermissions = true; 14145 final int appId = ps.appId; 14146 mHandler.post(new Runnable() { 14147 @Override 14148 public void run() { 14149 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14150 } 14151 }); 14152 } break; 14153 } 14154 } 14155 } 14156 14157 // Synchronously write as we are taking permissions away. 14158 if (writeRuntimePermissions) { 14159 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14160 } 14161 14162 // Synchronously write as we are taking permissions away. 14163 if (writeInstallPermissions) { 14164 mSettings.writeLPr(); 14165 } 14166 } 14167 14168 /** 14169 * Remove entries from the keystore daemon. Will only remove it if the 14170 * {@code appId} is valid. 14171 */ 14172 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14173 if (appId < 0) { 14174 return; 14175 } 14176 14177 final KeyStore keyStore = KeyStore.getInstance(); 14178 if (keyStore != null) { 14179 if (userId == UserHandle.USER_ALL) { 14180 for (final int individual : sUserManager.getUserIds()) { 14181 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14182 } 14183 } else { 14184 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14185 } 14186 } else { 14187 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14188 } 14189 } 14190 14191 @Override 14192 public void deleteApplicationCacheFiles(final String packageName, 14193 final IPackageDataObserver observer) { 14194 mContext.enforceCallingOrSelfPermission( 14195 android.Manifest.permission.DELETE_CACHE_FILES, null); 14196 // Queue up an async operation since the package deletion may take a little while. 14197 final int userId = UserHandle.getCallingUserId(); 14198 mHandler.post(new Runnable() { 14199 public void run() { 14200 mHandler.removeCallbacks(this); 14201 final boolean succeded; 14202 synchronized (mInstallLock) { 14203 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14204 } 14205 clearExternalStorageDataSync(packageName, userId, false); 14206 if (observer != null) { 14207 try { 14208 observer.onRemoveCompleted(packageName, succeded); 14209 } catch (RemoteException e) { 14210 Log.i(TAG, "Observer no longer exists."); 14211 } 14212 } //end if observer 14213 } //end run 14214 }); 14215 } 14216 14217 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14218 if (packageName == null) { 14219 Slog.w(TAG, "Attempt to delete null packageName."); 14220 return false; 14221 } 14222 PackageParser.Package p; 14223 synchronized (mPackages) { 14224 p = mPackages.get(packageName); 14225 } 14226 if (p == null) { 14227 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14228 return false; 14229 } 14230 final ApplicationInfo applicationInfo = p.applicationInfo; 14231 if (applicationInfo == null) { 14232 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14233 return false; 14234 } 14235 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 14236 if (retCode < 0) { 14237 Slog.w(TAG, "Couldn't remove cache files for package " 14238 + packageName + " u" + userId); 14239 return false; 14240 } 14241 return true; 14242 } 14243 14244 @Override 14245 public void getPackageSizeInfo(final String packageName, int userHandle, 14246 final IPackageStatsObserver observer) { 14247 mContext.enforceCallingOrSelfPermission( 14248 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14249 if (packageName == null) { 14250 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14251 } 14252 14253 PackageStats stats = new PackageStats(packageName, userHandle); 14254 14255 /* 14256 * Queue up an async operation since the package measurement may take a 14257 * little while. 14258 */ 14259 Message msg = mHandler.obtainMessage(INIT_COPY); 14260 msg.obj = new MeasureParams(stats, observer); 14261 mHandler.sendMessage(msg); 14262 } 14263 14264 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14265 PackageStats pStats) { 14266 if (packageName == null) { 14267 Slog.w(TAG, "Attempt to get size of null packageName."); 14268 return false; 14269 } 14270 PackageParser.Package p; 14271 boolean dataOnly = false; 14272 String libDirRoot = null; 14273 String asecPath = null; 14274 PackageSetting ps = null; 14275 synchronized (mPackages) { 14276 p = mPackages.get(packageName); 14277 ps = mSettings.mPackages.get(packageName); 14278 if(p == null) { 14279 dataOnly = true; 14280 if((ps == null) || (ps.pkg == null)) { 14281 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14282 return false; 14283 } 14284 p = ps.pkg; 14285 } 14286 if (ps != null) { 14287 libDirRoot = ps.legacyNativeLibraryPathString; 14288 } 14289 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14290 final long token = Binder.clearCallingIdentity(); 14291 try { 14292 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14293 if (secureContainerId != null) { 14294 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14295 } 14296 } finally { 14297 Binder.restoreCallingIdentity(token); 14298 } 14299 } 14300 } 14301 String publicSrcDir = null; 14302 if(!dataOnly) { 14303 final ApplicationInfo applicationInfo = p.applicationInfo; 14304 if (applicationInfo == null) { 14305 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14306 return false; 14307 } 14308 if (p.isForwardLocked()) { 14309 publicSrcDir = applicationInfo.getBaseResourcePath(); 14310 } 14311 } 14312 // TODO: extend to measure size of split APKs 14313 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14314 // not just the first level. 14315 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14316 // just the primary. 14317 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14318 14319 String apkPath; 14320 File packageDir = new File(p.codePath); 14321 14322 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14323 apkPath = packageDir.getAbsolutePath(); 14324 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14325 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14326 libDirRoot = null; 14327 } 14328 } else { 14329 apkPath = p.baseCodePath; 14330 } 14331 14332 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath, 14333 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14334 if (res < 0) { 14335 return false; 14336 } 14337 14338 // Fix-up for forward-locked applications in ASEC containers. 14339 if (!isExternal(p)) { 14340 pStats.codeSize += pStats.externalCodeSize; 14341 pStats.externalCodeSize = 0L; 14342 } 14343 14344 return true; 14345 } 14346 14347 14348 @Override 14349 public void addPackageToPreferred(String packageName) { 14350 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14351 } 14352 14353 @Override 14354 public void removePackageFromPreferred(String packageName) { 14355 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14356 } 14357 14358 @Override 14359 public List<PackageInfo> getPreferredPackages(int flags) { 14360 return new ArrayList<PackageInfo>(); 14361 } 14362 14363 private int getUidTargetSdkVersionLockedLPr(int uid) { 14364 Object obj = mSettings.getUserIdLPr(uid); 14365 if (obj instanceof SharedUserSetting) { 14366 final SharedUserSetting sus = (SharedUserSetting) obj; 14367 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14368 final Iterator<PackageSetting> it = sus.packages.iterator(); 14369 while (it.hasNext()) { 14370 final PackageSetting ps = it.next(); 14371 if (ps.pkg != null) { 14372 int v = ps.pkg.applicationInfo.targetSdkVersion; 14373 if (v < vers) vers = v; 14374 } 14375 } 14376 return vers; 14377 } else if (obj instanceof PackageSetting) { 14378 final PackageSetting ps = (PackageSetting) obj; 14379 if (ps.pkg != null) { 14380 return ps.pkg.applicationInfo.targetSdkVersion; 14381 } 14382 } 14383 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14384 } 14385 14386 @Override 14387 public void addPreferredActivity(IntentFilter filter, int match, 14388 ComponentName[] set, ComponentName activity, int userId) { 14389 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14390 "Adding preferred"); 14391 } 14392 14393 private void addPreferredActivityInternal(IntentFilter filter, int match, 14394 ComponentName[] set, ComponentName activity, boolean always, int userId, 14395 String opname) { 14396 // writer 14397 int callingUid = Binder.getCallingUid(); 14398 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14399 if (filter.countActions() == 0) { 14400 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14401 return; 14402 } 14403 synchronized (mPackages) { 14404 if (mContext.checkCallingOrSelfPermission( 14405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14406 != PackageManager.PERMISSION_GRANTED) { 14407 if (getUidTargetSdkVersionLockedLPr(callingUid) 14408 < Build.VERSION_CODES.FROYO) { 14409 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14410 + callingUid); 14411 return; 14412 } 14413 mContext.enforceCallingOrSelfPermission( 14414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14415 } 14416 14417 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14418 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14419 + userId + ":"); 14420 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14421 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14422 scheduleWritePackageRestrictionsLocked(userId); 14423 } 14424 } 14425 14426 @Override 14427 public void replacePreferredActivity(IntentFilter filter, int match, 14428 ComponentName[] set, ComponentName activity, int userId) { 14429 if (filter.countActions() != 1) { 14430 throw new IllegalArgumentException( 14431 "replacePreferredActivity expects filter to have only 1 action."); 14432 } 14433 if (filter.countDataAuthorities() != 0 14434 || filter.countDataPaths() != 0 14435 || filter.countDataSchemes() > 1 14436 || filter.countDataTypes() != 0) { 14437 throw new IllegalArgumentException( 14438 "replacePreferredActivity expects filter to have no data authorities, " + 14439 "paths, or types; and at most one scheme."); 14440 } 14441 14442 final int callingUid = Binder.getCallingUid(); 14443 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14444 synchronized (mPackages) { 14445 if (mContext.checkCallingOrSelfPermission( 14446 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14447 != PackageManager.PERMISSION_GRANTED) { 14448 if (getUidTargetSdkVersionLockedLPr(callingUid) 14449 < Build.VERSION_CODES.FROYO) { 14450 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14451 + Binder.getCallingUid()); 14452 return; 14453 } 14454 mContext.enforceCallingOrSelfPermission( 14455 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14456 } 14457 14458 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14459 if (pir != null) { 14460 // Get all of the existing entries that exactly match this filter. 14461 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14462 if (existing != null && existing.size() == 1) { 14463 PreferredActivity cur = existing.get(0); 14464 if (DEBUG_PREFERRED) { 14465 Slog.i(TAG, "Checking replace of preferred:"); 14466 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14467 if (!cur.mPref.mAlways) { 14468 Slog.i(TAG, " -- CUR; not mAlways!"); 14469 } else { 14470 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14471 Slog.i(TAG, " -- CUR: mSet=" 14472 + Arrays.toString(cur.mPref.mSetComponents)); 14473 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14474 Slog.i(TAG, " -- NEW: mMatch=" 14475 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14476 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14477 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14478 } 14479 } 14480 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14481 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14482 && cur.mPref.sameSet(set)) { 14483 // Setting the preferred activity to what it happens to be already 14484 if (DEBUG_PREFERRED) { 14485 Slog.i(TAG, "Replacing with same preferred activity " 14486 + cur.mPref.mShortComponent + " for user " 14487 + userId + ":"); 14488 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14489 } 14490 return; 14491 } 14492 } 14493 14494 if (existing != null) { 14495 if (DEBUG_PREFERRED) { 14496 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14497 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14498 } 14499 for (int i = 0; i < existing.size(); i++) { 14500 PreferredActivity pa = existing.get(i); 14501 if (DEBUG_PREFERRED) { 14502 Slog.i(TAG, "Removing existing preferred activity " 14503 + pa.mPref.mComponent + ":"); 14504 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14505 } 14506 pir.removeFilter(pa); 14507 } 14508 } 14509 } 14510 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14511 "Replacing preferred"); 14512 } 14513 } 14514 14515 @Override 14516 public void clearPackagePreferredActivities(String packageName) { 14517 final int uid = Binder.getCallingUid(); 14518 // writer 14519 synchronized (mPackages) { 14520 PackageParser.Package pkg = mPackages.get(packageName); 14521 if (pkg == null || pkg.applicationInfo.uid != uid) { 14522 if (mContext.checkCallingOrSelfPermission( 14523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14524 != PackageManager.PERMISSION_GRANTED) { 14525 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14526 < Build.VERSION_CODES.FROYO) { 14527 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14528 + Binder.getCallingUid()); 14529 return; 14530 } 14531 mContext.enforceCallingOrSelfPermission( 14532 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14533 } 14534 } 14535 14536 int user = UserHandle.getCallingUserId(); 14537 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14538 scheduleWritePackageRestrictionsLocked(user); 14539 } 14540 } 14541 } 14542 14543 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14544 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14545 ArrayList<PreferredActivity> removed = null; 14546 boolean changed = false; 14547 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14548 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14549 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14550 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14551 continue; 14552 } 14553 Iterator<PreferredActivity> it = pir.filterIterator(); 14554 while (it.hasNext()) { 14555 PreferredActivity pa = it.next(); 14556 // Mark entry for removal only if it matches the package name 14557 // and the entry is of type "always". 14558 if (packageName == null || 14559 (pa.mPref.mComponent.getPackageName().equals(packageName) 14560 && pa.mPref.mAlways)) { 14561 if (removed == null) { 14562 removed = new ArrayList<PreferredActivity>(); 14563 } 14564 removed.add(pa); 14565 } 14566 } 14567 if (removed != null) { 14568 for (int j=0; j<removed.size(); j++) { 14569 PreferredActivity pa = removed.get(j); 14570 pir.removeFilter(pa); 14571 } 14572 changed = true; 14573 } 14574 } 14575 return changed; 14576 } 14577 14578 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14579 private void clearIntentFilterVerificationsLPw(int userId) { 14580 final int packageCount = mPackages.size(); 14581 for (int i = 0; i < packageCount; i++) { 14582 PackageParser.Package pkg = mPackages.valueAt(i); 14583 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14584 } 14585 } 14586 14587 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14588 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14589 if (userId == UserHandle.USER_ALL) { 14590 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14591 sUserManager.getUserIds())) { 14592 for (int oneUserId : sUserManager.getUserIds()) { 14593 scheduleWritePackageRestrictionsLocked(oneUserId); 14594 } 14595 } 14596 } else { 14597 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14598 scheduleWritePackageRestrictionsLocked(userId); 14599 } 14600 } 14601 } 14602 14603 void clearDefaultBrowserIfNeeded(String packageName) { 14604 for (int oneUserId : sUserManager.getUserIds()) { 14605 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14606 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14607 if (packageName.equals(defaultBrowserPackageName)) { 14608 setDefaultBrowserPackageName(null, oneUserId); 14609 } 14610 } 14611 } 14612 14613 @Override 14614 public void resetApplicationPreferences(int userId) { 14615 mContext.enforceCallingOrSelfPermission( 14616 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14617 // writer 14618 synchronized (mPackages) { 14619 final long identity = Binder.clearCallingIdentity(); 14620 try { 14621 clearPackagePreferredActivitiesLPw(null, userId); 14622 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14623 // TODO: We have to reset the default SMS and Phone. This requires 14624 // significant refactoring to keep all default apps in the package 14625 // manager (cleaner but more work) or have the services provide 14626 // callbacks to the package manager to request a default app reset. 14627 applyFactoryDefaultBrowserLPw(userId); 14628 clearIntentFilterVerificationsLPw(userId); 14629 primeDomainVerificationsLPw(userId); 14630 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14631 scheduleWritePackageRestrictionsLocked(userId); 14632 } finally { 14633 Binder.restoreCallingIdentity(identity); 14634 } 14635 } 14636 } 14637 14638 @Override 14639 public int getPreferredActivities(List<IntentFilter> outFilters, 14640 List<ComponentName> outActivities, String packageName) { 14641 14642 int num = 0; 14643 final int userId = UserHandle.getCallingUserId(); 14644 // reader 14645 synchronized (mPackages) { 14646 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14647 if (pir != null) { 14648 final Iterator<PreferredActivity> it = pir.filterIterator(); 14649 while (it.hasNext()) { 14650 final PreferredActivity pa = it.next(); 14651 if (packageName == null 14652 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14653 && pa.mPref.mAlways)) { 14654 if (outFilters != null) { 14655 outFilters.add(new IntentFilter(pa)); 14656 } 14657 if (outActivities != null) { 14658 outActivities.add(pa.mPref.mComponent); 14659 } 14660 } 14661 } 14662 } 14663 } 14664 14665 return num; 14666 } 14667 14668 @Override 14669 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14670 int userId) { 14671 int callingUid = Binder.getCallingUid(); 14672 if (callingUid != Process.SYSTEM_UID) { 14673 throw new SecurityException( 14674 "addPersistentPreferredActivity can only be run by the system"); 14675 } 14676 if (filter.countActions() == 0) { 14677 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14678 return; 14679 } 14680 synchronized (mPackages) { 14681 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14682 ":"); 14683 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14684 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14685 new PersistentPreferredActivity(filter, activity)); 14686 scheduleWritePackageRestrictionsLocked(userId); 14687 } 14688 } 14689 14690 @Override 14691 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14692 int callingUid = Binder.getCallingUid(); 14693 if (callingUid != Process.SYSTEM_UID) { 14694 throw new SecurityException( 14695 "clearPackagePersistentPreferredActivities can only be run by the system"); 14696 } 14697 ArrayList<PersistentPreferredActivity> removed = null; 14698 boolean changed = false; 14699 synchronized (mPackages) { 14700 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14701 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14702 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14703 .valueAt(i); 14704 if (userId != thisUserId) { 14705 continue; 14706 } 14707 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14708 while (it.hasNext()) { 14709 PersistentPreferredActivity ppa = it.next(); 14710 // Mark entry for removal only if it matches the package name. 14711 if (ppa.mComponent.getPackageName().equals(packageName)) { 14712 if (removed == null) { 14713 removed = new ArrayList<PersistentPreferredActivity>(); 14714 } 14715 removed.add(ppa); 14716 } 14717 } 14718 if (removed != null) { 14719 for (int j=0; j<removed.size(); j++) { 14720 PersistentPreferredActivity ppa = removed.get(j); 14721 ppir.removeFilter(ppa); 14722 } 14723 changed = true; 14724 } 14725 } 14726 14727 if (changed) { 14728 scheduleWritePackageRestrictionsLocked(userId); 14729 } 14730 } 14731 } 14732 14733 /** 14734 * Common machinery for picking apart a restored XML blob and passing 14735 * it to a caller-supplied functor to be applied to the running system. 14736 */ 14737 private void restoreFromXml(XmlPullParser parser, int userId, 14738 String expectedStartTag, BlobXmlRestorer functor) 14739 throws IOException, XmlPullParserException { 14740 int type; 14741 while ((type = parser.next()) != XmlPullParser.START_TAG 14742 && type != XmlPullParser.END_DOCUMENT) { 14743 } 14744 if (type != XmlPullParser.START_TAG) { 14745 // oops didn't find a start tag?! 14746 if (DEBUG_BACKUP) { 14747 Slog.e(TAG, "Didn't find start tag during restore"); 14748 } 14749 return; 14750 } 14751 14752 // this is supposed to be TAG_PREFERRED_BACKUP 14753 if (!expectedStartTag.equals(parser.getName())) { 14754 if (DEBUG_BACKUP) { 14755 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14756 } 14757 return; 14758 } 14759 14760 // skip interfering stuff, then we're aligned with the backing implementation 14761 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14762 functor.apply(parser, userId); 14763 } 14764 14765 private interface BlobXmlRestorer { 14766 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14767 } 14768 14769 /** 14770 * Non-Binder method, support for the backup/restore mechanism: write the 14771 * full set of preferred activities in its canonical XML format. Returns the 14772 * XML output as a byte array, or null if there is none. 14773 */ 14774 @Override 14775 public byte[] getPreferredActivityBackup(int userId) { 14776 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14777 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14778 } 14779 14780 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14781 try { 14782 final XmlSerializer serializer = new FastXmlSerializer(); 14783 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14784 serializer.startDocument(null, true); 14785 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14786 14787 synchronized (mPackages) { 14788 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14789 } 14790 14791 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14792 serializer.endDocument(); 14793 serializer.flush(); 14794 } catch (Exception e) { 14795 if (DEBUG_BACKUP) { 14796 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14797 } 14798 return null; 14799 } 14800 14801 return dataStream.toByteArray(); 14802 } 14803 14804 @Override 14805 public void restorePreferredActivities(byte[] backup, int userId) { 14806 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14807 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14808 } 14809 14810 try { 14811 final XmlPullParser parser = Xml.newPullParser(); 14812 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14813 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14814 new BlobXmlRestorer() { 14815 @Override 14816 public void apply(XmlPullParser parser, int userId) 14817 throws XmlPullParserException, IOException { 14818 synchronized (mPackages) { 14819 mSettings.readPreferredActivitiesLPw(parser, userId); 14820 } 14821 } 14822 } ); 14823 } catch (Exception e) { 14824 if (DEBUG_BACKUP) { 14825 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14826 } 14827 } 14828 } 14829 14830 /** 14831 * Non-Binder method, support for the backup/restore mechanism: write the 14832 * default browser (etc) settings in its canonical XML format. Returns the default 14833 * browser XML representation as a byte array, or null if there is none. 14834 */ 14835 @Override 14836 public byte[] getDefaultAppsBackup(int userId) { 14837 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14838 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14839 } 14840 14841 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14842 try { 14843 final XmlSerializer serializer = new FastXmlSerializer(); 14844 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14845 serializer.startDocument(null, true); 14846 serializer.startTag(null, TAG_DEFAULT_APPS); 14847 14848 synchronized (mPackages) { 14849 mSettings.writeDefaultAppsLPr(serializer, userId); 14850 } 14851 14852 serializer.endTag(null, TAG_DEFAULT_APPS); 14853 serializer.endDocument(); 14854 serializer.flush(); 14855 } catch (Exception e) { 14856 if (DEBUG_BACKUP) { 14857 Slog.e(TAG, "Unable to write default apps for backup", e); 14858 } 14859 return null; 14860 } 14861 14862 return dataStream.toByteArray(); 14863 } 14864 14865 @Override 14866 public void restoreDefaultApps(byte[] backup, int userId) { 14867 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14868 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14869 } 14870 14871 try { 14872 final XmlPullParser parser = Xml.newPullParser(); 14873 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14874 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14875 new BlobXmlRestorer() { 14876 @Override 14877 public void apply(XmlPullParser parser, int userId) 14878 throws XmlPullParserException, IOException { 14879 synchronized (mPackages) { 14880 mSettings.readDefaultAppsLPw(parser, userId); 14881 } 14882 } 14883 } ); 14884 } catch (Exception e) { 14885 if (DEBUG_BACKUP) { 14886 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14887 } 14888 } 14889 } 14890 14891 @Override 14892 public byte[] getIntentFilterVerificationBackup(int userId) { 14893 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14894 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14895 } 14896 14897 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14898 try { 14899 final XmlSerializer serializer = new FastXmlSerializer(); 14900 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14901 serializer.startDocument(null, true); 14902 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14903 14904 synchronized (mPackages) { 14905 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14906 } 14907 14908 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14909 serializer.endDocument(); 14910 serializer.flush(); 14911 } catch (Exception e) { 14912 if (DEBUG_BACKUP) { 14913 Slog.e(TAG, "Unable to write default apps for backup", e); 14914 } 14915 return null; 14916 } 14917 14918 return dataStream.toByteArray(); 14919 } 14920 14921 @Override 14922 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14923 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14924 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14925 } 14926 14927 try { 14928 final XmlPullParser parser = Xml.newPullParser(); 14929 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14930 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 14931 new BlobXmlRestorer() { 14932 @Override 14933 public void apply(XmlPullParser parser, int userId) 14934 throws XmlPullParserException, IOException { 14935 synchronized (mPackages) { 14936 mSettings.readAllDomainVerificationsLPr(parser, userId); 14937 mSettings.writeLPr(); 14938 } 14939 } 14940 } ); 14941 } catch (Exception e) { 14942 if (DEBUG_BACKUP) { 14943 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14944 } 14945 } 14946 } 14947 14948 @Override 14949 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 14950 int sourceUserId, int targetUserId, int flags) { 14951 mContext.enforceCallingOrSelfPermission( 14952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14953 int callingUid = Binder.getCallingUid(); 14954 enforceOwnerRights(ownerPackage, callingUid); 14955 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14956 if (intentFilter.countActions() == 0) { 14957 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 14958 return; 14959 } 14960 synchronized (mPackages) { 14961 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 14962 ownerPackage, targetUserId, flags); 14963 CrossProfileIntentResolver resolver = 14964 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14965 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 14966 // We have all those whose filter is equal. Now checking if the rest is equal as well. 14967 if (existing != null) { 14968 int size = existing.size(); 14969 for (int i = 0; i < size; i++) { 14970 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 14971 return; 14972 } 14973 } 14974 } 14975 resolver.addFilter(newFilter); 14976 scheduleWritePackageRestrictionsLocked(sourceUserId); 14977 } 14978 } 14979 14980 @Override 14981 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 14982 mContext.enforceCallingOrSelfPermission( 14983 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14984 int callingUid = Binder.getCallingUid(); 14985 enforceOwnerRights(ownerPackage, callingUid); 14986 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 14987 synchronized (mPackages) { 14988 CrossProfileIntentResolver resolver = 14989 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 14990 ArraySet<CrossProfileIntentFilter> set = 14991 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 14992 for (CrossProfileIntentFilter filter : set) { 14993 if (filter.getOwnerPackage().equals(ownerPackage)) { 14994 resolver.removeFilter(filter); 14995 } 14996 } 14997 scheduleWritePackageRestrictionsLocked(sourceUserId); 14998 } 14999 } 15000 15001 // Enforcing that callingUid is owning pkg on userId 15002 private void enforceOwnerRights(String pkg, int callingUid) { 15003 // The system owns everything. 15004 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15005 return; 15006 } 15007 int callingUserId = UserHandle.getUserId(callingUid); 15008 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15009 if (pi == null) { 15010 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15011 + callingUserId); 15012 } 15013 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15014 throw new SecurityException("Calling uid " + callingUid 15015 + " does not own package " + pkg); 15016 } 15017 } 15018 15019 @Override 15020 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15021 Intent intent = new Intent(Intent.ACTION_MAIN); 15022 intent.addCategory(Intent.CATEGORY_HOME); 15023 15024 final int callingUserId = UserHandle.getCallingUserId(); 15025 List<ResolveInfo> list = queryIntentActivities(intent, null, 15026 PackageManager.GET_META_DATA, callingUserId); 15027 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15028 true, false, false, callingUserId); 15029 15030 allHomeCandidates.clear(); 15031 if (list != null) { 15032 for (ResolveInfo ri : list) { 15033 allHomeCandidates.add(ri); 15034 } 15035 } 15036 return (preferred == null || preferred.activityInfo == null) 15037 ? null 15038 : new ComponentName(preferred.activityInfo.packageName, 15039 preferred.activityInfo.name); 15040 } 15041 15042 @Override 15043 public void setApplicationEnabledSetting(String appPackageName, 15044 int newState, int flags, int userId, String callingPackage) { 15045 if (!sUserManager.exists(userId)) return; 15046 if (callingPackage == null) { 15047 callingPackage = Integer.toString(Binder.getCallingUid()); 15048 } 15049 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15050 } 15051 15052 @Override 15053 public void setComponentEnabledSetting(ComponentName componentName, 15054 int newState, int flags, int userId) { 15055 if (!sUserManager.exists(userId)) return; 15056 setEnabledSetting(componentName.getPackageName(), 15057 componentName.getClassName(), newState, flags, userId, null); 15058 } 15059 15060 private void setEnabledSetting(final String packageName, String className, int newState, 15061 final int flags, int userId, String callingPackage) { 15062 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15063 || newState == COMPONENT_ENABLED_STATE_ENABLED 15064 || newState == COMPONENT_ENABLED_STATE_DISABLED 15065 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15066 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15067 throw new IllegalArgumentException("Invalid new component state: " 15068 + newState); 15069 } 15070 PackageSetting pkgSetting; 15071 final int uid = Binder.getCallingUid(); 15072 final int permission = mContext.checkCallingOrSelfPermission( 15073 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15074 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15075 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15076 boolean sendNow = false; 15077 boolean isApp = (className == null); 15078 String componentName = isApp ? packageName : className; 15079 int packageUid = -1; 15080 ArrayList<String> components; 15081 15082 // writer 15083 synchronized (mPackages) { 15084 pkgSetting = mSettings.mPackages.get(packageName); 15085 if (pkgSetting == null) { 15086 if (className == null) { 15087 throw new IllegalArgumentException("Unknown package: " + packageName); 15088 } 15089 throw new IllegalArgumentException( 15090 "Unknown component: " + packageName + "/" + className); 15091 } 15092 // Allow root and verify that userId is not being specified by a different user 15093 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15094 throw new SecurityException( 15095 "Permission Denial: attempt to change component state from pid=" 15096 + Binder.getCallingPid() 15097 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15098 } 15099 if (className == null) { 15100 // We're dealing with an application/package level state change 15101 if (pkgSetting.getEnabled(userId) == newState) { 15102 // Nothing to do 15103 return; 15104 } 15105 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15106 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15107 // Don't care about who enables an app. 15108 callingPackage = null; 15109 } 15110 pkgSetting.setEnabled(newState, userId, callingPackage); 15111 // pkgSetting.pkg.mSetEnabled = newState; 15112 } else { 15113 // We're dealing with a component level state change 15114 // First, verify that this is a valid class name. 15115 PackageParser.Package pkg = pkgSetting.pkg; 15116 if (pkg == null || !pkg.hasComponentClassName(className)) { 15117 if (pkg != null && 15118 pkg.applicationInfo.targetSdkVersion >= 15119 Build.VERSION_CODES.JELLY_BEAN) { 15120 throw new IllegalArgumentException("Component class " + className 15121 + " does not exist in " + packageName); 15122 } else { 15123 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15124 + className + " does not exist in " + packageName); 15125 } 15126 } 15127 switch (newState) { 15128 case COMPONENT_ENABLED_STATE_ENABLED: 15129 if (!pkgSetting.enableComponentLPw(className, userId)) { 15130 return; 15131 } 15132 break; 15133 case COMPONENT_ENABLED_STATE_DISABLED: 15134 if (!pkgSetting.disableComponentLPw(className, userId)) { 15135 return; 15136 } 15137 break; 15138 case COMPONENT_ENABLED_STATE_DEFAULT: 15139 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15140 return; 15141 } 15142 break; 15143 default: 15144 Slog.e(TAG, "Invalid new component state: " + newState); 15145 return; 15146 } 15147 } 15148 scheduleWritePackageRestrictionsLocked(userId); 15149 components = mPendingBroadcasts.get(userId, packageName); 15150 final boolean newPackage = components == null; 15151 if (newPackage) { 15152 components = new ArrayList<String>(); 15153 } 15154 if (!components.contains(componentName)) { 15155 components.add(componentName); 15156 } 15157 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15158 sendNow = true; 15159 // Purge entry from pending broadcast list if another one exists already 15160 // since we are sending one right away. 15161 mPendingBroadcasts.remove(userId, packageName); 15162 } else { 15163 if (newPackage) { 15164 mPendingBroadcasts.put(userId, packageName, components); 15165 } 15166 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15167 // Schedule a message 15168 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15169 } 15170 } 15171 } 15172 15173 long callingId = Binder.clearCallingIdentity(); 15174 try { 15175 if (sendNow) { 15176 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15177 sendPackageChangedBroadcast(packageName, 15178 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15179 } 15180 } finally { 15181 Binder.restoreCallingIdentity(callingId); 15182 } 15183 } 15184 15185 private void sendPackageChangedBroadcast(String packageName, 15186 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15187 if (DEBUG_INSTALL) 15188 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15189 + componentNames); 15190 Bundle extras = new Bundle(4); 15191 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15192 String nameList[] = new String[componentNames.size()]; 15193 componentNames.toArray(nameList); 15194 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15195 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15196 extras.putInt(Intent.EXTRA_UID, packageUid); 15197 // If this is not reporting a change of the overall package, then only send it 15198 // to registered receivers. We don't want to launch a swath of apps for every 15199 // little component state change. 15200 final int flags = !componentNames.contains(packageName) 15201 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15202 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15203 new int[] {UserHandle.getUserId(packageUid)}); 15204 } 15205 15206 @Override 15207 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15208 if (!sUserManager.exists(userId)) return; 15209 final int uid = Binder.getCallingUid(); 15210 final int permission = mContext.checkCallingOrSelfPermission( 15211 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15212 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15213 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15214 // writer 15215 synchronized (mPackages) { 15216 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15217 allowedByPermission, uid, userId)) { 15218 scheduleWritePackageRestrictionsLocked(userId); 15219 } 15220 } 15221 } 15222 15223 @Override 15224 public String getInstallerPackageName(String packageName) { 15225 // reader 15226 synchronized (mPackages) { 15227 return mSettings.getInstallerPackageNameLPr(packageName); 15228 } 15229 } 15230 15231 @Override 15232 public int getApplicationEnabledSetting(String packageName, int userId) { 15233 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15234 int uid = Binder.getCallingUid(); 15235 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15236 // reader 15237 synchronized (mPackages) { 15238 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15239 } 15240 } 15241 15242 @Override 15243 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15244 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15245 int uid = Binder.getCallingUid(); 15246 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15247 // reader 15248 synchronized (mPackages) { 15249 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15250 } 15251 } 15252 15253 @Override 15254 public void enterSafeMode() { 15255 enforceSystemOrRoot("Only the system can request entering safe mode"); 15256 15257 if (!mSystemReady) { 15258 mSafeMode = true; 15259 } 15260 } 15261 15262 @Override 15263 public void systemReady() { 15264 mSystemReady = true; 15265 15266 // Read the compatibilty setting when the system is ready. 15267 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15268 mContext.getContentResolver(), 15269 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15270 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15271 if (DEBUG_SETTINGS) { 15272 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15273 } 15274 15275 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15276 15277 synchronized (mPackages) { 15278 // Verify that all of the preferred activity components actually 15279 // exist. It is possible for applications to be updated and at 15280 // that point remove a previously declared activity component that 15281 // had been set as a preferred activity. We try to clean this up 15282 // the next time we encounter that preferred activity, but it is 15283 // possible for the user flow to never be able to return to that 15284 // situation so here we do a sanity check to make sure we haven't 15285 // left any junk around. 15286 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15287 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15288 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15289 removed.clear(); 15290 for (PreferredActivity pa : pir.filterSet()) { 15291 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15292 removed.add(pa); 15293 } 15294 } 15295 if (removed.size() > 0) { 15296 for (int r=0; r<removed.size(); r++) { 15297 PreferredActivity pa = removed.get(r); 15298 Slog.w(TAG, "Removing dangling preferred activity: " 15299 + pa.mPref.mComponent); 15300 pir.removeFilter(pa); 15301 } 15302 mSettings.writePackageRestrictionsLPr( 15303 mSettings.mPreferredActivities.keyAt(i)); 15304 } 15305 } 15306 15307 for (int userId : UserManagerService.getInstance().getUserIds()) { 15308 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15309 grantPermissionsUserIds = ArrayUtils.appendInt( 15310 grantPermissionsUserIds, userId); 15311 } 15312 } 15313 } 15314 sUserManager.systemReady(); 15315 15316 // If we upgraded grant all default permissions before kicking off. 15317 for (int userId : grantPermissionsUserIds) { 15318 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15319 } 15320 15321 // Kick off any messages waiting for system ready 15322 if (mPostSystemReadyMessages != null) { 15323 for (Message msg : mPostSystemReadyMessages) { 15324 msg.sendToTarget(); 15325 } 15326 mPostSystemReadyMessages = null; 15327 } 15328 15329 // Watch for external volumes that come and go over time 15330 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15331 storage.registerListener(mStorageListener); 15332 15333 mInstallerService.systemReady(); 15334 mPackageDexOptimizer.systemReady(); 15335 15336 MountServiceInternal mountServiceInternal = LocalServices.getService( 15337 MountServiceInternal.class); 15338 mountServiceInternal.addExternalStoragePolicy( 15339 new MountServiceInternal.ExternalStorageMountPolicy() { 15340 @Override 15341 public int getMountMode(int uid, String packageName) { 15342 if (Process.isIsolated(uid)) { 15343 return Zygote.MOUNT_EXTERNAL_NONE; 15344 } 15345 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15346 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15347 } 15348 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15349 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15350 } 15351 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15352 return Zygote.MOUNT_EXTERNAL_READ; 15353 } 15354 return Zygote.MOUNT_EXTERNAL_WRITE; 15355 } 15356 15357 @Override 15358 public boolean hasExternalStorage(int uid, String packageName) { 15359 return true; 15360 } 15361 }); 15362 } 15363 15364 @Override 15365 public boolean isSafeMode() { 15366 return mSafeMode; 15367 } 15368 15369 @Override 15370 public boolean hasSystemUidErrors() { 15371 return mHasSystemUidErrors; 15372 } 15373 15374 static String arrayToString(int[] array) { 15375 StringBuffer buf = new StringBuffer(128); 15376 buf.append('['); 15377 if (array != null) { 15378 for (int i=0; i<array.length; i++) { 15379 if (i > 0) buf.append(", "); 15380 buf.append(array[i]); 15381 } 15382 } 15383 buf.append(']'); 15384 return buf.toString(); 15385 } 15386 15387 static class DumpState { 15388 public static final int DUMP_LIBS = 1 << 0; 15389 public static final int DUMP_FEATURES = 1 << 1; 15390 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15391 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15392 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15393 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15394 public static final int DUMP_PERMISSIONS = 1 << 6; 15395 public static final int DUMP_PACKAGES = 1 << 7; 15396 public static final int DUMP_SHARED_USERS = 1 << 8; 15397 public static final int DUMP_MESSAGES = 1 << 9; 15398 public static final int DUMP_PROVIDERS = 1 << 10; 15399 public static final int DUMP_VERIFIERS = 1 << 11; 15400 public static final int DUMP_PREFERRED = 1 << 12; 15401 public static final int DUMP_PREFERRED_XML = 1 << 13; 15402 public static final int DUMP_KEYSETS = 1 << 14; 15403 public static final int DUMP_VERSION = 1 << 15; 15404 public static final int DUMP_INSTALLS = 1 << 16; 15405 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15406 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15407 15408 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15409 15410 private int mTypes; 15411 15412 private int mOptions; 15413 15414 private boolean mTitlePrinted; 15415 15416 private SharedUserSetting mSharedUser; 15417 15418 public boolean isDumping(int type) { 15419 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15420 return true; 15421 } 15422 15423 return (mTypes & type) != 0; 15424 } 15425 15426 public void setDump(int type) { 15427 mTypes |= type; 15428 } 15429 15430 public boolean isOptionEnabled(int option) { 15431 return (mOptions & option) != 0; 15432 } 15433 15434 public void setOptionEnabled(int option) { 15435 mOptions |= option; 15436 } 15437 15438 public boolean onTitlePrinted() { 15439 final boolean printed = mTitlePrinted; 15440 mTitlePrinted = true; 15441 return printed; 15442 } 15443 15444 public boolean getTitlePrinted() { 15445 return mTitlePrinted; 15446 } 15447 15448 public void setTitlePrinted(boolean enabled) { 15449 mTitlePrinted = enabled; 15450 } 15451 15452 public SharedUserSetting getSharedUser() { 15453 return mSharedUser; 15454 } 15455 15456 public void setSharedUser(SharedUserSetting user) { 15457 mSharedUser = user; 15458 } 15459 } 15460 15461 @Override 15462 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15463 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15464 (new PackageManagerShellCommand(this)).exec( 15465 this, in, out, err, args, resultReceiver); 15466 } 15467 15468 @Override 15469 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15470 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15471 != PackageManager.PERMISSION_GRANTED) { 15472 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15473 + Binder.getCallingPid() 15474 + ", uid=" + Binder.getCallingUid() 15475 + " without permission " 15476 + android.Manifest.permission.DUMP); 15477 return; 15478 } 15479 15480 DumpState dumpState = new DumpState(); 15481 boolean fullPreferred = false; 15482 boolean checkin = false; 15483 15484 String packageName = null; 15485 ArraySet<String> permissionNames = null; 15486 15487 int opti = 0; 15488 while (opti < args.length) { 15489 String opt = args[opti]; 15490 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15491 break; 15492 } 15493 opti++; 15494 15495 if ("-a".equals(opt)) { 15496 // Right now we only know how to print all. 15497 } else if ("-h".equals(opt)) { 15498 pw.println("Package manager dump options:"); 15499 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15500 pw.println(" --checkin: dump for a checkin"); 15501 pw.println(" -f: print details of intent filters"); 15502 pw.println(" -h: print this help"); 15503 pw.println(" cmd may be one of:"); 15504 pw.println(" l[ibraries]: list known shared libraries"); 15505 pw.println(" f[eatures]: list device features"); 15506 pw.println(" k[eysets]: print known keysets"); 15507 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15508 pw.println(" perm[issions]: dump permissions"); 15509 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15510 pw.println(" pref[erred]: print preferred package settings"); 15511 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15512 pw.println(" prov[iders]: dump content providers"); 15513 pw.println(" p[ackages]: dump installed packages"); 15514 pw.println(" s[hared-users]: dump shared user IDs"); 15515 pw.println(" m[essages]: print collected runtime messages"); 15516 pw.println(" v[erifiers]: print package verifier info"); 15517 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15518 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15519 pw.println(" version: print database version info"); 15520 pw.println(" write: write current settings now"); 15521 pw.println(" installs: details about install sessions"); 15522 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15523 pw.println(" <package.name>: info about given package"); 15524 return; 15525 } else if ("--checkin".equals(opt)) { 15526 checkin = true; 15527 } else if ("-f".equals(opt)) { 15528 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15529 } else { 15530 pw.println("Unknown argument: " + opt + "; use -h for help"); 15531 } 15532 } 15533 15534 // Is the caller requesting to dump a particular piece of data? 15535 if (opti < args.length) { 15536 String cmd = args[opti]; 15537 opti++; 15538 // Is this a package name? 15539 if ("android".equals(cmd) || cmd.contains(".")) { 15540 packageName = cmd; 15541 // When dumping a single package, we always dump all of its 15542 // filter information since the amount of data will be reasonable. 15543 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15544 } else if ("check-permission".equals(cmd)) { 15545 if (opti >= args.length) { 15546 pw.println("Error: check-permission missing permission argument"); 15547 return; 15548 } 15549 String perm = args[opti]; 15550 opti++; 15551 if (opti >= args.length) { 15552 pw.println("Error: check-permission missing package argument"); 15553 return; 15554 } 15555 String pkg = args[opti]; 15556 opti++; 15557 int user = UserHandle.getUserId(Binder.getCallingUid()); 15558 if (opti < args.length) { 15559 try { 15560 user = Integer.parseInt(args[opti]); 15561 } catch (NumberFormatException e) { 15562 pw.println("Error: check-permission user argument is not a number: " 15563 + args[opti]); 15564 return; 15565 } 15566 } 15567 pw.println(checkPermission(perm, pkg, user)); 15568 return; 15569 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15570 dumpState.setDump(DumpState.DUMP_LIBS); 15571 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15572 dumpState.setDump(DumpState.DUMP_FEATURES); 15573 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15574 if (opti >= args.length) { 15575 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15576 | DumpState.DUMP_SERVICE_RESOLVERS 15577 | DumpState.DUMP_RECEIVER_RESOLVERS 15578 | DumpState.DUMP_CONTENT_RESOLVERS); 15579 } else { 15580 while (opti < args.length) { 15581 String name = args[opti]; 15582 if ("a".equals(name) || "activity".equals(name)) { 15583 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15584 } else if ("s".equals(name) || "service".equals(name)) { 15585 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15586 } else if ("r".equals(name) || "receiver".equals(name)) { 15587 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15588 } else if ("c".equals(name) || "content".equals(name)) { 15589 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15590 } else { 15591 pw.println("Error: unknown resolver table type: " + name); 15592 return; 15593 } 15594 opti++; 15595 } 15596 } 15597 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15598 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15599 } else if ("permission".equals(cmd)) { 15600 if (opti >= args.length) { 15601 pw.println("Error: permission requires permission name"); 15602 return; 15603 } 15604 permissionNames = new ArraySet<>(); 15605 while (opti < args.length) { 15606 permissionNames.add(args[opti]); 15607 opti++; 15608 } 15609 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15610 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15611 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15612 dumpState.setDump(DumpState.DUMP_PREFERRED); 15613 } else if ("preferred-xml".equals(cmd)) { 15614 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15615 if (opti < args.length && "--full".equals(args[opti])) { 15616 fullPreferred = true; 15617 opti++; 15618 } 15619 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15620 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15621 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15622 dumpState.setDump(DumpState.DUMP_PACKAGES); 15623 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15624 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15625 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15626 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15627 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15628 dumpState.setDump(DumpState.DUMP_MESSAGES); 15629 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15630 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15631 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15632 || "intent-filter-verifiers".equals(cmd)) { 15633 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15634 } else if ("version".equals(cmd)) { 15635 dumpState.setDump(DumpState.DUMP_VERSION); 15636 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15637 dumpState.setDump(DumpState.DUMP_KEYSETS); 15638 } else if ("installs".equals(cmd)) { 15639 dumpState.setDump(DumpState.DUMP_INSTALLS); 15640 } else if ("write".equals(cmd)) { 15641 synchronized (mPackages) { 15642 mSettings.writeLPr(); 15643 pw.println("Settings written."); 15644 return; 15645 } 15646 } 15647 } 15648 15649 if (checkin) { 15650 pw.println("vers,1"); 15651 } 15652 15653 // reader 15654 synchronized (mPackages) { 15655 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15656 if (!checkin) { 15657 if (dumpState.onTitlePrinted()) 15658 pw.println(); 15659 pw.println("Database versions:"); 15660 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15661 } 15662 } 15663 15664 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15665 if (!checkin) { 15666 if (dumpState.onTitlePrinted()) 15667 pw.println(); 15668 pw.println("Verifiers:"); 15669 pw.print(" Required: "); 15670 pw.print(mRequiredVerifierPackage); 15671 pw.print(" (uid="); 15672 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15673 UserHandle.USER_SYSTEM)); 15674 pw.println(")"); 15675 } else if (mRequiredVerifierPackage != null) { 15676 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15677 pw.print(","); 15678 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15679 UserHandle.USER_SYSTEM)); 15680 } 15681 } 15682 15683 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15684 packageName == null) { 15685 if (mIntentFilterVerifierComponent != null) { 15686 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15687 if (!checkin) { 15688 if (dumpState.onTitlePrinted()) 15689 pw.println(); 15690 pw.println("Intent Filter Verifier:"); 15691 pw.print(" Using: "); 15692 pw.print(verifierPackageName); 15693 pw.print(" (uid="); 15694 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15695 UserHandle.USER_SYSTEM)); 15696 pw.println(")"); 15697 } else if (verifierPackageName != null) { 15698 pw.print("ifv,"); pw.print(verifierPackageName); 15699 pw.print(","); 15700 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15701 UserHandle.USER_SYSTEM)); 15702 } 15703 } else { 15704 pw.println(); 15705 pw.println("No Intent Filter Verifier available!"); 15706 } 15707 } 15708 15709 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15710 boolean printedHeader = false; 15711 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15712 while (it.hasNext()) { 15713 String name = it.next(); 15714 SharedLibraryEntry ent = mSharedLibraries.get(name); 15715 if (!checkin) { 15716 if (!printedHeader) { 15717 if (dumpState.onTitlePrinted()) 15718 pw.println(); 15719 pw.println("Libraries:"); 15720 printedHeader = true; 15721 } 15722 pw.print(" "); 15723 } else { 15724 pw.print("lib,"); 15725 } 15726 pw.print(name); 15727 if (!checkin) { 15728 pw.print(" -> "); 15729 } 15730 if (ent.path != null) { 15731 if (!checkin) { 15732 pw.print("(jar) "); 15733 pw.print(ent.path); 15734 } else { 15735 pw.print(",jar,"); 15736 pw.print(ent.path); 15737 } 15738 } else { 15739 if (!checkin) { 15740 pw.print("(apk) "); 15741 pw.print(ent.apk); 15742 } else { 15743 pw.print(",apk,"); 15744 pw.print(ent.apk); 15745 } 15746 } 15747 pw.println(); 15748 } 15749 } 15750 15751 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 15752 if (dumpState.onTitlePrinted()) 15753 pw.println(); 15754 if (!checkin) { 15755 pw.println("Features:"); 15756 } 15757 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 15758 while (it.hasNext()) { 15759 String name = it.next(); 15760 if (!checkin) { 15761 pw.print(" "); 15762 } else { 15763 pw.print("feat,"); 15764 } 15765 pw.println(name); 15766 } 15767 } 15768 15769 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 15770 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 15771 : "Activity Resolver Table:", " ", packageName, 15772 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15773 dumpState.setTitlePrinted(true); 15774 } 15775 } 15776 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 15777 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 15778 : "Receiver Resolver Table:", " ", packageName, 15779 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15780 dumpState.setTitlePrinted(true); 15781 } 15782 } 15783 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 15784 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 15785 : "Service Resolver Table:", " ", packageName, 15786 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15787 dumpState.setTitlePrinted(true); 15788 } 15789 } 15790 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 15791 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 15792 : "Provider Resolver Table:", " ", packageName, 15793 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 15794 dumpState.setTitlePrinted(true); 15795 } 15796 } 15797 15798 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 15799 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15800 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15801 int user = mSettings.mPreferredActivities.keyAt(i); 15802 if (pir.dump(pw, 15803 dumpState.getTitlePrinted() 15804 ? "\nPreferred Activities User " + user + ":" 15805 : "Preferred Activities User " + user + ":", " ", 15806 packageName, true, false)) { 15807 dumpState.setTitlePrinted(true); 15808 } 15809 } 15810 } 15811 15812 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 15813 pw.flush(); 15814 FileOutputStream fout = new FileOutputStream(fd); 15815 BufferedOutputStream str = new BufferedOutputStream(fout); 15816 XmlSerializer serializer = new FastXmlSerializer(); 15817 try { 15818 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 15819 serializer.startDocument(null, true); 15820 serializer.setFeature( 15821 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 15822 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 15823 serializer.endDocument(); 15824 serializer.flush(); 15825 } catch (IllegalArgumentException e) { 15826 pw.println("Failed writing: " + e); 15827 } catch (IllegalStateException e) { 15828 pw.println("Failed writing: " + e); 15829 } catch (IOException e) { 15830 pw.println("Failed writing: " + e); 15831 } 15832 } 15833 15834 if (!checkin 15835 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 15836 && packageName == null) { 15837 pw.println(); 15838 int count = mSettings.mPackages.size(); 15839 if (count == 0) { 15840 pw.println("No applications!"); 15841 pw.println(); 15842 } else { 15843 final String prefix = " "; 15844 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 15845 if (allPackageSettings.size() == 0) { 15846 pw.println("No domain preferred apps!"); 15847 pw.println(); 15848 } else { 15849 pw.println("App verification status:"); 15850 pw.println(); 15851 count = 0; 15852 for (PackageSetting ps : allPackageSettings) { 15853 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 15854 if (ivi == null || ivi.getPackageName() == null) continue; 15855 pw.println(prefix + "Package: " + ivi.getPackageName()); 15856 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 15857 pw.println(prefix + "Status: " + ivi.getStatusString()); 15858 pw.println(); 15859 count++; 15860 } 15861 if (count == 0) { 15862 pw.println(prefix + "No app verification established."); 15863 pw.println(); 15864 } 15865 for (int userId : sUserManager.getUserIds()) { 15866 pw.println("App linkages for user " + userId + ":"); 15867 pw.println(); 15868 count = 0; 15869 for (PackageSetting ps : allPackageSettings) { 15870 final long status = ps.getDomainVerificationStatusForUser(userId); 15871 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 15872 continue; 15873 } 15874 pw.println(prefix + "Package: " + ps.name); 15875 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 15876 String statusStr = IntentFilterVerificationInfo. 15877 getStatusStringFromValue(status); 15878 pw.println(prefix + "Status: " + statusStr); 15879 pw.println(); 15880 count++; 15881 } 15882 if (count == 0) { 15883 pw.println(prefix + "No configured app linkages."); 15884 pw.println(); 15885 } 15886 } 15887 } 15888 } 15889 } 15890 15891 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 15892 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 15893 if (packageName == null && permissionNames == null) { 15894 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 15895 if (iperm == 0) { 15896 if (dumpState.onTitlePrinted()) 15897 pw.println(); 15898 pw.println("AppOp Permissions:"); 15899 } 15900 pw.print(" AppOp Permission "); 15901 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 15902 pw.println(":"); 15903 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 15904 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 15905 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 15906 } 15907 } 15908 } 15909 } 15910 15911 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 15912 boolean printedSomething = false; 15913 for (PackageParser.Provider p : mProviders.mProviders.values()) { 15914 if (packageName != null && !packageName.equals(p.info.packageName)) { 15915 continue; 15916 } 15917 if (!printedSomething) { 15918 if (dumpState.onTitlePrinted()) 15919 pw.println(); 15920 pw.println("Registered ContentProviders:"); 15921 printedSomething = true; 15922 } 15923 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 15924 pw.print(" "); pw.println(p.toString()); 15925 } 15926 printedSomething = false; 15927 for (Map.Entry<String, PackageParser.Provider> entry : 15928 mProvidersByAuthority.entrySet()) { 15929 PackageParser.Provider p = entry.getValue(); 15930 if (packageName != null && !packageName.equals(p.info.packageName)) { 15931 continue; 15932 } 15933 if (!printedSomething) { 15934 if (dumpState.onTitlePrinted()) 15935 pw.println(); 15936 pw.println("ContentProvider Authorities:"); 15937 printedSomething = true; 15938 } 15939 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 15940 pw.print(" "); pw.println(p.toString()); 15941 if (p.info != null && p.info.applicationInfo != null) { 15942 final String appInfo = p.info.applicationInfo.toString(); 15943 pw.print(" applicationInfo="); pw.println(appInfo); 15944 } 15945 } 15946 } 15947 15948 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 15949 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 15950 } 15951 15952 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 15953 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 15954 } 15955 15956 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 15957 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 15958 } 15959 15960 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 15961 // XXX should handle packageName != null by dumping only install data that 15962 // the given package is involved with. 15963 if (dumpState.onTitlePrinted()) pw.println(); 15964 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 15965 } 15966 15967 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 15968 if (dumpState.onTitlePrinted()) pw.println(); 15969 mSettings.dumpReadMessagesLPr(pw, dumpState); 15970 15971 pw.println(); 15972 pw.println("Package warning messages:"); 15973 BufferedReader in = null; 15974 String line = null; 15975 try { 15976 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15977 while ((line = in.readLine()) != null) { 15978 if (line.contains("ignored: updated version")) continue; 15979 pw.println(line); 15980 } 15981 } catch (IOException ignored) { 15982 } finally { 15983 IoUtils.closeQuietly(in); 15984 } 15985 } 15986 15987 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 15988 BufferedReader in = null; 15989 String line = null; 15990 try { 15991 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 15992 while ((line = in.readLine()) != null) { 15993 if (line.contains("ignored: updated version")) continue; 15994 pw.print("msg,"); 15995 pw.println(line); 15996 } 15997 } catch (IOException ignored) { 15998 } finally { 15999 IoUtils.closeQuietly(in); 16000 } 16001 } 16002 } 16003 } 16004 16005 private String dumpDomainString(String packageName) { 16006 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16007 List<IntentFilter> filters = getAllIntentFilters(packageName); 16008 16009 ArraySet<String> result = new ArraySet<>(); 16010 if (iviList.size() > 0) { 16011 for (IntentFilterVerificationInfo ivi : iviList) { 16012 for (String host : ivi.getDomains()) { 16013 result.add(host); 16014 } 16015 } 16016 } 16017 if (filters != null && filters.size() > 0) { 16018 for (IntentFilter filter : filters) { 16019 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16020 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16021 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16022 result.addAll(filter.getHostsList()); 16023 } 16024 } 16025 } 16026 16027 StringBuilder sb = new StringBuilder(result.size() * 16); 16028 for (String domain : result) { 16029 if (sb.length() > 0) sb.append(" "); 16030 sb.append(domain); 16031 } 16032 return sb.toString(); 16033 } 16034 16035 // ------- apps on sdcard specific code ------- 16036 static final boolean DEBUG_SD_INSTALL = false; 16037 16038 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16039 16040 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16041 16042 private boolean mMediaMounted = false; 16043 16044 static String getEncryptKey() { 16045 try { 16046 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16047 SD_ENCRYPTION_KEYSTORE_NAME); 16048 if (sdEncKey == null) { 16049 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16050 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16051 if (sdEncKey == null) { 16052 Slog.e(TAG, "Failed to create encryption keys"); 16053 return null; 16054 } 16055 } 16056 return sdEncKey; 16057 } catch (NoSuchAlgorithmException nsae) { 16058 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16059 return null; 16060 } catch (IOException ioe) { 16061 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16062 return null; 16063 } 16064 } 16065 16066 /* 16067 * Update media status on PackageManager. 16068 */ 16069 @Override 16070 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16071 int callingUid = Binder.getCallingUid(); 16072 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16073 throw new SecurityException("Media status can only be updated by the system"); 16074 } 16075 // reader; this apparently protects mMediaMounted, but should probably 16076 // be a different lock in that case. 16077 synchronized (mPackages) { 16078 Log.i(TAG, "Updating external media status from " 16079 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16080 + (mediaStatus ? "mounted" : "unmounted")); 16081 if (DEBUG_SD_INSTALL) 16082 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16083 + ", mMediaMounted=" + mMediaMounted); 16084 if (mediaStatus == mMediaMounted) { 16085 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16086 : 0, -1); 16087 mHandler.sendMessage(msg); 16088 return; 16089 } 16090 mMediaMounted = mediaStatus; 16091 } 16092 // Queue up an async operation since the package installation may take a 16093 // little while. 16094 mHandler.post(new Runnable() { 16095 public void run() { 16096 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16097 } 16098 }); 16099 } 16100 16101 /** 16102 * Called by MountService when the initial ASECs to scan are available. 16103 * Should block until all the ASEC containers are finished being scanned. 16104 */ 16105 public void scanAvailableAsecs() { 16106 updateExternalMediaStatusInner(true, false, false); 16107 if (mShouldRestoreconData) { 16108 SELinuxMMAC.setRestoreconDone(); 16109 mShouldRestoreconData = false; 16110 } 16111 } 16112 16113 /* 16114 * Collect information of applications on external media, map them against 16115 * existing containers and update information based on current mount status. 16116 * Please note that we always have to report status if reportStatus has been 16117 * set to true especially when unloading packages. 16118 */ 16119 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16120 boolean externalStorage) { 16121 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16122 int[] uidArr = EmptyArray.INT; 16123 16124 final String[] list = PackageHelper.getSecureContainerList(); 16125 if (ArrayUtils.isEmpty(list)) { 16126 Log.i(TAG, "No secure containers found"); 16127 } else { 16128 // Process list of secure containers and categorize them 16129 // as active or stale based on their package internal state. 16130 16131 // reader 16132 synchronized (mPackages) { 16133 for (String cid : list) { 16134 // Leave stages untouched for now; installer service owns them 16135 if (PackageInstallerService.isStageName(cid)) continue; 16136 16137 if (DEBUG_SD_INSTALL) 16138 Log.i(TAG, "Processing container " + cid); 16139 String pkgName = getAsecPackageName(cid); 16140 if (pkgName == null) { 16141 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16142 continue; 16143 } 16144 if (DEBUG_SD_INSTALL) 16145 Log.i(TAG, "Looking for pkg : " + pkgName); 16146 16147 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16148 if (ps == null) { 16149 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16150 continue; 16151 } 16152 16153 /* 16154 * Skip packages that are not external if we're unmounting 16155 * external storage. 16156 */ 16157 if (externalStorage && !isMounted && !isExternal(ps)) { 16158 continue; 16159 } 16160 16161 final AsecInstallArgs args = new AsecInstallArgs(cid, 16162 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16163 // The package status is changed only if the code path 16164 // matches between settings and the container id. 16165 if (ps.codePathString != null 16166 && ps.codePathString.startsWith(args.getCodePath())) { 16167 if (DEBUG_SD_INSTALL) { 16168 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16169 + " at code path: " + ps.codePathString); 16170 } 16171 16172 // We do have a valid package installed on sdcard 16173 processCids.put(args, ps.codePathString); 16174 final int uid = ps.appId; 16175 if (uid != -1) { 16176 uidArr = ArrayUtils.appendInt(uidArr, uid); 16177 } 16178 } else { 16179 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16180 + ps.codePathString); 16181 } 16182 } 16183 } 16184 16185 Arrays.sort(uidArr); 16186 } 16187 16188 // Process packages with valid entries. 16189 if (isMounted) { 16190 if (DEBUG_SD_INSTALL) 16191 Log.i(TAG, "Loading packages"); 16192 loadMediaPackages(processCids, uidArr, externalStorage); 16193 startCleaningPackages(); 16194 mInstallerService.onSecureContainersAvailable(); 16195 } else { 16196 if (DEBUG_SD_INSTALL) 16197 Log.i(TAG, "Unloading packages"); 16198 unloadMediaPackages(processCids, uidArr, reportStatus); 16199 } 16200 } 16201 16202 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16203 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16204 final int size = infos.size(); 16205 final String[] packageNames = new String[size]; 16206 final int[] packageUids = new int[size]; 16207 for (int i = 0; i < size; i++) { 16208 final ApplicationInfo info = infos.get(i); 16209 packageNames[i] = info.packageName; 16210 packageUids[i] = info.uid; 16211 } 16212 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16213 finishedReceiver); 16214 } 16215 16216 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16217 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16218 sendResourcesChangedBroadcast(mediaStatus, replacing, 16219 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16220 } 16221 16222 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16223 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16224 int size = pkgList.length; 16225 if (size > 0) { 16226 // Send broadcasts here 16227 Bundle extras = new Bundle(); 16228 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16229 if (uidArr != null) { 16230 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16231 } 16232 if (replacing) { 16233 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16234 } 16235 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16236 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16237 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16238 } 16239 } 16240 16241 /* 16242 * Look at potentially valid container ids from processCids If package 16243 * information doesn't match the one on record or package scanning fails, 16244 * the cid is added to list of removeCids. We currently don't delete stale 16245 * containers. 16246 */ 16247 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16248 boolean externalStorage) { 16249 ArrayList<String> pkgList = new ArrayList<String>(); 16250 Set<AsecInstallArgs> keys = processCids.keySet(); 16251 16252 for (AsecInstallArgs args : keys) { 16253 String codePath = processCids.get(args); 16254 if (DEBUG_SD_INSTALL) 16255 Log.i(TAG, "Loading container : " + args.cid); 16256 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16257 try { 16258 // Make sure there are no container errors first. 16259 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16260 Slog.e(TAG, "Failed to mount cid : " + args.cid 16261 + " when installing from sdcard"); 16262 continue; 16263 } 16264 // Check code path here. 16265 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16266 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16267 + " does not match one in settings " + codePath); 16268 continue; 16269 } 16270 // Parse package 16271 int parseFlags = mDefParseFlags; 16272 if (args.isExternalAsec()) { 16273 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16274 } 16275 if (args.isFwdLocked()) { 16276 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16277 } 16278 16279 synchronized (mInstallLock) { 16280 PackageParser.Package pkg = null; 16281 try { 16282 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16283 } catch (PackageManagerException e) { 16284 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16285 } 16286 // Scan the package 16287 if (pkg != null) { 16288 /* 16289 * TODO why is the lock being held? doPostInstall is 16290 * called in other places without the lock. This needs 16291 * to be straightened out. 16292 */ 16293 // writer 16294 synchronized (mPackages) { 16295 retCode = PackageManager.INSTALL_SUCCEEDED; 16296 pkgList.add(pkg.packageName); 16297 // Post process args 16298 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16299 pkg.applicationInfo.uid); 16300 } 16301 } else { 16302 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16303 } 16304 } 16305 16306 } finally { 16307 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16308 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16309 } 16310 } 16311 } 16312 // writer 16313 synchronized (mPackages) { 16314 // If the platform SDK has changed since the last time we booted, 16315 // we need to re-grant app permission to catch any new ones that 16316 // appear. This is really a hack, and means that apps can in some 16317 // cases get permissions that the user didn't initially explicitly 16318 // allow... it would be nice to have some better way to handle 16319 // this situation. 16320 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16321 : mSettings.getInternalVersion(); 16322 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16323 : StorageManager.UUID_PRIVATE_INTERNAL; 16324 16325 int updateFlags = UPDATE_PERMISSIONS_ALL; 16326 if (ver.sdkVersion != mSdkVersion) { 16327 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16328 + mSdkVersion + "; regranting permissions for external"); 16329 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16330 } 16331 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16332 16333 // Yay, everything is now upgraded 16334 ver.forceCurrent(); 16335 16336 // can downgrade to reader 16337 // Persist settings 16338 mSettings.writeLPr(); 16339 } 16340 // Send a broadcast to let everyone know we are done processing 16341 if (pkgList.size() > 0) { 16342 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16343 } 16344 } 16345 16346 /* 16347 * Utility method to unload a list of specified containers 16348 */ 16349 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16350 // Just unmount all valid containers. 16351 for (AsecInstallArgs arg : cidArgs) { 16352 synchronized (mInstallLock) { 16353 arg.doPostDeleteLI(false); 16354 } 16355 } 16356 } 16357 16358 /* 16359 * Unload packages mounted on external media. This involves deleting package 16360 * data from internal structures, sending broadcasts about diabled packages, 16361 * gc'ing to free up references, unmounting all secure containers 16362 * corresponding to packages on external media, and posting a 16363 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16364 * that we always have to post this message if status has been requested no 16365 * matter what. 16366 */ 16367 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16368 final boolean reportStatus) { 16369 if (DEBUG_SD_INSTALL) 16370 Log.i(TAG, "unloading media packages"); 16371 ArrayList<String> pkgList = new ArrayList<String>(); 16372 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16373 final Set<AsecInstallArgs> keys = processCids.keySet(); 16374 for (AsecInstallArgs args : keys) { 16375 String pkgName = args.getPackageName(); 16376 if (DEBUG_SD_INSTALL) 16377 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16378 // Delete package internally 16379 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16380 synchronized (mInstallLock) { 16381 boolean res = deletePackageLI(pkgName, null, false, null, null, 16382 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16383 if (res) { 16384 pkgList.add(pkgName); 16385 } else { 16386 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16387 failedList.add(args); 16388 } 16389 } 16390 } 16391 16392 // reader 16393 synchronized (mPackages) { 16394 // We didn't update the settings after removing each package; 16395 // write them now for all packages. 16396 mSettings.writeLPr(); 16397 } 16398 16399 // We have to absolutely send UPDATED_MEDIA_STATUS only 16400 // after confirming that all the receivers processed the ordered 16401 // broadcast when packages get disabled, force a gc to clean things up. 16402 // and unload all the containers. 16403 if (pkgList.size() > 0) { 16404 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16405 new IIntentReceiver.Stub() { 16406 public void performReceive(Intent intent, int resultCode, String data, 16407 Bundle extras, boolean ordered, boolean sticky, 16408 int sendingUser) throws RemoteException { 16409 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16410 reportStatus ? 1 : 0, 1, keys); 16411 mHandler.sendMessage(msg); 16412 } 16413 }); 16414 } else { 16415 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16416 keys); 16417 mHandler.sendMessage(msg); 16418 } 16419 } 16420 16421 private void loadPrivatePackages(final VolumeInfo vol) { 16422 mHandler.post(new Runnable() { 16423 @Override 16424 public void run() { 16425 loadPrivatePackagesInner(vol); 16426 } 16427 }); 16428 } 16429 16430 private void loadPrivatePackagesInner(VolumeInfo vol) { 16431 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16432 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16433 16434 final VersionInfo ver; 16435 final List<PackageSetting> packages; 16436 synchronized (mPackages) { 16437 ver = mSettings.findOrCreateVersion(vol.fsUuid); 16438 packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16439 } 16440 16441 for (PackageSetting ps : packages) { 16442 synchronized (mInstallLock) { 16443 final PackageParser.Package pkg; 16444 try { 16445 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16446 loaded.add(pkg.applicationInfo); 16447 } catch (PackageManagerException e) { 16448 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16449 } 16450 16451 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16452 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16453 } 16454 } 16455 } 16456 16457 synchronized (mPackages) { 16458 int updateFlags = UPDATE_PERMISSIONS_ALL; 16459 if (ver.sdkVersion != mSdkVersion) { 16460 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16461 + mSdkVersion + "; regranting permissions for " + vol.fsUuid); 16462 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16463 } 16464 updatePermissionsLPw(null, null, vol.fsUuid, updateFlags); 16465 16466 // Yay, everything is now upgraded 16467 ver.forceCurrent(); 16468 16469 mSettings.writeLPr(); 16470 } 16471 16472 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16473 sendResourcesChangedBroadcast(true, false, loaded, null); 16474 } 16475 16476 private void unloadPrivatePackages(final VolumeInfo vol) { 16477 mHandler.post(new Runnable() { 16478 @Override 16479 public void run() { 16480 unloadPrivatePackagesInner(vol); 16481 } 16482 }); 16483 } 16484 16485 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16486 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16487 synchronized (mInstallLock) { 16488 synchronized (mPackages) { 16489 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 16490 for (PackageSetting ps : packages) { 16491 if (ps.pkg == null) continue; 16492 16493 final ApplicationInfo info = ps.pkg.applicationInfo; 16494 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16495 if (deletePackageLI(ps.name, null, false, null, null, 16496 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16497 unloaded.add(info); 16498 } else { 16499 Slog.w(TAG, "Failed to unload " + ps.codePath); 16500 } 16501 } 16502 16503 mSettings.writeLPr(); 16504 } 16505 } 16506 16507 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16508 sendResourcesChangedBroadcast(false, false, unloaded, null); 16509 } 16510 16511 /** 16512 * Examine all users present on given mounted volume, and destroy data 16513 * belonging to users that are no longer valid, or whose user ID has been 16514 * recycled. 16515 */ 16516 private void reconcileUsers(String volumeUuid) { 16517 final File[] files = FileUtils 16518 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16519 for (File file : files) { 16520 if (!file.isDirectory()) continue; 16521 16522 final int userId; 16523 final UserInfo info; 16524 try { 16525 userId = Integer.parseInt(file.getName()); 16526 info = sUserManager.getUserInfo(userId); 16527 } catch (NumberFormatException e) { 16528 Slog.w(TAG, "Invalid user directory " + file); 16529 continue; 16530 } 16531 16532 boolean destroyUser = false; 16533 if (info == null) { 16534 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16535 + " because no matching user was found"); 16536 destroyUser = true; 16537 } else { 16538 try { 16539 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16540 } catch (IOException e) { 16541 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16542 + " because we failed to enforce serial number: " + e); 16543 destroyUser = true; 16544 } 16545 } 16546 16547 if (destroyUser) { 16548 synchronized (mInstallLock) { 16549 mInstaller.removeUserDataDirs(volumeUuid, userId); 16550 } 16551 } 16552 } 16553 16554 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16555 final UserManager um = mContext.getSystemService(UserManager.class); 16556 for (UserInfo user : um.getUsers()) { 16557 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16558 if (userDir.exists()) continue; 16559 16560 try { 16561 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16562 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16563 } catch (IOException e) { 16564 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16565 } 16566 } 16567 } 16568 16569 /** 16570 * Examine all apps present on given mounted volume, and destroy apps that 16571 * aren't expected, either due to uninstallation or reinstallation on 16572 * another volume. 16573 */ 16574 private void reconcileApps(String volumeUuid) { 16575 final File[] files = FileUtils 16576 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16577 for (File file : files) { 16578 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16579 && !PackageInstallerService.isStageName(file.getName()); 16580 if (!isPackage) { 16581 // Ignore entries which are not packages 16582 continue; 16583 } 16584 16585 boolean destroyApp = false; 16586 String packageName = null; 16587 try { 16588 final PackageLite pkg = PackageParser.parsePackageLite(file, 16589 PackageParser.PARSE_MUST_BE_APK); 16590 packageName = pkg.packageName; 16591 16592 synchronized (mPackages) { 16593 final PackageSetting ps = mSettings.mPackages.get(packageName); 16594 if (ps == null) { 16595 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + " 16596 + volumeUuid + " because we found no install record"); 16597 destroyApp = true; 16598 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16599 logCriticalInfo(Log.WARN, "Destroying " + packageName + " on " 16600 + volumeUuid + " because we expected it on " + ps.volumeUuid); 16601 destroyApp = true; 16602 } 16603 } 16604 16605 } catch (PackageParserException e) { 16606 logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e); 16607 destroyApp = true; 16608 } 16609 16610 if (destroyApp) { 16611 synchronized (mInstallLock) { 16612 if (packageName != null) { 16613 removeDataDirsLI(volumeUuid, packageName); 16614 } 16615 if (file.isDirectory()) { 16616 mInstaller.rmPackageDir(file.getAbsolutePath()); 16617 } else { 16618 file.delete(); 16619 } 16620 } 16621 } 16622 } 16623 } 16624 16625 private void unfreezePackage(String packageName) { 16626 synchronized (mPackages) { 16627 final PackageSetting ps = mSettings.mPackages.get(packageName); 16628 if (ps != null) { 16629 ps.frozen = false; 16630 } 16631 } 16632 } 16633 16634 @Override 16635 public int movePackage(final String packageName, final String volumeUuid) { 16636 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16637 16638 final int moveId = mNextMoveId.getAndIncrement(); 16639 mHandler.post(new Runnable() { 16640 @Override 16641 public void run() { 16642 try { 16643 movePackageInternal(packageName, volumeUuid, moveId); 16644 } catch (PackageManagerException e) { 16645 Slog.w(TAG, "Failed to move " + packageName, e); 16646 mMoveCallbacks.notifyStatusChanged(moveId, 16647 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16648 } 16649 } 16650 }); 16651 return moveId; 16652 } 16653 16654 private void movePackageInternal(final String packageName, final String volumeUuid, 16655 final int moveId) throws PackageManagerException { 16656 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 16657 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16658 final PackageManager pm = mContext.getPackageManager(); 16659 16660 final boolean currentAsec; 16661 final String currentVolumeUuid; 16662 final File codeFile; 16663 final String installerPackageName; 16664 final String packageAbiOverride; 16665 final int appId; 16666 final String seinfo; 16667 final String label; 16668 16669 // reader 16670 synchronized (mPackages) { 16671 final PackageParser.Package pkg = mPackages.get(packageName); 16672 final PackageSetting ps = mSettings.mPackages.get(packageName); 16673 if (pkg == null || ps == null) { 16674 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 16675 } 16676 16677 if (pkg.applicationInfo.isSystemApp()) { 16678 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 16679 "Cannot move system application"); 16680 } 16681 16682 if (pkg.applicationInfo.isExternalAsec()) { 16683 currentAsec = true; 16684 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 16685 } else if (pkg.applicationInfo.isForwardLocked()) { 16686 currentAsec = true; 16687 currentVolumeUuid = "forward_locked"; 16688 } else { 16689 currentAsec = false; 16690 currentVolumeUuid = ps.volumeUuid; 16691 16692 final File probe = new File(pkg.codePath); 16693 final File probeOat = new File(probe, "oat"); 16694 if (!probe.isDirectory() || !probeOat.isDirectory()) { 16695 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16696 "Move only supported for modern cluster style installs"); 16697 } 16698 } 16699 16700 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 16701 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16702 "Package already moved to " + volumeUuid); 16703 } 16704 16705 if (ps.frozen) { 16706 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 16707 "Failed to move already frozen package"); 16708 } 16709 ps.frozen = true; 16710 16711 codeFile = new File(pkg.codePath); 16712 installerPackageName = ps.installerPackageName; 16713 packageAbiOverride = ps.cpuAbiOverrideString; 16714 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16715 seinfo = pkg.applicationInfo.seinfo; 16716 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 16717 } 16718 16719 // Now that we're guarded by frozen state, kill app during move 16720 final long token = Binder.clearCallingIdentity(); 16721 try { 16722 killApplication(packageName, appId, "move pkg"); 16723 } finally { 16724 Binder.restoreCallingIdentity(token); 16725 } 16726 16727 final Bundle extras = new Bundle(); 16728 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 16729 extras.putString(Intent.EXTRA_TITLE, label); 16730 mMoveCallbacks.notifyCreated(moveId, extras); 16731 16732 int installFlags; 16733 final boolean moveCompleteApp; 16734 final File measurePath; 16735 16736 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 16737 installFlags = INSTALL_INTERNAL; 16738 moveCompleteApp = !currentAsec; 16739 measurePath = Environment.getDataAppDirectory(volumeUuid); 16740 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 16741 installFlags = INSTALL_EXTERNAL; 16742 moveCompleteApp = false; 16743 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 16744 } else { 16745 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 16746 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 16747 || !volume.isMountedWritable()) { 16748 unfreezePackage(packageName); 16749 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16750 "Move location not mounted private volume"); 16751 } 16752 16753 Preconditions.checkState(!currentAsec); 16754 16755 installFlags = INSTALL_INTERNAL; 16756 moveCompleteApp = true; 16757 measurePath = Environment.getDataAppDirectory(volumeUuid); 16758 } 16759 16760 final PackageStats stats = new PackageStats(null, -1); 16761 synchronized (mInstaller) { 16762 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 16763 unfreezePackage(packageName); 16764 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16765 "Failed to measure package size"); 16766 } 16767 } 16768 16769 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 16770 + stats.dataSize); 16771 16772 final long startFreeBytes = measurePath.getFreeSpace(); 16773 final long sizeBytes; 16774 if (moveCompleteApp) { 16775 sizeBytes = stats.codeSize + stats.dataSize; 16776 } else { 16777 sizeBytes = stats.codeSize; 16778 } 16779 16780 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 16781 unfreezePackage(packageName); 16782 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 16783 "Not enough free space to move"); 16784 } 16785 16786 mMoveCallbacks.notifyStatusChanged(moveId, 10); 16787 16788 final CountDownLatch installedLatch = new CountDownLatch(1); 16789 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 16790 @Override 16791 public void onUserActionRequired(Intent intent) throws RemoteException { 16792 throw new IllegalStateException(); 16793 } 16794 16795 @Override 16796 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 16797 Bundle extras) throws RemoteException { 16798 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 16799 + PackageManager.installStatusToString(returnCode, msg)); 16800 16801 installedLatch.countDown(); 16802 16803 // Regardless of success or failure of the move operation, 16804 // always unfreeze the package 16805 unfreezePackage(packageName); 16806 16807 final int status = PackageManager.installStatusToPublicStatus(returnCode); 16808 switch (status) { 16809 case PackageInstaller.STATUS_SUCCESS: 16810 mMoveCallbacks.notifyStatusChanged(moveId, 16811 PackageManager.MOVE_SUCCEEDED); 16812 break; 16813 case PackageInstaller.STATUS_FAILURE_STORAGE: 16814 mMoveCallbacks.notifyStatusChanged(moveId, 16815 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 16816 break; 16817 default: 16818 mMoveCallbacks.notifyStatusChanged(moveId, 16819 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 16820 break; 16821 } 16822 } 16823 }; 16824 16825 final MoveInfo move; 16826 if (moveCompleteApp) { 16827 // Kick off a thread to report progress estimates 16828 new Thread() { 16829 @Override 16830 public void run() { 16831 while (true) { 16832 try { 16833 if (installedLatch.await(1, TimeUnit.SECONDS)) { 16834 break; 16835 } 16836 } catch (InterruptedException ignored) { 16837 } 16838 16839 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 16840 final int progress = 10 + (int) MathUtils.constrain( 16841 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 16842 mMoveCallbacks.notifyStatusChanged(moveId, progress); 16843 } 16844 } 16845 }.start(); 16846 16847 final String dataAppName = codeFile.getName(); 16848 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 16849 dataAppName, appId, seinfo); 16850 } else { 16851 move = null; 16852 } 16853 16854 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 16855 16856 final Message msg = mHandler.obtainMessage(INIT_COPY); 16857 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 16858 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 16859 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 16860 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 16861 msg.obj = params; 16862 16863 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 16864 System.identityHashCode(msg.obj)); 16865 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 16866 System.identityHashCode(msg.obj)); 16867 16868 mHandler.sendMessage(msg); 16869 } 16870 16871 @Override 16872 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 16873 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 16874 16875 final int realMoveId = mNextMoveId.getAndIncrement(); 16876 final Bundle extras = new Bundle(); 16877 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 16878 mMoveCallbacks.notifyCreated(realMoveId, extras); 16879 16880 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 16881 @Override 16882 public void onCreated(int moveId, Bundle extras) { 16883 // Ignored 16884 } 16885 16886 @Override 16887 public void onStatusChanged(int moveId, int status, long estMillis) { 16888 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 16889 } 16890 }; 16891 16892 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16893 storage.setPrimaryStorageUuid(volumeUuid, callback); 16894 return realMoveId; 16895 } 16896 16897 @Override 16898 public int getMoveStatus(int moveId) { 16899 mContext.enforceCallingOrSelfPermission( 16900 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16901 return mMoveCallbacks.mLastStatus.get(moveId); 16902 } 16903 16904 @Override 16905 public void registerMoveCallback(IPackageMoveObserver callback) { 16906 mContext.enforceCallingOrSelfPermission( 16907 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16908 mMoveCallbacks.register(callback); 16909 } 16910 16911 @Override 16912 public void unregisterMoveCallback(IPackageMoveObserver callback) { 16913 mContext.enforceCallingOrSelfPermission( 16914 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 16915 mMoveCallbacks.unregister(callback); 16916 } 16917 16918 @Override 16919 public boolean setInstallLocation(int loc) { 16920 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 16921 null); 16922 if (getInstallLocation() == loc) { 16923 return true; 16924 } 16925 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 16926 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 16927 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 16928 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 16929 return true; 16930 } 16931 return false; 16932 } 16933 16934 @Override 16935 public int getInstallLocation() { 16936 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 16937 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 16938 PackageHelper.APP_INSTALL_AUTO); 16939 } 16940 16941 /** Called by UserManagerService */ 16942 void cleanUpUser(UserManagerService userManager, int userHandle) { 16943 synchronized (mPackages) { 16944 mDirtyUsers.remove(userHandle); 16945 mUserNeedsBadging.delete(userHandle); 16946 mSettings.removeUserLPw(userHandle); 16947 mPendingBroadcasts.remove(userHandle); 16948 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 16949 } 16950 synchronized (mInstallLock) { 16951 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16952 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16953 final String volumeUuid = vol.getFsUuid(); 16954 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 16955 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 16956 } 16957 synchronized (mPackages) { 16958 removeUnusedPackagesLILPw(userManager, userHandle); 16959 } 16960 } 16961 } 16962 16963 /** 16964 * We're removing userHandle and would like to remove any downloaded packages 16965 * that are no longer in use by any other user. 16966 * @param userHandle the user being removed 16967 */ 16968 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 16969 final boolean DEBUG_CLEAN_APKS = false; 16970 int [] users = userManager.getUserIds(); 16971 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 16972 while (psit.hasNext()) { 16973 PackageSetting ps = psit.next(); 16974 if (ps.pkg == null) { 16975 continue; 16976 } 16977 final String packageName = ps.pkg.packageName; 16978 // Skip over if system app 16979 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 16980 continue; 16981 } 16982 if (DEBUG_CLEAN_APKS) { 16983 Slog.i(TAG, "Checking package " + packageName); 16984 } 16985 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 16986 if (keep) { 16987 if (DEBUG_CLEAN_APKS) { 16988 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 16989 } 16990 } else { 16991 for (int i = 0; i < users.length; i++) { 16992 if (users[i] != userHandle && ps.getInstalled(users[i])) { 16993 keep = true; 16994 if (DEBUG_CLEAN_APKS) { 16995 Slog.i(TAG, " Keeping package " + packageName + " for user " 16996 + users[i]); 16997 } 16998 break; 16999 } 17000 } 17001 } 17002 if (!keep) { 17003 if (DEBUG_CLEAN_APKS) { 17004 Slog.i(TAG, " Removing package " + packageName); 17005 } 17006 mHandler.post(new Runnable() { 17007 public void run() { 17008 deletePackageX(packageName, userHandle, 0); 17009 } //end run 17010 }); 17011 } 17012 } 17013 } 17014 17015 /** Called by UserManagerService */ 17016 void createNewUser(int userHandle) { 17017 synchronized (mInstallLock) { 17018 mInstaller.createUserConfig(userHandle); 17019 mSettings.createNewUserLI(this, mInstaller, userHandle); 17020 } 17021 synchronized (mPackages) { 17022 applyFactoryDefaultBrowserLPw(userHandle); 17023 primeDomainVerificationsLPw(userHandle); 17024 } 17025 } 17026 17027 void newUserCreated(final int userHandle) { 17028 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17029 // If permission review for legacy apps is required, we represent 17030 // dagerous permissions for such apps as always granted runtime 17031 // permissions to keep per user flag state whether review is needed. 17032 // Hence, if a new user is added we have to propagate dangerous 17033 // permission grants for these legacy apps. 17034 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17035 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17036 | UPDATE_PERMISSIONS_REPLACE_ALL); 17037 } 17038 } 17039 17040 @Override 17041 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17042 mContext.enforceCallingOrSelfPermission( 17043 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17044 "Only package verification agents can read the verifier device identity"); 17045 17046 synchronized (mPackages) { 17047 return mSettings.getVerifierDeviceIdentityLPw(); 17048 } 17049 } 17050 17051 @Override 17052 public void setPermissionEnforced(String permission, boolean enforced) { 17053 // TODO: Now that we no longer change GID for storage, this should to away. 17054 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17055 "setPermissionEnforced"); 17056 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17057 synchronized (mPackages) { 17058 if (mSettings.mReadExternalStorageEnforced == null 17059 || mSettings.mReadExternalStorageEnforced != enforced) { 17060 mSettings.mReadExternalStorageEnforced = enforced; 17061 mSettings.writeLPr(); 17062 } 17063 } 17064 // kill any non-foreground processes so we restart them and 17065 // grant/revoke the GID. 17066 final IActivityManager am = ActivityManagerNative.getDefault(); 17067 if (am != null) { 17068 final long token = Binder.clearCallingIdentity(); 17069 try { 17070 am.killProcessesBelowForeground("setPermissionEnforcement"); 17071 } catch (RemoteException e) { 17072 } finally { 17073 Binder.restoreCallingIdentity(token); 17074 } 17075 } 17076 } else { 17077 throw new IllegalArgumentException("No selective enforcement for " + permission); 17078 } 17079 } 17080 17081 @Override 17082 @Deprecated 17083 public boolean isPermissionEnforced(String permission) { 17084 return true; 17085 } 17086 17087 @Override 17088 public boolean isStorageLow() { 17089 final long token = Binder.clearCallingIdentity(); 17090 try { 17091 final DeviceStorageMonitorInternal 17092 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17093 if (dsm != null) { 17094 return dsm.isMemoryLow(); 17095 } else { 17096 return false; 17097 } 17098 } finally { 17099 Binder.restoreCallingIdentity(token); 17100 } 17101 } 17102 17103 @Override 17104 public IPackageInstaller getPackageInstaller() { 17105 return mInstallerService; 17106 } 17107 17108 private boolean userNeedsBadging(int userId) { 17109 int index = mUserNeedsBadging.indexOfKey(userId); 17110 if (index < 0) { 17111 final UserInfo userInfo; 17112 final long token = Binder.clearCallingIdentity(); 17113 try { 17114 userInfo = sUserManager.getUserInfo(userId); 17115 } finally { 17116 Binder.restoreCallingIdentity(token); 17117 } 17118 final boolean b; 17119 if (userInfo != null && userInfo.isManagedProfile()) { 17120 b = true; 17121 } else { 17122 b = false; 17123 } 17124 mUserNeedsBadging.put(userId, b); 17125 return b; 17126 } 17127 return mUserNeedsBadging.valueAt(index); 17128 } 17129 17130 @Override 17131 public KeySet getKeySetByAlias(String packageName, String alias) { 17132 if (packageName == null || alias == null) { 17133 return null; 17134 } 17135 synchronized(mPackages) { 17136 final PackageParser.Package pkg = mPackages.get(packageName); 17137 if (pkg == null) { 17138 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17139 throw new IllegalArgumentException("Unknown package: " + packageName); 17140 } 17141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17142 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17143 } 17144 } 17145 17146 @Override 17147 public KeySet getSigningKeySet(String packageName) { 17148 if (packageName == null) { 17149 return null; 17150 } 17151 synchronized(mPackages) { 17152 final PackageParser.Package pkg = mPackages.get(packageName); 17153 if (pkg == null) { 17154 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17155 throw new IllegalArgumentException("Unknown package: " + packageName); 17156 } 17157 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17158 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17159 throw new SecurityException("May not access signing KeySet of other apps."); 17160 } 17161 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17162 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17163 } 17164 } 17165 17166 @Override 17167 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17168 if (packageName == null || ks == null) { 17169 return false; 17170 } 17171 synchronized(mPackages) { 17172 final PackageParser.Package pkg = mPackages.get(packageName); 17173 if (pkg == null) { 17174 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17175 throw new IllegalArgumentException("Unknown package: " + packageName); 17176 } 17177 IBinder ksh = ks.getToken(); 17178 if (ksh instanceof KeySetHandle) { 17179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17180 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17181 } 17182 return false; 17183 } 17184 } 17185 17186 @Override 17187 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17188 if (packageName == null || ks == null) { 17189 return false; 17190 } 17191 synchronized(mPackages) { 17192 final PackageParser.Package pkg = mPackages.get(packageName); 17193 if (pkg == null) { 17194 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17195 throw new IllegalArgumentException("Unknown package: " + packageName); 17196 } 17197 IBinder ksh = ks.getToken(); 17198 if (ksh instanceof KeySetHandle) { 17199 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17200 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17201 } 17202 return false; 17203 } 17204 } 17205 17206 private void deletePackageIfUnusedLPr(final String packageName) { 17207 PackageSetting ps = mSettings.mPackages.get(packageName); 17208 if (ps == null) { 17209 return; 17210 } 17211 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17212 // TODO Implement atomic delete if package is unused 17213 // It is currently possible that the package will be deleted even if it is installed 17214 // after this method returns. 17215 mHandler.post(new Runnable() { 17216 public void run() { 17217 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17218 } 17219 }); 17220 } 17221 } 17222 17223 /** 17224 * Check and throw if the given before/after packages would be considered a 17225 * downgrade. 17226 */ 17227 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17228 throws PackageManagerException { 17229 if (after.versionCode < before.mVersionCode) { 17230 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17231 "Update version code " + after.versionCode + " is older than current " 17232 + before.mVersionCode); 17233 } else if (after.versionCode == before.mVersionCode) { 17234 if (after.baseRevisionCode < before.baseRevisionCode) { 17235 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17236 "Update base revision code " + after.baseRevisionCode 17237 + " is older than current " + before.baseRevisionCode); 17238 } 17239 17240 if (!ArrayUtils.isEmpty(after.splitNames)) { 17241 for (int i = 0; i < after.splitNames.length; i++) { 17242 final String splitName = after.splitNames[i]; 17243 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17244 if (j != -1) { 17245 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17246 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17247 "Update split " + splitName + " revision code " 17248 + after.splitRevisionCodes[i] + " is older than current " 17249 + before.splitRevisionCodes[j]); 17250 } 17251 } 17252 } 17253 } 17254 } 17255 } 17256 17257 private static class MoveCallbacks extends Handler { 17258 private static final int MSG_CREATED = 1; 17259 private static final int MSG_STATUS_CHANGED = 2; 17260 17261 private final RemoteCallbackList<IPackageMoveObserver> 17262 mCallbacks = new RemoteCallbackList<>(); 17263 17264 private final SparseIntArray mLastStatus = new SparseIntArray(); 17265 17266 public MoveCallbacks(Looper looper) { 17267 super(looper); 17268 } 17269 17270 public void register(IPackageMoveObserver callback) { 17271 mCallbacks.register(callback); 17272 } 17273 17274 public void unregister(IPackageMoveObserver callback) { 17275 mCallbacks.unregister(callback); 17276 } 17277 17278 @Override 17279 public void handleMessage(Message msg) { 17280 final SomeArgs args = (SomeArgs) msg.obj; 17281 final int n = mCallbacks.beginBroadcast(); 17282 for (int i = 0; i < n; i++) { 17283 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17284 try { 17285 invokeCallback(callback, msg.what, args); 17286 } catch (RemoteException ignored) { 17287 } 17288 } 17289 mCallbacks.finishBroadcast(); 17290 args.recycle(); 17291 } 17292 17293 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17294 throws RemoteException { 17295 switch (what) { 17296 case MSG_CREATED: { 17297 callback.onCreated(args.argi1, (Bundle) args.arg2); 17298 break; 17299 } 17300 case MSG_STATUS_CHANGED: { 17301 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17302 break; 17303 } 17304 } 17305 } 17306 17307 private void notifyCreated(int moveId, Bundle extras) { 17308 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17309 17310 final SomeArgs args = SomeArgs.obtain(); 17311 args.argi1 = moveId; 17312 args.arg2 = extras; 17313 obtainMessage(MSG_CREATED, args).sendToTarget(); 17314 } 17315 17316 private void notifyStatusChanged(int moveId, int status) { 17317 notifyStatusChanged(moveId, status, -1); 17318 } 17319 17320 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17321 Slog.v(TAG, "Move " + moveId + " status " + status); 17322 17323 final SomeArgs args = SomeArgs.obtain(); 17324 args.argi1 = moveId; 17325 args.argi2 = status; 17326 args.arg3 = estMillis; 17327 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17328 17329 synchronized (mLastStatus) { 17330 mLastStatus.put(moveId, status); 17331 } 17332 } 17333 } 17334 17335 private final static class OnPermissionChangeListeners extends Handler { 17336 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17337 17338 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17339 new RemoteCallbackList<>(); 17340 17341 public OnPermissionChangeListeners(Looper looper) { 17342 super(looper); 17343 } 17344 17345 @Override 17346 public void handleMessage(Message msg) { 17347 switch (msg.what) { 17348 case MSG_ON_PERMISSIONS_CHANGED: { 17349 final int uid = msg.arg1; 17350 handleOnPermissionsChanged(uid); 17351 } break; 17352 } 17353 } 17354 17355 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17356 mPermissionListeners.register(listener); 17357 17358 } 17359 17360 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17361 mPermissionListeners.unregister(listener); 17362 } 17363 17364 public void onPermissionsChanged(int uid) { 17365 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17366 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17367 } 17368 } 17369 17370 private void handleOnPermissionsChanged(int uid) { 17371 final int count = mPermissionListeners.beginBroadcast(); 17372 try { 17373 for (int i = 0; i < count; i++) { 17374 IOnPermissionsChangeListener callback = mPermissionListeners 17375 .getBroadcastItem(i); 17376 try { 17377 callback.onPermissionsChanged(uid); 17378 } catch (RemoteException e) { 17379 Log.e(TAG, "Permission listener is dead", e); 17380 } 17381 } 17382 } finally { 17383 mPermissionListeners.finishBroadcast(); 17384 } 17385 } 17386 } 17387 17388 private class PackageManagerInternalImpl extends PackageManagerInternal { 17389 @Override 17390 public void setLocationPackagesProvider(PackagesProvider provider) { 17391 synchronized (mPackages) { 17392 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17393 } 17394 } 17395 17396 @Override 17397 public void setImePackagesProvider(PackagesProvider provider) { 17398 synchronized (mPackages) { 17399 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17400 } 17401 } 17402 17403 @Override 17404 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17405 synchronized (mPackages) { 17406 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17407 } 17408 } 17409 17410 @Override 17411 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17412 synchronized (mPackages) { 17413 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17414 } 17415 } 17416 17417 @Override 17418 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17419 synchronized (mPackages) { 17420 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17421 } 17422 } 17423 17424 @Override 17425 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17426 synchronized (mPackages) { 17427 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17428 } 17429 } 17430 17431 @Override 17432 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17433 synchronized (mPackages) { 17434 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17435 } 17436 } 17437 17438 @Override 17439 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17440 synchronized (mPackages) { 17441 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17442 packageName, userId); 17443 } 17444 } 17445 17446 @Override 17447 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17448 synchronized (mPackages) { 17449 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17450 packageName, userId); 17451 } 17452 } 17453 17454 @Override 17455 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17456 synchronized (mPackages) { 17457 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17458 packageName, userId); 17459 } 17460 } 17461 17462 @Override 17463 public void setKeepUninstalledPackages(final List<String> packageList) { 17464 Preconditions.checkNotNull(packageList); 17465 List<String> removedFromList = null; 17466 synchronized (mPackages) { 17467 if (mKeepUninstalledPackages != null) { 17468 final int packagesCount = mKeepUninstalledPackages.size(); 17469 for (int i = 0; i < packagesCount; i++) { 17470 String oldPackage = mKeepUninstalledPackages.get(i); 17471 if (packageList != null && packageList.contains(oldPackage)) { 17472 continue; 17473 } 17474 if (removedFromList == null) { 17475 removedFromList = new ArrayList<>(); 17476 } 17477 removedFromList.add(oldPackage); 17478 } 17479 } 17480 mKeepUninstalledPackages = new ArrayList<>(packageList); 17481 if (removedFromList != null) { 17482 final int removedCount = removedFromList.size(); 17483 for (int i = 0; i < removedCount; i++) { 17484 deletePackageIfUnusedLPr(removedFromList.get(i)); 17485 } 17486 } 17487 } 17488 } 17489 17490 @Override 17491 public boolean isPermissionsReviewRequired(String packageName, int userId) { 17492 synchronized (mPackages) { 17493 // If we do not support permission review, done. 17494 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 17495 return false; 17496 } 17497 17498 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 17499 if (packageSetting == null) { 17500 return false; 17501 } 17502 17503 // Permission review applies only to apps not supporting the new permission model. 17504 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 17505 return false; 17506 } 17507 17508 // Legacy apps have the permission and get user consent on launch. 17509 PermissionsState permissionsState = packageSetting.getPermissionsState(); 17510 return permissionsState.isPermissionReviewRequired(userId); 17511 } 17512 } 17513 } 17514 17515 @Override 17516 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 17517 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 17518 synchronized (mPackages) { 17519 final long identity = Binder.clearCallingIdentity(); 17520 try { 17521 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 17522 packageNames, userId); 17523 } finally { 17524 Binder.restoreCallingIdentity(identity); 17525 } 17526 } 17527 } 17528 17529 private static void enforceSystemOrPhoneCaller(String tag) { 17530 int callingUid = Binder.getCallingUid(); 17531 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 17532 throw new SecurityException( 17533 "Cannot call " + tag + " from UID " + callingUid); 17534 } 17535 } 17536} 17537