PackageManagerService.java revision 0829fd4b269aafd0d64a93f00870c124bee877eb
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 34import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 71import static android.content.pm.PackageManager.PERMISSION_DENIED; 72import static android.content.pm.PackageManager.PERMISSION_GRANTED; 73import static android.content.pm.PackageParser.isApkFile; 74import static android.os.Process.PACKAGE_INFO_GID; 75import static android.os.Process.SYSTEM_UID; 76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 77import static android.system.OsConstants.O_CREAT; 78import static android.system.OsConstants.O_RDWR; 79 80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 84import static com.android.internal.util.ArrayUtils.appendInt; 85import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 94 95import android.Manifest; 96import android.annotation.NonNull; 97import android.annotation.Nullable; 98import android.app.ActivityManager; 99import android.app.ActivityManagerNative; 100import android.app.AppGlobals; 101import android.app.IActivityManager; 102import android.app.admin.IDevicePolicyManager; 103import android.app.backup.IBackupManager; 104import android.content.BroadcastReceiver; 105import android.content.ComponentName; 106import android.content.Context; 107import android.content.IIntentReceiver; 108import android.content.Intent; 109import android.content.IntentFilter; 110import android.content.IntentSender; 111import android.content.IntentSender.SendIntentException; 112import android.content.ServiceConnection; 113import android.content.pm.ActivityInfo; 114import android.content.pm.ApplicationInfo; 115import android.content.pm.AppsQueryHelper; 116import android.content.pm.ComponentInfo; 117import android.content.pm.EphemeralApplicationInfo; 118import android.content.pm.EphemeralResolveInfo; 119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 120import android.content.pm.FeatureInfo; 121import android.content.pm.IOnPermissionsChangeListener; 122import android.content.pm.IPackageDataObserver; 123import android.content.pm.IPackageDeleteObserver; 124import android.content.pm.IPackageDeleteObserver2; 125import android.content.pm.IPackageInstallObserver2; 126import android.content.pm.IPackageInstaller; 127import android.content.pm.IPackageManager; 128import android.content.pm.IPackageMoveObserver; 129import android.content.pm.IPackageStatsObserver; 130import android.content.pm.InstrumentationInfo; 131import android.content.pm.IntentFilterVerificationInfo; 132import android.content.pm.KeySet; 133import android.content.pm.PackageCleanItem; 134import android.content.pm.PackageInfo; 135import android.content.pm.PackageInfoLite; 136import android.content.pm.PackageInstaller; 137import android.content.pm.PackageManager; 138import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 139import android.content.pm.PackageManagerInternal; 140import android.content.pm.PackageParser; 141import android.content.pm.PackageParser.ActivityIntentInfo; 142import android.content.pm.PackageParser.PackageLite; 143import android.content.pm.PackageParser.PackageParserException; 144import android.content.pm.PackageStats; 145import android.content.pm.PackageUserState; 146import android.content.pm.ParceledListSlice; 147import android.content.pm.PermissionGroupInfo; 148import android.content.pm.PermissionInfo; 149import android.content.pm.ProviderInfo; 150import android.content.pm.ResolveInfo; 151import android.content.pm.ServiceInfo; 152import android.content.pm.Signature; 153import android.content.pm.UserInfo; 154import android.content.pm.VerificationParams; 155import android.content.pm.VerifierDeviceIdentity; 156import android.content.pm.VerifierInfo; 157import android.content.res.Resources; 158import android.graphics.Bitmap; 159import android.hardware.display.DisplayManager; 160import android.net.Uri; 161import android.os.Binder; 162import android.os.Build; 163import android.os.Bundle; 164import android.os.Debug; 165import android.os.Environment; 166import android.os.Environment.UserEnvironment; 167import android.os.FileUtils; 168import android.os.Handler; 169import android.os.IBinder; 170import android.os.Looper; 171import android.os.Message; 172import android.os.Parcel; 173import android.os.ParcelFileDescriptor; 174import android.os.Process; 175import android.os.RemoteCallbackList; 176import android.os.RemoteException; 177import android.os.ResultReceiver; 178import android.os.SELinux; 179import android.os.ServiceManager; 180import android.os.SystemClock; 181import android.os.SystemProperties; 182import android.os.Trace; 183import android.os.UserHandle; 184import android.os.UserManager; 185import android.os.storage.IMountService; 186import android.os.storage.MountServiceInternal; 187import android.os.storage.StorageEventListener; 188import android.os.storage.StorageManager; 189import android.os.storage.VolumeInfo; 190import android.os.storage.VolumeRecord; 191import android.security.KeyStore; 192import android.security.SystemKeyStore; 193import android.system.ErrnoException; 194import android.system.Os; 195import android.text.TextUtils; 196import android.text.format.DateUtils; 197import android.util.ArrayMap; 198import android.util.ArraySet; 199import android.util.AtomicFile; 200import android.util.DisplayMetrics; 201import android.util.EventLog; 202import android.util.ExceptionUtils; 203import android.util.Log; 204import android.util.LogPrinter; 205import android.util.MathUtils; 206import android.util.PrintStreamPrinter; 207import android.util.Slog; 208import android.util.SparseArray; 209import android.util.SparseBooleanArray; 210import android.util.SparseIntArray; 211import android.util.Xml; 212import android.view.Display; 213 214import com.android.internal.R; 215import com.android.internal.annotations.GuardedBy; 216import com.android.internal.app.IMediaContainerService; 217import com.android.internal.app.ResolverActivity; 218import com.android.internal.content.NativeLibraryHelper; 219import com.android.internal.content.PackageHelper; 220import com.android.internal.os.IParcelFileDescriptorFactory; 221import com.android.internal.os.InstallerConnection.InstallerException; 222import com.android.internal.os.SomeArgs; 223import com.android.internal.os.Zygote; 224import com.android.internal.util.ArrayUtils; 225import com.android.internal.util.FastPrintWriter; 226import com.android.internal.util.FastXmlSerializer; 227import com.android.internal.util.IndentingPrintWriter; 228import com.android.internal.util.Preconditions; 229import com.android.internal.util.XmlUtils; 230import com.android.server.EventLogTags; 231import com.android.server.FgThread; 232import com.android.server.IntentResolver; 233import com.android.server.LocalServices; 234import com.android.server.ServiceThread; 235import com.android.server.SystemConfig; 236import com.android.server.Watchdog; 237import com.android.server.pm.Installer.StorageFlags; 238import com.android.server.pm.PermissionsState.PermissionState; 239import com.android.server.pm.Settings.DatabaseVersion; 240import com.android.server.pm.Settings.VersionInfo; 241import com.android.server.storage.DeviceStorageMonitorInternal; 242 243import dalvik.system.DexFile; 244import dalvik.system.VMRuntime; 245 246import libcore.io.IoUtils; 247import libcore.util.EmptyArray; 248 249import org.xmlpull.v1.XmlPullParser; 250import org.xmlpull.v1.XmlPullParserException; 251import org.xmlpull.v1.XmlSerializer; 252 253import java.io.BufferedInputStream; 254import java.io.BufferedOutputStream; 255import java.io.BufferedReader; 256import java.io.ByteArrayInputStream; 257import java.io.ByteArrayOutputStream; 258import java.io.File; 259import java.io.FileDescriptor; 260import java.io.FileNotFoundException; 261import java.io.FileOutputStream; 262import java.io.FileReader; 263import java.io.FilenameFilter; 264import java.io.IOException; 265import java.io.InputStream; 266import java.io.PrintWriter; 267import java.nio.charset.StandardCharsets; 268import java.security.MessageDigest; 269import java.security.NoSuchAlgorithmException; 270import java.security.PublicKey; 271import java.security.cert.CertificateEncodingException; 272import java.security.cert.CertificateException; 273import java.text.SimpleDateFormat; 274import java.util.ArrayList; 275import java.util.Arrays; 276import java.util.Collection; 277import java.util.Collections; 278import java.util.Comparator; 279import java.util.Date; 280import java.util.Iterator; 281import java.util.List; 282import java.util.Map; 283import java.util.Objects; 284import java.util.Set; 285import java.util.concurrent.CountDownLatch; 286import java.util.concurrent.TimeUnit; 287import java.util.concurrent.atomic.AtomicBoolean; 288import java.util.concurrent.atomic.AtomicInteger; 289import java.util.concurrent.atomic.AtomicLong; 290 291/** 292 * Keep track of all those .apks everywhere. 293 * 294 * This is very central to the platform's security; please run the unit 295 * tests whenever making modifications here: 296 * 297runtest -c android.content.pm.PackageManagerTests frameworks-core 298 * 299 * {@hide} 300 */ 301public class PackageManagerService extends IPackageManager.Stub { 302 static final String TAG = "PackageManager"; 303 static final boolean DEBUG_SETTINGS = false; 304 static final boolean DEBUG_PREFERRED = false; 305 static final boolean DEBUG_UPGRADE = false; 306 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 307 private static final boolean DEBUG_BACKUP = false; 308 private static final boolean DEBUG_INSTALL = false; 309 private static final boolean DEBUG_REMOVE = false; 310 private static final boolean DEBUG_BROADCASTS = false; 311 private static final boolean DEBUG_SHOW_INFO = false; 312 private static final boolean DEBUG_PACKAGE_INFO = false; 313 private static final boolean DEBUG_INTENT_MATCHING = false; 314 private static final boolean DEBUG_PACKAGE_SCANNING = false; 315 private static final boolean DEBUG_VERIFY = false; 316 private static final boolean DEBUG_DEXOPT = false; 317 private static final boolean DEBUG_ABI_SELECTION = false; 318 private static final boolean DEBUG_EPHEMERAL = false; 319 private static final boolean DEBUG_TRIAGED_MISSING = false; 320 private static final boolean DEBUG_APP_DATA = false; 321 322 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 323 324 private static final boolean DISABLE_EPHEMERAL_APPS = true; 325 326 private static final int RADIO_UID = Process.PHONE_UID; 327 private static final int LOG_UID = Process.LOG_UID; 328 private static final int NFC_UID = Process.NFC_UID; 329 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 330 private static final int SHELL_UID = Process.SHELL_UID; 331 332 // Cap the size of permission trees that 3rd party apps can define 333 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 334 335 // Suffix used during package installation when copying/moving 336 // package apks to install directory. 337 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 338 339 static final int SCAN_NO_DEX = 1<<1; 340 static final int SCAN_FORCE_DEX = 1<<2; 341 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 342 static final int SCAN_NEW_INSTALL = 1<<4; 343 static final int SCAN_NO_PATHS = 1<<5; 344 static final int SCAN_UPDATE_TIME = 1<<6; 345 static final int SCAN_DEFER_DEX = 1<<7; 346 static final int SCAN_BOOTING = 1<<8; 347 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 348 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 349 static final int SCAN_REPLACING = 1<<11; 350 static final int SCAN_REQUIRE_KNOWN = 1<<12; 351 static final int SCAN_MOVE = 1<<13; 352 static final int SCAN_INITIAL = 1<<14; 353 354 static final int REMOVE_CHATTY = 1<<16; 355 356 private static final int[] EMPTY_INT_ARRAY = new int[0]; 357 358 /** 359 * Timeout (in milliseconds) after which the watchdog should declare that 360 * our handler thread is wedged. The usual default for such things is one 361 * minute but we sometimes do very lengthy I/O operations on this thread, 362 * such as installing multi-gigabyte applications, so ours needs to be longer. 363 */ 364 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 365 366 /** 367 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 368 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 369 * settings entry if available, otherwise we use the hardcoded default. If it's been 370 * more than this long since the last fstrim, we force one during the boot sequence. 371 * 372 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 373 * one gets run at the next available charging+idle time. This final mandatory 374 * no-fstrim check kicks in only of the other scheduling criteria is never met. 375 */ 376 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 377 378 /** 379 * Whether verification is enabled by default. 380 */ 381 private static final boolean DEFAULT_VERIFY_ENABLE = true; 382 383 /** 384 * The default maximum time to wait for the verification agent to return in 385 * milliseconds. 386 */ 387 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 388 389 /** 390 * The default response for package verification timeout. 391 * 392 * This can be either PackageManager.VERIFICATION_ALLOW or 393 * PackageManager.VERIFICATION_REJECT. 394 */ 395 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 396 397 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 398 399 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 400 DEFAULT_CONTAINER_PACKAGE, 401 "com.android.defcontainer.DefaultContainerService"); 402 403 private static final String KILL_APP_REASON_GIDS_CHANGED = 404 "permission grant or revoke changed gids"; 405 406 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 407 "permissions revoked"; 408 409 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 410 411 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 412 413 /** Permission grant: not grant the permission. */ 414 private static final int GRANT_DENIED = 1; 415 416 /** Permission grant: grant the permission as an install permission. */ 417 private static final int GRANT_INSTALL = 2; 418 419 /** Permission grant: grant the permission as a runtime one. */ 420 private static final int GRANT_RUNTIME = 3; 421 422 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 423 private static final int GRANT_UPGRADE = 4; 424 425 /** Canonical intent used to identify what counts as a "web browser" app */ 426 private static final Intent sBrowserIntent; 427 static { 428 sBrowserIntent = new Intent(); 429 sBrowserIntent.setAction(Intent.ACTION_VIEW); 430 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 431 sBrowserIntent.setData(Uri.parse("http:")); 432 } 433 434 final ServiceThread mHandlerThread; 435 436 final PackageHandler mHandler; 437 438 /** 439 * Messages for {@link #mHandler} that need to wait for system ready before 440 * being dispatched. 441 */ 442 private ArrayList<Message> mPostSystemReadyMessages; 443 444 final int mSdkVersion = Build.VERSION.SDK_INT; 445 446 final Context mContext; 447 final boolean mFactoryTest; 448 final boolean mOnlyCore; 449 final DisplayMetrics mMetrics; 450 final int mDefParseFlags; 451 final String[] mSeparateProcesses; 452 final boolean mIsUpgrade; 453 454 /** The location for ASEC container files on internal storage. */ 455 final String mAsecInternalPath; 456 457 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 458 // LOCK HELD. Can be called with mInstallLock held. 459 @GuardedBy("mInstallLock") 460 final Installer mInstaller; 461 462 /** Directory where installed third-party apps stored */ 463 final File mAppInstallDir; 464 final File mEphemeralInstallDir; 465 466 /** 467 * Directory to which applications installed internally have their 468 * 32 bit native libraries copied. 469 */ 470 private File mAppLib32InstallDir; 471 472 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 473 // apps. 474 final File mDrmAppPrivateInstallDir; 475 476 // ---------------------------------------------------------------- 477 478 // Lock for state used when installing and doing other long running 479 // operations. Methods that must be called with this lock held have 480 // the suffix "LI". 481 final Object mInstallLock = new Object(); 482 483 // ---------------------------------------------------------------- 484 485 // Keys are String (package name), values are Package. This also serves 486 // as the lock for the global state. Methods that must be called with 487 // this lock held have the prefix "LP". 488 @GuardedBy("mPackages") 489 final ArrayMap<String, PackageParser.Package> mPackages = 490 new ArrayMap<String, PackageParser.Package>(); 491 492 // Tracks available target package names -> overlay package paths. 493 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 494 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 495 496 /** 497 * Tracks new system packages [received in an OTA] that we expect to 498 * find updated user-installed versions. Keys are package name, values 499 * are package location. 500 */ 501 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 502 503 /** 504 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 505 */ 506 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 507 /** 508 * Whether or not system app permissions should be promoted from install to runtime. 509 */ 510 boolean mPromoteSystemApps; 511 512 final Settings mSettings; 513 boolean mRestoredSettings; 514 515 // System configuration read by SystemConfig. 516 final int[] mGlobalGids; 517 final SparseArray<ArraySet<String>> mSystemPermissions; 518 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 519 520 // If mac_permissions.xml was found for seinfo labeling. 521 boolean mFoundPolicyFile; 522 523 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 524 525 public static final class SharedLibraryEntry { 526 public final String path; 527 public final String apk; 528 529 SharedLibraryEntry(String _path, String _apk) { 530 path = _path; 531 apk = _apk; 532 } 533 } 534 535 // Currently known shared libraries. 536 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 537 new ArrayMap<String, SharedLibraryEntry>(); 538 539 // All available activities, for your resolving pleasure. 540 final ActivityIntentResolver mActivities = 541 new ActivityIntentResolver(); 542 543 // All available receivers, for your resolving pleasure. 544 final ActivityIntentResolver mReceivers = 545 new ActivityIntentResolver(); 546 547 // All available services, for your resolving pleasure. 548 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 549 550 // All available providers, for your resolving pleasure. 551 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 552 553 // Mapping from provider base names (first directory in content URI codePath) 554 // to the provider information. 555 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 556 new ArrayMap<String, PackageParser.Provider>(); 557 558 // Mapping from instrumentation class names to info about them. 559 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 560 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 561 562 // Mapping from permission names to info about them. 563 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 564 new ArrayMap<String, PackageParser.PermissionGroup>(); 565 566 // Packages whose data we have transfered into another package, thus 567 // should no longer exist. 568 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 569 570 // Broadcast actions that are only available to the system. 571 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 572 573 /** List of packages waiting for verification. */ 574 final SparseArray<PackageVerificationState> mPendingVerification 575 = new SparseArray<PackageVerificationState>(); 576 577 /** Set of packages associated with each app op permission. */ 578 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 579 580 final PackageInstallerService mInstallerService; 581 582 private final PackageDexOptimizer mPackageDexOptimizer; 583 584 private AtomicInteger mNextMoveId = new AtomicInteger(); 585 private final MoveCallbacks mMoveCallbacks; 586 587 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 588 589 // Cache of users who need badging. 590 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 591 592 /** Token for keys in mPendingVerification. */ 593 private int mPendingVerificationToken = 0; 594 595 volatile boolean mSystemReady; 596 volatile boolean mSafeMode; 597 volatile boolean mHasSystemUidErrors; 598 599 ApplicationInfo mAndroidApplication; 600 final ActivityInfo mResolveActivity = new ActivityInfo(); 601 final ResolveInfo mResolveInfo = new ResolveInfo(); 602 ComponentName mResolveComponentName; 603 PackageParser.Package mPlatformPackage; 604 ComponentName mCustomResolverComponentName; 605 606 boolean mResolverReplaced = false; 607 608 private final @Nullable ComponentName mIntentFilterVerifierComponent; 609 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 610 611 private int mIntentFilterVerificationToken = 0; 612 613 /** Component that knows whether or not an ephemeral application exists */ 614 final ComponentName mEphemeralResolverComponent; 615 /** The service connection to the ephemeral resolver */ 616 final EphemeralResolverConnection mEphemeralResolverConnection; 617 618 /** Component used to install ephemeral applications */ 619 final ComponentName mEphemeralInstallerComponent; 620 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 621 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 622 623 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 624 = new SparseArray<IntentFilterVerificationState>(); 625 626 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 627 new DefaultPermissionGrantPolicy(this); 628 629 // List of packages names to keep cached, even if they are uninstalled for all users 630 private List<String> mKeepUninstalledPackages; 631 632 private boolean mUseJitProfiles = 633 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 634 635 private static class IFVerificationParams { 636 PackageParser.Package pkg; 637 boolean replacing; 638 int userId; 639 int verifierUid; 640 641 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 642 int _userId, int _verifierUid) { 643 pkg = _pkg; 644 replacing = _replacing; 645 userId = _userId; 646 replacing = _replacing; 647 verifierUid = _verifierUid; 648 } 649 } 650 651 private interface IntentFilterVerifier<T extends IntentFilter> { 652 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 653 T filter, String packageName); 654 void startVerifications(int userId); 655 void receiveVerificationResponse(int verificationId); 656 } 657 658 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 659 private Context mContext; 660 private ComponentName mIntentFilterVerifierComponent; 661 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 662 663 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 664 mContext = context; 665 mIntentFilterVerifierComponent = verifierComponent; 666 } 667 668 private String getDefaultScheme() { 669 return IntentFilter.SCHEME_HTTPS; 670 } 671 672 @Override 673 public void startVerifications(int userId) { 674 // Launch verifications requests 675 int count = mCurrentIntentFilterVerifications.size(); 676 for (int n=0; n<count; n++) { 677 int verificationId = mCurrentIntentFilterVerifications.get(n); 678 final IntentFilterVerificationState ivs = 679 mIntentFilterVerificationStates.get(verificationId); 680 681 String packageName = ivs.getPackageName(); 682 683 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 684 final int filterCount = filters.size(); 685 ArraySet<String> domainsSet = new ArraySet<>(); 686 for (int m=0; m<filterCount; m++) { 687 PackageParser.ActivityIntentInfo filter = filters.get(m); 688 domainsSet.addAll(filter.getHostsList()); 689 } 690 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 691 synchronized (mPackages) { 692 if (mSettings.createIntentFilterVerificationIfNeededLPw( 693 packageName, domainsList) != null) { 694 scheduleWriteSettingsLocked(); 695 } 696 } 697 sendVerificationRequest(userId, verificationId, ivs); 698 } 699 mCurrentIntentFilterVerifications.clear(); 700 } 701 702 private void sendVerificationRequest(int userId, int verificationId, 703 IntentFilterVerificationState ivs) { 704 705 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 706 verificationIntent.putExtra( 707 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 708 verificationId); 709 verificationIntent.putExtra( 710 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 711 getDefaultScheme()); 712 verificationIntent.putExtra( 713 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 714 ivs.getHostsString()); 715 verificationIntent.putExtra( 716 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 717 ivs.getPackageName()); 718 verificationIntent.setComponent(mIntentFilterVerifierComponent); 719 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 720 721 UserHandle user = new UserHandle(userId); 722 mContext.sendBroadcastAsUser(verificationIntent, user); 723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 724 "Sending IntentFilter verification broadcast"); 725 } 726 727 public void receiveVerificationResponse(int verificationId) { 728 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 729 730 final boolean verified = ivs.isVerified(); 731 732 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 733 final int count = filters.size(); 734 if (DEBUG_DOMAIN_VERIFICATION) { 735 Slog.i(TAG, "Received verification response " + verificationId 736 + " for " + count + " filters, verified=" + verified); 737 } 738 for (int n=0; n<count; n++) { 739 PackageParser.ActivityIntentInfo filter = filters.get(n); 740 filter.setVerified(verified); 741 742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 743 + " verified with result:" + verified + " and hosts:" 744 + ivs.getHostsString()); 745 } 746 747 mIntentFilterVerificationStates.remove(verificationId); 748 749 final String packageName = ivs.getPackageName(); 750 IntentFilterVerificationInfo ivi = null; 751 752 synchronized (mPackages) { 753 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 754 } 755 if (ivi == null) { 756 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 757 + verificationId + " packageName:" + packageName); 758 return; 759 } 760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 761 "Updating IntentFilterVerificationInfo for package " + packageName 762 +" verificationId:" + verificationId); 763 764 synchronized (mPackages) { 765 if (verified) { 766 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 767 } else { 768 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 769 } 770 scheduleWriteSettingsLocked(); 771 772 final int userId = ivs.getUserId(); 773 if (userId != UserHandle.USER_ALL) { 774 final int userStatus = 775 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 776 777 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 778 boolean needUpdate = false; 779 780 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 781 // already been set by the User thru the Disambiguation dialog 782 switch (userStatus) { 783 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 784 if (verified) { 785 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 786 } else { 787 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 788 } 789 needUpdate = true; 790 break; 791 792 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 793 if (verified) { 794 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 795 needUpdate = true; 796 } 797 break; 798 799 default: 800 // Nothing to do 801 } 802 803 if (needUpdate) { 804 mSettings.updateIntentFilterVerificationStatusLPw( 805 packageName, updatedStatus, userId); 806 scheduleWritePackageRestrictionsLocked(userId); 807 } 808 } 809 } 810 } 811 812 @Override 813 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 814 ActivityIntentInfo filter, String packageName) { 815 if (!hasValidDomains(filter)) { 816 return false; 817 } 818 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 819 if (ivs == null) { 820 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 821 packageName); 822 } 823 if (DEBUG_DOMAIN_VERIFICATION) { 824 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 825 } 826 ivs.addFilter(filter); 827 return true; 828 } 829 830 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 831 int userId, int verificationId, String packageName) { 832 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 833 verifierUid, userId, packageName); 834 ivs.setPendingState(); 835 synchronized (mPackages) { 836 mIntentFilterVerificationStates.append(verificationId, ivs); 837 mCurrentIntentFilterVerifications.add(verificationId); 838 } 839 return ivs; 840 } 841 } 842 843 private static boolean hasValidDomains(ActivityIntentInfo filter) { 844 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 845 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 846 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 847 } 848 849 // Set of pending broadcasts for aggregating enable/disable of components. 850 static class PendingPackageBroadcasts { 851 // for each user id, a map of <package name -> components within that package> 852 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 853 854 public PendingPackageBroadcasts() { 855 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 856 } 857 858 public ArrayList<String> get(int userId, String packageName) { 859 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 860 return packages.get(packageName); 861 } 862 863 public void put(int userId, String packageName, ArrayList<String> components) { 864 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 865 packages.put(packageName, components); 866 } 867 868 public void remove(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 870 if (packages != null) { 871 packages.remove(packageName); 872 } 873 } 874 875 public void remove(int userId) { 876 mUidMap.remove(userId); 877 } 878 879 public int userIdCount() { 880 return mUidMap.size(); 881 } 882 883 public int userIdAt(int n) { 884 return mUidMap.keyAt(n); 885 } 886 887 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 888 return mUidMap.get(userId); 889 } 890 891 public int size() { 892 // total number of pending broadcast entries across all userIds 893 int num = 0; 894 for (int i = 0; i< mUidMap.size(); i++) { 895 num += mUidMap.valueAt(i).size(); 896 } 897 return num; 898 } 899 900 public void clear() { 901 mUidMap.clear(); 902 } 903 904 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 905 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 906 if (map == null) { 907 map = new ArrayMap<String, ArrayList<String>>(); 908 mUidMap.put(userId, map); 909 } 910 return map; 911 } 912 } 913 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 914 915 // Service Connection to remote media container service to copy 916 // package uri's from external media onto secure containers 917 // or internal storage. 918 private IMediaContainerService mContainerService = null; 919 920 static final int SEND_PENDING_BROADCAST = 1; 921 static final int MCS_BOUND = 3; 922 static final int END_COPY = 4; 923 static final int INIT_COPY = 5; 924 static final int MCS_UNBIND = 6; 925 static final int START_CLEANING_PACKAGE = 7; 926 static final int FIND_INSTALL_LOC = 8; 927 static final int POST_INSTALL = 9; 928 static final int MCS_RECONNECT = 10; 929 static final int MCS_GIVE_UP = 11; 930 static final int UPDATED_MEDIA_STATUS = 12; 931 static final int WRITE_SETTINGS = 13; 932 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 933 static final int PACKAGE_VERIFIED = 15; 934 static final int CHECK_PENDING_VERIFICATION = 16; 935 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 936 static final int INTENT_FILTER_VERIFIED = 18; 937 938 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 939 940 // Delay time in millisecs 941 static final int BROADCAST_DELAY = 10 * 1000; 942 943 static UserManagerService sUserManager; 944 945 // Stores a list of users whose package restrictions file needs to be updated 946 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 947 948 final private DefaultContainerConnection mDefContainerConn = 949 new DefaultContainerConnection(); 950 class DefaultContainerConnection implements ServiceConnection { 951 public void onServiceConnected(ComponentName name, IBinder service) { 952 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 953 IMediaContainerService imcs = 954 IMediaContainerService.Stub.asInterface(service); 955 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 956 } 957 958 public void onServiceDisconnected(ComponentName name) { 959 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 960 } 961 } 962 963 // Recordkeeping of restore-after-install operations that are currently in flight 964 // between the Package Manager and the Backup Manager 965 static class PostInstallData { 966 public InstallArgs args; 967 public PackageInstalledInfo res; 968 969 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 970 args = _a; 971 res = _r; 972 } 973 } 974 975 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 976 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 977 978 // XML tags for backup/restore of various bits of state 979 private static final String TAG_PREFERRED_BACKUP = "pa"; 980 private static final String TAG_DEFAULT_APPS = "da"; 981 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 982 983 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 984 private static final String TAG_ALL_GRANTS = "rt-grants"; 985 private static final String TAG_GRANT = "grant"; 986 private static final String ATTR_PACKAGE_NAME = "pkg"; 987 988 private static final String TAG_PERMISSION = "perm"; 989 private static final String ATTR_PERMISSION_NAME = "name"; 990 private static final String ATTR_IS_GRANTED = "g"; 991 private static final String ATTR_USER_SET = "set"; 992 private static final String ATTR_USER_FIXED = "fixed"; 993 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 994 995 // System/policy permission grants are not backed up 996 private static final int SYSTEM_RUNTIME_GRANT_MASK = 997 FLAG_PERMISSION_POLICY_FIXED 998 | FLAG_PERMISSION_SYSTEM_FIXED 999 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1000 1001 // And we back up these user-adjusted states 1002 private static final int USER_RUNTIME_GRANT_MASK = 1003 FLAG_PERMISSION_USER_SET 1004 | FLAG_PERMISSION_USER_FIXED 1005 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1006 1007 final @Nullable String mRequiredVerifierPackage; 1008 final @Nullable String mRequiredInstallerPackage; 1009 1010 private final PackageUsage mPackageUsage = new PackageUsage(); 1011 1012 private class PackageUsage { 1013 private static final int WRITE_INTERVAL 1014 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1015 1016 private final Object mFileLock = new Object(); 1017 private final AtomicLong mLastWritten = new AtomicLong(0); 1018 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1019 1020 private boolean mIsHistoricalPackageUsageAvailable = true; 1021 1022 boolean isHistoricalPackageUsageAvailable() { 1023 return mIsHistoricalPackageUsageAvailable; 1024 } 1025 1026 void write(boolean force) { 1027 if (force) { 1028 writeInternal(); 1029 return; 1030 } 1031 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1032 && !DEBUG_DEXOPT) { 1033 return; 1034 } 1035 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1036 new Thread("PackageUsage_DiskWriter") { 1037 @Override 1038 public void run() { 1039 try { 1040 writeInternal(); 1041 } finally { 1042 mBackgroundWriteRunning.set(false); 1043 } 1044 } 1045 }.start(); 1046 } 1047 } 1048 1049 private void writeInternal() { 1050 synchronized (mPackages) { 1051 synchronized (mFileLock) { 1052 AtomicFile file = getFile(); 1053 FileOutputStream f = null; 1054 try { 1055 f = file.startWrite(); 1056 BufferedOutputStream out = new BufferedOutputStream(f); 1057 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1058 StringBuilder sb = new StringBuilder(); 1059 for (PackageParser.Package pkg : mPackages.values()) { 1060 if (pkg.mLastPackageUsageTimeInMills == 0) { 1061 continue; 1062 } 1063 sb.setLength(0); 1064 sb.append(pkg.packageName); 1065 sb.append(' '); 1066 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1067 sb.append('\n'); 1068 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1069 } 1070 out.flush(); 1071 file.finishWrite(f); 1072 } catch (IOException e) { 1073 if (f != null) { 1074 file.failWrite(f); 1075 } 1076 Log.e(TAG, "Failed to write package usage times", e); 1077 } 1078 } 1079 } 1080 mLastWritten.set(SystemClock.elapsedRealtime()); 1081 } 1082 1083 void readLP() { 1084 synchronized (mFileLock) { 1085 AtomicFile file = getFile(); 1086 BufferedInputStream in = null; 1087 try { 1088 in = new BufferedInputStream(file.openRead()); 1089 StringBuffer sb = new StringBuffer(); 1090 while (true) { 1091 String packageName = readToken(in, sb, ' '); 1092 if (packageName == null) { 1093 break; 1094 } 1095 String timeInMillisString = readToken(in, sb, '\n'); 1096 if (timeInMillisString == null) { 1097 throw new IOException("Failed to find last usage time for package " 1098 + packageName); 1099 } 1100 PackageParser.Package pkg = mPackages.get(packageName); 1101 if (pkg == null) { 1102 continue; 1103 } 1104 long timeInMillis; 1105 try { 1106 timeInMillis = Long.parseLong(timeInMillisString); 1107 } catch (NumberFormatException e) { 1108 throw new IOException("Failed to parse " + timeInMillisString 1109 + " as a long.", e); 1110 } 1111 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1112 } 1113 } catch (FileNotFoundException expected) { 1114 mIsHistoricalPackageUsageAvailable = false; 1115 } catch (IOException e) { 1116 Log.w(TAG, "Failed to read package usage times", e); 1117 } finally { 1118 IoUtils.closeQuietly(in); 1119 } 1120 } 1121 mLastWritten.set(SystemClock.elapsedRealtime()); 1122 } 1123 1124 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1125 throws IOException { 1126 sb.setLength(0); 1127 while (true) { 1128 int ch = in.read(); 1129 if (ch == -1) { 1130 if (sb.length() == 0) { 1131 return null; 1132 } 1133 throw new IOException("Unexpected EOF"); 1134 } 1135 if (ch == endOfToken) { 1136 return sb.toString(); 1137 } 1138 sb.append((char)ch); 1139 } 1140 } 1141 1142 private AtomicFile getFile() { 1143 File dataDir = Environment.getDataDirectory(); 1144 File systemDir = new File(dataDir, "system"); 1145 File fname = new File(systemDir, "package-usage.list"); 1146 return new AtomicFile(fname); 1147 } 1148 } 1149 1150 class PackageHandler extends Handler { 1151 private boolean mBound = false; 1152 final ArrayList<HandlerParams> mPendingInstalls = 1153 new ArrayList<HandlerParams>(); 1154 1155 private boolean connectToService() { 1156 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1157 " DefaultContainerService"); 1158 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1159 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1160 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1161 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1162 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1163 mBound = true; 1164 return true; 1165 } 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 return false; 1168 } 1169 1170 private void disconnectService() { 1171 mContainerService = null; 1172 mBound = false; 1173 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1174 mContext.unbindService(mDefContainerConn); 1175 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1176 } 1177 1178 PackageHandler(Looper looper) { 1179 super(looper); 1180 } 1181 1182 public void handleMessage(Message msg) { 1183 try { 1184 doHandleMessage(msg); 1185 } finally { 1186 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1187 } 1188 } 1189 1190 void doHandleMessage(Message msg) { 1191 switch (msg.what) { 1192 case INIT_COPY: { 1193 HandlerParams params = (HandlerParams) msg.obj; 1194 int idx = mPendingInstalls.size(); 1195 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1196 // If a bind was already initiated we dont really 1197 // need to do anything. The pending install 1198 // will be processed later on. 1199 if (!mBound) { 1200 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1201 System.identityHashCode(mHandler)); 1202 // If this is the only one pending we might 1203 // have to bind to the service again. 1204 if (!connectToService()) { 1205 Slog.e(TAG, "Failed to bind to media container service"); 1206 params.serviceError(); 1207 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1208 System.identityHashCode(mHandler)); 1209 if (params.traceMethod != null) { 1210 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1211 params.traceCookie); 1212 } 1213 return; 1214 } else { 1215 // Once we bind to the service, the first 1216 // pending request will be processed. 1217 mPendingInstalls.add(idx, params); 1218 } 1219 } else { 1220 mPendingInstalls.add(idx, params); 1221 // Already bound to the service. Just make 1222 // sure we trigger off processing the first request. 1223 if (idx == 0) { 1224 mHandler.sendEmptyMessage(MCS_BOUND); 1225 } 1226 } 1227 break; 1228 } 1229 case MCS_BOUND: { 1230 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1231 if (msg.obj != null) { 1232 mContainerService = (IMediaContainerService) msg.obj; 1233 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1234 System.identityHashCode(mHandler)); 1235 } 1236 if (mContainerService == null) { 1237 if (!mBound) { 1238 // Something seriously wrong since we are not bound and we are not 1239 // waiting for connection. Bail out. 1240 Slog.e(TAG, "Cannot bind to media container service"); 1241 for (HandlerParams params : mPendingInstalls) { 1242 // Indicate service bind error 1243 params.serviceError(); 1244 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1245 System.identityHashCode(params)); 1246 if (params.traceMethod != null) { 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1248 params.traceMethod, params.traceCookie); 1249 } 1250 return; 1251 } 1252 mPendingInstalls.clear(); 1253 } else { 1254 Slog.w(TAG, "Waiting to connect to media container service"); 1255 } 1256 } else if (mPendingInstalls.size() > 0) { 1257 HandlerParams params = mPendingInstalls.get(0); 1258 if (params != null) { 1259 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1260 System.identityHashCode(params)); 1261 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1262 if (params.startCopy()) { 1263 // We are done... look for more work or to 1264 // go idle. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Checking for more work or unbind..."); 1267 // Delete pending install 1268 if (mPendingInstalls.size() > 0) { 1269 mPendingInstalls.remove(0); 1270 } 1271 if (mPendingInstalls.size() == 0) { 1272 if (mBound) { 1273 if (DEBUG_SD_INSTALL) Log.i(TAG, 1274 "Posting delayed MCS_UNBIND"); 1275 removeMessages(MCS_UNBIND); 1276 Message ubmsg = obtainMessage(MCS_UNBIND); 1277 // Unbind after a little delay, to avoid 1278 // continual thrashing. 1279 sendMessageDelayed(ubmsg, 10000); 1280 } 1281 } else { 1282 // There are more pending requests in queue. 1283 // Just post MCS_BOUND message to trigger processing 1284 // of next pending install. 1285 if (DEBUG_SD_INSTALL) Log.i(TAG, 1286 "Posting MCS_BOUND for next work"); 1287 mHandler.sendEmptyMessage(MCS_BOUND); 1288 } 1289 } 1290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1291 } 1292 } else { 1293 // Should never happen ideally. 1294 Slog.w(TAG, "Empty queue"); 1295 } 1296 break; 1297 } 1298 case MCS_RECONNECT: { 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1300 if (mPendingInstalls.size() > 0) { 1301 if (mBound) { 1302 disconnectService(); 1303 } 1304 if (!connectToService()) { 1305 Slog.e(TAG, "Failed to bind to media container service"); 1306 for (HandlerParams params : mPendingInstalls) { 1307 // Indicate service bind error 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1310 System.identityHashCode(params)); 1311 } 1312 mPendingInstalls.clear(); 1313 } 1314 } 1315 break; 1316 } 1317 case MCS_UNBIND: { 1318 // If there is no actual work left, then time to unbind. 1319 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1320 1321 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1322 if (mBound) { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1324 1325 disconnectService(); 1326 } 1327 } else if (mPendingInstalls.size() > 0) { 1328 // There are more pending requests in queue. 1329 // Just post MCS_BOUND message to trigger processing 1330 // of next pending install. 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 1334 break; 1335 } 1336 case MCS_GIVE_UP: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1338 HandlerParams params = mPendingInstalls.remove(0); 1339 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1340 System.identityHashCode(params)); 1341 break; 1342 } 1343 case SEND_PENDING_BROADCAST: { 1344 String packages[]; 1345 ArrayList<String> components[]; 1346 int size = 0; 1347 int uids[]; 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1349 synchronized (mPackages) { 1350 if (mPendingBroadcasts == null) { 1351 return; 1352 } 1353 size = mPendingBroadcasts.size(); 1354 if (size <= 0) { 1355 // Nothing to be done. Just return 1356 return; 1357 } 1358 packages = new String[size]; 1359 components = new ArrayList[size]; 1360 uids = new int[size]; 1361 int i = 0; // filling out the above arrays 1362 1363 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1364 int packageUserId = mPendingBroadcasts.userIdAt(n); 1365 Iterator<Map.Entry<String, ArrayList<String>>> it 1366 = mPendingBroadcasts.packagesForUserId(packageUserId) 1367 .entrySet().iterator(); 1368 while (it.hasNext() && i < size) { 1369 Map.Entry<String, ArrayList<String>> ent = it.next(); 1370 packages[i] = ent.getKey(); 1371 components[i] = ent.getValue(); 1372 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1373 uids[i] = (ps != null) 1374 ? UserHandle.getUid(packageUserId, ps.appId) 1375 : -1; 1376 i++; 1377 } 1378 } 1379 size = i; 1380 mPendingBroadcasts.clear(); 1381 } 1382 // Send broadcasts 1383 for (int i = 0; i < size; i++) { 1384 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 break; 1388 } 1389 case START_CLEANING_PACKAGE: { 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1391 final String packageName = (String)msg.obj; 1392 final int userId = msg.arg1; 1393 final boolean andCode = msg.arg2 != 0; 1394 synchronized (mPackages) { 1395 if (userId == UserHandle.USER_ALL) { 1396 int[] users = sUserManager.getUserIds(); 1397 for (int user : users) { 1398 mSettings.addPackageToCleanLPw( 1399 new PackageCleanItem(user, packageName, andCode)); 1400 } 1401 } else { 1402 mSettings.addPackageToCleanLPw( 1403 new PackageCleanItem(userId, packageName, andCode)); 1404 } 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 startCleaningPackages(); 1408 } break; 1409 case POST_INSTALL: { 1410 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1411 1412 PostInstallData data = mRunningInstalls.get(msg.arg1); 1413 mRunningInstalls.delete(msg.arg1); 1414 boolean deleteOld = false; 1415 1416 if (data != null) { 1417 InstallArgs args = data.args; 1418 PackageInstalledInfo res = data.res; 1419 1420 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1421 final String packageName = res.pkg.applicationInfo.packageName; 1422 res.removedInfo.sendBroadcast(false, true, false); 1423 Bundle extras = new Bundle(1); 1424 extras.putInt(Intent.EXTRA_UID, res.uid); 1425 1426 // Now that we successfully installed the package, grant runtime 1427 // permissions if requested before broadcasting the install. 1428 if ((args.installFlags 1429 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1430 && res.pkg.applicationInfo.targetSdkVersion 1431 >= Build.VERSION_CODES.M) { 1432 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1433 args.installGrantPermissions); 1434 } 1435 1436 synchronized (mPackages) { 1437 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1438 } 1439 1440 // Determine the set of users who are adding this 1441 // package for the first time vs. those who are seeing 1442 // an update. 1443 int[] firstUsers; 1444 int[] updateUsers = new int[0]; 1445 if (res.origUsers == null || res.origUsers.length == 0) { 1446 firstUsers = res.newUsers; 1447 } else { 1448 firstUsers = new int[0]; 1449 for (int i=0; i<res.newUsers.length; i++) { 1450 int user = res.newUsers[i]; 1451 boolean isNew = true; 1452 for (int j=0; j<res.origUsers.length; j++) { 1453 if (res.origUsers[j] == user) { 1454 isNew = false; 1455 break; 1456 } 1457 } 1458 if (isNew) { 1459 int[] newFirst = new int[firstUsers.length+1]; 1460 System.arraycopy(firstUsers, 0, newFirst, 0, 1461 firstUsers.length); 1462 newFirst[firstUsers.length] = user; 1463 firstUsers = newFirst; 1464 } else { 1465 int[] newUpdate = new int[updateUsers.length+1]; 1466 System.arraycopy(updateUsers, 0, newUpdate, 0, 1467 updateUsers.length); 1468 newUpdate[updateUsers.length] = user; 1469 updateUsers = newUpdate; 1470 } 1471 } 1472 } 1473 // don't broadcast for ephemeral installs/updates 1474 final boolean isEphemeral = isEphemeral(res.pkg); 1475 if (!isEphemeral) { 1476 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1477 extras, 0 /*flags*/, null /*targetPackage*/, 1478 null /*finishedReceiver*/, firstUsers); 1479 } 1480 final boolean update = res.removedInfo.removedPackage != null; 1481 if (update) { 1482 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1483 } 1484 if (!isEphemeral) { 1485 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1486 extras, 0 /*flags*/, null /*targetPackage*/, 1487 null /*finishedReceiver*/, updateUsers); 1488 } 1489 if (update) { 1490 if (!isEphemeral) { 1491 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1492 packageName, extras, 0 /*flags*/, 1493 null /*targetPackage*/, null /*finishedReceiver*/, 1494 updateUsers); 1495 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1496 null /*package*/, null /*extras*/, 0 /*flags*/, 1497 packageName /*targetPackage*/, 1498 null /*finishedReceiver*/, updateUsers); 1499 } 1500 1501 // treat asec-hosted packages like removable media on upgrade 1502 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1503 if (DEBUG_INSTALL) { 1504 Slog.i(TAG, "upgrading pkg " + res.pkg 1505 + " is ASEC-hosted -> AVAILABLE"); 1506 } 1507 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1508 ArrayList<String> pkgList = new ArrayList<String>(1); 1509 pkgList.add(packageName); 1510 sendResourcesChangedBroadcast(true, true, 1511 pkgList,uidArray, null); 1512 } 1513 } 1514 if (res.removedInfo.args != null) { 1515 // Remove the replaced package's older resources safely now 1516 deleteOld = true; 1517 } 1518 1519 1520 // Work that needs to happen on first install within each user 1521 if (firstUsers.length > 0) { 1522 for (int userId : firstUsers) { 1523 synchronized (mPackages) { 1524 // If this app is a browser and it's newly-installed for 1525 // some users, clear any default-browser state in those 1526 // users. The app's nature doesn't depend on the user, 1527 // so we can just check its browser nature in any user 1528 // and generalize. 1529 if (packageIsBrowser(packageName, firstUsers[0])) { 1530 mSettings.setDefaultBrowserPackageNameLPw( 1531 null, userId); 1532 } 1533 1534 // We may also need to apply pending (restored) runtime 1535 // permission grants within these users. 1536 mSettings.applyPendingPermissionGrantsLPw( 1537 packageName, userId); 1538 } 1539 } 1540 } 1541 // Log current value of "unknown sources" setting 1542 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1543 getUnknownSourcesSettings()); 1544 } 1545 // Force a gc to clear up things 1546 Runtime.getRuntime().gc(); 1547 // We delete after a gc for applications on sdcard. 1548 if (deleteOld) { 1549 synchronized (mInstallLock) { 1550 res.removedInfo.args.doPostDeleteLI(true); 1551 } 1552 } 1553 if (args.observer != null) { 1554 try { 1555 Bundle extras = extrasForInstallResult(res); 1556 args.observer.onPackageInstalled(res.name, res.returnCode, 1557 res.returnMsg, extras); 1558 } catch (RemoteException e) { 1559 Slog.i(TAG, "Observer no longer exists."); 1560 } 1561 } 1562 if (args.traceMethod != null) { 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1564 args.traceCookie); 1565 } 1566 return; 1567 } else { 1568 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1569 } 1570 1571 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1572 } break; 1573 case UPDATED_MEDIA_STATUS: { 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1575 boolean reportStatus = msg.arg1 == 1; 1576 boolean doGc = msg.arg2 == 1; 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1578 if (doGc) { 1579 // Force a gc to clear up stale containers. 1580 Runtime.getRuntime().gc(); 1581 } 1582 if (msg.obj != null) { 1583 @SuppressWarnings("unchecked") 1584 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1586 // Unload containers 1587 unloadAllContainers(args); 1588 } 1589 if (reportStatus) { 1590 try { 1591 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1592 PackageHelper.getMountService().finishMediaUpdate(); 1593 } catch (RemoteException e) { 1594 Log.e(TAG, "MountService not running?"); 1595 } 1596 } 1597 } break; 1598 case WRITE_SETTINGS: { 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1600 synchronized (mPackages) { 1601 removeMessages(WRITE_SETTINGS); 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 mSettings.writeLPr(); 1604 mDirtyUsers.clear(); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case WRITE_PACKAGE_RESTRICTIONS: { 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1610 synchronized (mPackages) { 1611 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1612 for (int userId : mDirtyUsers) { 1613 mSettings.writePackageRestrictionsLPr(userId); 1614 } 1615 mDirtyUsers.clear(); 1616 } 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1618 } break; 1619 case CHECK_PENDING_VERIFICATION: { 1620 final int verificationId = msg.arg1; 1621 final PackageVerificationState state = mPendingVerification.get(verificationId); 1622 1623 if ((state != null) && !state.timeoutExtended()) { 1624 final InstallArgs args = state.getInstallArgs(); 1625 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1626 1627 Slog.i(TAG, "Verification timed out for " + originUri); 1628 mPendingVerification.remove(verificationId); 1629 1630 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1631 1632 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1633 Slog.i(TAG, "Continuing with installation of " + originUri); 1634 state.setVerifierResponse(Binder.getCallingUid(), 1635 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1636 broadcastPackageVerified(verificationId, originUri, 1637 PackageManager.VERIFICATION_ALLOW, 1638 state.getInstallArgs().getUser()); 1639 try { 1640 ret = args.copyApk(mContainerService, true); 1641 } catch (RemoteException e) { 1642 Slog.e(TAG, "Could not contact the ContainerService"); 1643 } 1644 } else { 1645 broadcastPackageVerified(verificationId, originUri, 1646 PackageManager.VERIFICATION_REJECT, 1647 state.getInstallArgs().getUser()); 1648 } 1649 1650 Trace.asyncTraceEnd( 1651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1652 1653 processPendingInstall(args, ret); 1654 mHandler.sendEmptyMessage(MCS_UNBIND); 1655 } 1656 break; 1657 } 1658 case PACKAGE_VERIFIED: { 1659 final int verificationId = msg.arg1; 1660 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 if (state == null) { 1663 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1664 break; 1665 } 1666 1667 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1668 1669 state.setVerifierResponse(response.callerUid, response.code); 1670 1671 if (state.isVerificationComplete()) { 1672 mPendingVerification.remove(verificationId); 1673 1674 final InstallArgs args = state.getInstallArgs(); 1675 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1676 1677 int ret; 1678 if (state.isInstallAllowed()) { 1679 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1680 broadcastPackageVerified(verificationId, originUri, 1681 response.code, state.getInstallArgs().getUser()); 1682 try { 1683 ret = args.copyApk(mContainerService, true); 1684 } catch (RemoteException e) { 1685 Slog.e(TAG, "Could not contact the ContainerService"); 1686 } 1687 } else { 1688 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1689 } 1690 1691 Trace.asyncTraceEnd( 1692 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1693 1694 processPendingInstall(args, ret); 1695 mHandler.sendEmptyMessage(MCS_UNBIND); 1696 } 1697 1698 break; 1699 } 1700 case START_INTENT_FILTER_VERIFICATIONS: { 1701 IFVerificationParams params = (IFVerificationParams) msg.obj; 1702 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1703 params.replacing, params.pkg); 1704 break; 1705 } 1706 case INTENT_FILTER_VERIFIED: { 1707 final int verificationId = msg.arg1; 1708 1709 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1710 verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid IntentFilter verification token " 1713 + verificationId + " received"); 1714 break; 1715 } 1716 1717 final int userId = state.getUserId(); 1718 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1720 "Processing IntentFilter verification with token:" 1721 + verificationId + " and userId:" + userId); 1722 1723 final IntentFilterVerificationResponse response = 1724 (IntentFilterVerificationResponse) msg.obj; 1725 1726 state.setVerifierResponse(response.callerUid, response.code); 1727 1728 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1729 "IntentFilter verification with token:" + verificationId 1730 + " and userId:" + userId 1731 + " is settings verifier response with response code:" 1732 + response.code); 1733 1734 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1735 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1736 + response.getFailedDomainsString()); 1737 } 1738 1739 if (state.isVerificationComplete()) { 1740 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1741 } else { 1742 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1743 "IntentFilter verification with token:" + verificationId 1744 + " was not said to be complete"); 1745 } 1746 1747 break; 1748 } 1749 } 1750 } 1751 } 1752 1753 private StorageEventListener mStorageListener = new StorageEventListener() { 1754 @Override 1755 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1756 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1757 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1758 final String volumeUuid = vol.getFsUuid(); 1759 1760 // Clean up any users or apps that were removed or recreated 1761 // while this volume was missing 1762 reconcileUsers(volumeUuid); 1763 reconcileApps(volumeUuid); 1764 1765 // Clean up any install sessions that expired or were 1766 // cancelled while this volume was missing 1767 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1768 1769 loadPrivatePackages(vol); 1770 1771 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1772 unloadPrivatePackages(vol); 1773 } 1774 } 1775 1776 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1777 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1778 updateExternalMediaStatus(true, false); 1779 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1780 updateExternalMediaStatus(false, false); 1781 } 1782 } 1783 } 1784 1785 @Override 1786 public void onVolumeForgotten(String fsUuid) { 1787 if (TextUtils.isEmpty(fsUuid)) { 1788 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1789 return; 1790 } 1791 1792 // Remove any apps installed on the forgotten volume 1793 synchronized (mPackages) { 1794 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1795 for (PackageSetting ps : packages) { 1796 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1797 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1798 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1799 } 1800 1801 mSettings.onVolumeForgotten(fsUuid); 1802 mSettings.writeLPr(); 1803 } 1804 } 1805 }; 1806 1807 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1808 String[] grantedPermissions) { 1809 if (userId >= UserHandle.USER_SYSTEM) { 1810 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1811 } else if (userId == UserHandle.USER_ALL) { 1812 final int[] userIds; 1813 synchronized (mPackages) { 1814 userIds = UserManagerService.getInstance().getUserIds(); 1815 } 1816 for (int someUserId : userIds) { 1817 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1818 } 1819 } 1820 1821 // We could have touched GID membership, so flush out packages.list 1822 synchronized (mPackages) { 1823 mSettings.writePackageListLPr(); 1824 } 1825 } 1826 1827 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1828 String[] grantedPermissions) { 1829 SettingBase sb = (SettingBase) pkg.mExtras; 1830 if (sb == null) { 1831 return; 1832 } 1833 1834 PermissionsState permissionsState = sb.getPermissionsState(); 1835 1836 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1837 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1838 1839 synchronized (mPackages) { 1840 for (String permission : pkg.requestedPermissions) { 1841 BasePermission bp = mSettings.mPermissions.get(permission); 1842 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1843 && (grantedPermissions == null 1844 || ArrayUtils.contains(grantedPermissions, permission))) { 1845 final int flags = permissionsState.getPermissionFlags(permission, userId); 1846 // Installer cannot change immutable permissions. 1847 if ((flags & immutableFlags) == 0) { 1848 grantRuntimePermission(pkg.packageName, permission, userId); 1849 } 1850 } 1851 } 1852 } 1853 } 1854 1855 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1856 Bundle extras = null; 1857 switch (res.returnCode) { 1858 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1859 extras = new Bundle(); 1860 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1861 res.origPermission); 1862 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1863 res.origPackage); 1864 break; 1865 } 1866 case PackageManager.INSTALL_SUCCEEDED: { 1867 extras = new Bundle(); 1868 extras.putBoolean(Intent.EXTRA_REPLACING, 1869 res.removedInfo != null && res.removedInfo.removedPackage != null); 1870 break; 1871 } 1872 } 1873 return extras; 1874 } 1875 1876 void scheduleWriteSettingsLocked() { 1877 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1878 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1879 } 1880 } 1881 1882 void scheduleWritePackageRestrictionsLocked(int userId) { 1883 if (!sUserManager.exists(userId)) return; 1884 mDirtyUsers.add(userId); 1885 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1886 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1887 } 1888 } 1889 1890 public static PackageManagerService main(Context context, Installer installer, 1891 boolean factoryTest, boolean onlyCore) { 1892 PackageManagerService m = new PackageManagerService(context, installer, 1893 factoryTest, onlyCore); 1894 m.enableSystemUserPackages(); 1895 ServiceManager.addService("package", m); 1896 return m; 1897 } 1898 1899 private void enableSystemUserPackages() { 1900 if (!UserManager.isSplitSystemUser()) { 1901 return; 1902 } 1903 // For system user, enable apps based on the following conditions: 1904 // - app is whitelisted or belong to one of these groups: 1905 // -- system app which has no launcher icons 1906 // -- system app which has INTERACT_ACROSS_USERS permission 1907 // -- system IME app 1908 // - app is not in the blacklist 1909 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1910 Set<String> enableApps = new ArraySet<>(); 1911 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1912 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1913 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1914 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1915 enableApps.addAll(wlApps); 1916 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1917 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1918 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1919 enableApps.removeAll(blApps); 1920 Log.i(TAG, "Applications installed for system user: " + enableApps); 1921 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1922 UserHandle.SYSTEM); 1923 final int allAppsSize = allAps.size(); 1924 synchronized (mPackages) { 1925 for (int i = 0; i < allAppsSize; i++) { 1926 String pName = allAps.get(i); 1927 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1928 // Should not happen, but we shouldn't be failing if it does 1929 if (pkgSetting == null) { 1930 continue; 1931 } 1932 boolean install = enableApps.contains(pName); 1933 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1934 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1935 + " for system user"); 1936 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1937 } 1938 } 1939 } 1940 } 1941 1942 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1943 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1944 Context.DISPLAY_SERVICE); 1945 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1946 } 1947 1948 public PackageManagerService(Context context, Installer installer, 1949 boolean factoryTest, boolean onlyCore) { 1950 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1951 SystemClock.uptimeMillis()); 1952 1953 if (mSdkVersion <= 0) { 1954 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1955 } 1956 1957 mContext = context; 1958 mFactoryTest = factoryTest; 1959 mOnlyCore = onlyCore; 1960 mMetrics = new DisplayMetrics(); 1961 mSettings = new Settings(mPackages); 1962 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1963 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1964 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1965 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1966 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1967 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1968 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1969 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1970 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1971 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1972 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1973 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1974 1975 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1976 if (separateProcesses != null && separateProcesses.length() > 0) { 1977 if ("*".equals(separateProcesses)) { 1978 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1979 mSeparateProcesses = null; 1980 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1981 } else { 1982 mDefParseFlags = 0; 1983 mSeparateProcesses = separateProcesses.split(","); 1984 Slog.w(TAG, "Running with debug.separate_processes: " 1985 + separateProcesses); 1986 } 1987 } else { 1988 mDefParseFlags = 0; 1989 mSeparateProcesses = null; 1990 } 1991 1992 mInstaller = installer; 1993 mPackageDexOptimizer = new PackageDexOptimizer(this); 1994 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1995 1996 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1997 FgThread.get().getLooper()); 1998 1999 getDefaultDisplayMetrics(context, mMetrics); 2000 2001 SystemConfig systemConfig = SystemConfig.getInstance(); 2002 mGlobalGids = systemConfig.getGlobalGids(); 2003 mSystemPermissions = systemConfig.getSystemPermissions(); 2004 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2005 2006 synchronized (mInstallLock) { 2007 // writer 2008 synchronized (mPackages) { 2009 mHandlerThread = new ServiceThread(TAG, 2010 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2011 mHandlerThread.start(); 2012 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2013 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2014 2015 File dataDir = Environment.getDataDirectory(); 2016 mAppInstallDir = new File(dataDir, "app"); 2017 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2018 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2019 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2020 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2021 2022 sUserManager = new UserManagerService(context, this, mPackages); 2023 2024 // Propagate permission configuration in to package manager. 2025 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2026 = systemConfig.getPermissions(); 2027 for (int i=0; i<permConfig.size(); i++) { 2028 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2029 BasePermission bp = mSettings.mPermissions.get(perm.name); 2030 if (bp == null) { 2031 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2032 mSettings.mPermissions.put(perm.name, bp); 2033 } 2034 if (perm.gids != null) { 2035 bp.setGids(perm.gids, perm.perUser); 2036 } 2037 } 2038 2039 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2040 for (int i=0; i<libConfig.size(); i++) { 2041 mSharedLibraries.put(libConfig.keyAt(i), 2042 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2043 } 2044 2045 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2046 2047 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2048 2049 String customResolverActivity = Resources.getSystem().getString( 2050 R.string.config_customResolverActivity); 2051 if (TextUtils.isEmpty(customResolverActivity)) { 2052 customResolverActivity = null; 2053 } else { 2054 mCustomResolverComponentName = ComponentName.unflattenFromString( 2055 customResolverActivity); 2056 } 2057 2058 long startTime = SystemClock.uptimeMillis(); 2059 2060 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2061 startTime); 2062 2063 // Set flag to monitor and not change apk file paths when 2064 // scanning install directories. 2065 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2066 2067 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2068 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2069 2070 if (bootClassPath == null) { 2071 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2072 } 2073 2074 if (systemServerClassPath == null) { 2075 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2076 } 2077 2078 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2079 final String[] dexCodeInstructionSets = 2080 getDexCodeInstructionSets( 2081 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2082 2083 /** 2084 * Ensure all external libraries have had dexopt run on them. 2085 */ 2086 if (mSharedLibraries.size() > 0) { 2087 // NOTE: For now, we're compiling these system "shared libraries" 2088 // (and framework jars) into all available architectures. It's possible 2089 // to compile them only when we come across an app that uses them (there's 2090 // already logic for that in scanPackageLI) but that adds some complexity. 2091 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2092 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2093 final String lib = libEntry.path; 2094 if (lib == null) { 2095 continue; 2096 } 2097 2098 try { 2099 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2100 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2101 // Shared libraries do not have profiles so we perform a full 2102 // AOT compilation. 2103 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2104 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2105 StorageManager.UUID_PRIVATE_INTERNAL, 2106 false /*useProfiles*/); 2107 } 2108 } catch (FileNotFoundException e) { 2109 Slog.w(TAG, "Library not found: " + lib); 2110 } catch (IOException | InstallerException e) { 2111 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2112 + e.getMessage()); 2113 } 2114 } 2115 } 2116 } 2117 2118 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2119 2120 final VersionInfo ver = mSettings.getInternalVersion(); 2121 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2122 // when upgrading from pre-M, promote system app permissions from install to runtime 2123 mPromoteSystemApps = 2124 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2125 2126 // save off the names of pre-existing system packages prior to scanning; we don't 2127 // want to automatically grant runtime permissions for new system apps 2128 if (mPromoteSystemApps) { 2129 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2130 while (pkgSettingIter.hasNext()) { 2131 PackageSetting ps = pkgSettingIter.next(); 2132 if (isSystemApp(ps)) { 2133 mExistingSystemPackages.add(ps.name); 2134 } 2135 } 2136 } 2137 2138 // Collect vendor overlay packages. 2139 // (Do this before scanning any apps.) 2140 // For security and version matching reason, only consider 2141 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2142 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2143 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2144 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2145 2146 // Find base frameworks (resource packages without code). 2147 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2148 | PackageParser.PARSE_IS_SYSTEM_DIR 2149 | PackageParser.PARSE_IS_PRIVILEGED, 2150 scanFlags | SCAN_NO_DEX, 0); 2151 2152 // Collected privileged system packages. 2153 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2154 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2155 | PackageParser.PARSE_IS_SYSTEM_DIR 2156 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2157 2158 // Collect ordinary system packages. 2159 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2160 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2161 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2162 2163 // Collect all vendor packages. 2164 File vendorAppDir = new File("/vendor/app"); 2165 try { 2166 vendorAppDir = vendorAppDir.getCanonicalFile(); 2167 } catch (IOException e) { 2168 // failed to look up canonical path, continue with original one 2169 } 2170 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2171 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2172 2173 // Collect all OEM packages. 2174 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2175 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2177 2178 // Prune any system packages that no longer exist. 2179 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2180 if (!mOnlyCore) { 2181 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2182 while (psit.hasNext()) { 2183 PackageSetting ps = psit.next(); 2184 2185 /* 2186 * If this is not a system app, it can't be a 2187 * disable system app. 2188 */ 2189 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2190 continue; 2191 } 2192 2193 /* 2194 * If the package is scanned, it's not erased. 2195 */ 2196 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2197 if (scannedPkg != null) { 2198 /* 2199 * If the system app is both scanned and in the 2200 * disabled packages list, then it must have been 2201 * added via OTA. Remove it from the currently 2202 * scanned package so the previously user-installed 2203 * application can be scanned. 2204 */ 2205 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2206 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2207 + ps.name + "; removing system app. Last known codePath=" 2208 + ps.codePathString + ", installStatus=" + ps.installStatus 2209 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2210 + scannedPkg.mVersionCode); 2211 removePackageLI(ps, true); 2212 mExpectingBetter.put(ps.name, ps.codePath); 2213 } 2214 2215 continue; 2216 } 2217 2218 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2219 psit.remove(); 2220 logCriticalInfo(Log.WARN, "System package " + ps.name 2221 + " no longer exists; wiping its data"); 2222 removeDataDirsLI(null, ps.name); 2223 } else { 2224 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2225 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2226 possiblyDeletedUpdatedSystemApps.add(ps.name); 2227 } 2228 } 2229 } 2230 } 2231 2232 //look for any incomplete package installations 2233 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2234 //clean up list 2235 for(int i = 0; i < deletePkgsList.size(); i++) { 2236 //clean up here 2237 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2238 } 2239 //delete tmp files 2240 deleteTempPackageFiles(); 2241 2242 // Remove any shared userIDs that have no associated packages 2243 mSettings.pruneSharedUsersLPw(); 2244 2245 if (!mOnlyCore) { 2246 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2247 SystemClock.uptimeMillis()); 2248 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2249 2250 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2251 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2252 2253 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2254 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2255 2256 /** 2257 * Remove disable package settings for any updated system 2258 * apps that were removed via an OTA. If they're not a 2259 * previously-updated app, remove them completely. 2260 * Otherwise, just revoke their system-level permissions. 2261 */ 2262 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2263 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2264 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2265 2266 String msg; 2267 if (deletedPkg == null) { 2268 msg = "Updated system package " + deletedAppName 2269 + " no longer exists; wiping its data"; 2270 removeDataDirsLI(null, deletedAppName); 2271 } else { 2272 msg = "Updated system app + " + deletedAppName 2273 + " no longer present; removing system privileges for " 2274 + deletedAppName; 2275 2276 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2277 2278 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2279 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2280 } 2281 logCriticalInfo(Log.WARN, msg); 2282 } 2283 2284 /** 2285 * Make sure all system apps that we expected to appear on 2286 * the userdata partition actually showed up. If they never 2287 * appeared, crawl back and revive the system version. 2288 */ 2289 for (int i = 0; i < mExpectingBetter.size(); i++) { 2290 final String packageName = mExpectingBetter.keyAt(i); 2291 if (!mPackages.containsKey(packageName)) { 2292 final File scanFile = mExpectingBetter.valueAt(i); 2293 2294 logCriticalInfo(Log.WARN, "Expected better " + packageName 2295 + " but never showed up; reverting to system"); 2296 2297 final int reparseFlags; 2298 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2299 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2300 | PackageParser.PARSE_IS_SYSTEM_DIR 2301 | PackageParser.PARSE_IS_PRIVILEGED; 2302 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2303 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2304 | PackageParser.PARSE_IS_SYSTEM_DIR; 2305 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2306 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2307 | PackageParser.PARSE_IS_SYSTEM_DIR; 2308 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2309 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2310 | PackageParser.PARSE_IS_SYSTEM_DIR; 2311 } else { 2312 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2313 continue; 2314 } 2315 2316 mSettings.enableSystemPackageLPw(packageName); 2317 2318 try { 2319 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2320 } catch (PackageManagerException e) { 2321 Slog.e(TAG, "Failed to parse original system package: " 2322 + e.getMessage()); 2323 } 2324 } 2325 } 2326 } 2327 mExpectingBetter.clear(); 2328 2329 // Now that we know all of the shared libraries, update all clients to have 2330 // the correct library paths. 2331 updateAllSharedLibrariesLPw(); 2332 2333 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2334 // NOTE: We ignore potential failures here during a system scan (like 2335 // the rest of the commands above) because there's precious little we 2336 // can do about it. A settings error is reported, though. 2337 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2338 false /* boot complete */); 2339 } 2340 2341 // Now that we know all the packages we are keeping, 2342 // read and update their last usage times. 2343 mPackageUsage.readLP(); 2344 2345 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2346 SystemClock.uptimeMillis()); 2347 Slog.i(TAG, "Time to scan packages: " 2348 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2349 + " seconds"); 2350 2351 // If the platform SDK has changed since the last time we booted, 2352 // we need to re-grant app permission to catch any new ones that 2353 // appear. This is really a hack, and means that apps can in some 2354 // cases get permissions that the user didn't initially explicitly 2355 // allow... it would be nice to have some better way to handle 2356 // this situation. 2357 int updateFlags = UPDATE_PERMISSIONS_ALL; 2358 if (ver.sdkVersion != mSdkVersion) { 2359 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2360 + mSdkVersion + "; regranting permissions for internal storage"); 2361 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2362 } 2363 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2364 ver.sdkVersion = mSdkVersion; 2365 2366 // If this is the first boot or an update from pre-M, and it is a normal 2367 // boot, then we need to initialize the default preferred apps across 2368 // all defined users. 2369 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2370 for (UserInfo user : sUserManager.getUsers(true)) { 2371 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2372 applyFactoryDefaultBrowserLPw(user.id); 2373 primeDomainVerificationsLPw(user.id); 2374 } 2375 } 2376 2377 // Prepare storage for system user really early during boot, 2378 // since core system apps like SettingsProvider and SystemUI 2379 // can't wait for user to start 2380 final int flags; 2381 if (StorageManager.isFileBasedEncryptionEnabled()) { 2382 flags = Installer.FLAG_DE_STORAGE; 2383 } else { 2384 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 2385 } 2386 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags); 2387 2388 // If this is first boot after an OTA, and a normal boot, then 2389 // we need to clear code cache directories. 2390 if (mIsUpgrade && !onlyCore) { 2391 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2392 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2393 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2394 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2395 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2396 } 2397 } 2398 ver.fingerprint = Build.FINGERPRINT; 2399 } 2400 2401 checkDefaultBrowser(); 2402 2403 // clear only after permissions and other defaults have been updated 2404 mExistingSystemPackages.clear(); 2405 mPromoteSystemApps = false; 2406 2407 // All the changes are done during package scanning. 2408 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2409 2410 // can downgrade to reader 2411 mSettings.writeLPr(); 2412 2413 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2414 SystemClock.uptimeMillis()); 2415 2416 if (!mOnlyCore) { 2417 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2418 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2419 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2420 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2421 mIntentFilterVerifierComponent); 2422 } else { 2423 mRequiredVerifierPackage = null; 2424 mRequiredInstallerPackage = null; 2425 mIntentFilterVerifierComponent = null; 2426 mIntentFilterVerifier = null; 2427 } 2428 2429 mInstallerService = new PackageInstallerService(context, this); 2430 2431 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2432 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2433 // both the installer and resolver must be present to enable ephemeral 2434 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2435 if (DEBUG_EPHEMERAL) { 2436 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2437 + " installer:" + ephemeralInstallerComponent); 2438 } 2439 mEphemeralResolverComponent = ephemeralResolverComponent; 2440 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2441 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2442 mEphemeralResolverConnection = 2443 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2444 } else { 2445 if (DEBUG_EPHEMERAL) { 2446 final String missingComponent = 2447 (ephemeralResolverComponent == null) 2448 ? (ephemeralInstallerComponent == null) 2449 ? "resolver and installer" 2450 : "resolver" 2451 : "installer"; 2452 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2453 } 2454 mEphemeralResolverComponent = null; 2455 mEphemeralInstallerComponent = null; 2456 mEphemeralResolverConnection = null; 2457 } 2458 2459 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2460 } // synchronized (mPackages) 2461 } // synchronized (mInstallLock) 2462 2463 // Now after opening every single application zip, make sure they 2464 // are all flushed. Not really needed, but keeps things nice and 2465 // tidy. 2466 Runtime.getRuntime().gc(); 2467 2468 // The initial scanning above does many calls into installd while 2469 // holding the mPackages lock, but we're mostly interested in yelling 2470 // once we have a booted system. 2471 mInstaller.setWarnIfHeld(mPackages); 2472 2473 // Expose private service for system components to use. 2474 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2475 } 2476 2477 @Override 2478 public boolean isFirstBoot() { 2479 return !mRestoredSettings; 2480 } 2481 2482 @Override 2483 public boolean isOnlyCoreApps() { 2484 return mOnlyCore; 2485 } 2486 2487 @Override 2488 public boolean isUpgrade() { 2489 return mIsUpgrade; 2490 } 2491 2492 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2493 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2494 2495 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2496 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2497 if (matches.size() == 1) { 2498 return matches.get(0).getComponentInfo().packageName; 2499 } else { 2500 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2501 return null; 2502 } 2503 } 2504 2505 private @NonNull String getRequiredInstallerLPr() { 2506 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2507 intent.addCategory(Intent.CATEGORY_DEFAULT); 2508 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2509 2510 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2511 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2512 if (matches.size() == 1) { 2513 return matches.get(0).getComponentInfo().packageName; 2514 } else { 2515 throw new RuntimeException("There must be exactly one installer; found " + matches); 2516 } 2517 } 2518 2519 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2520 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2521 2522 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2523 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2524 ResolveInfo best = null; 2525 final int N = matches.size(); 2526 for (int i = 0; i < N; i++) { 2527 final ResolveInfo cur = matches.get(i); 2528 final String packageName = cur.getComponentInfo().packageName; 2529 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2530 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2531 continue; 2532 } 2533 2534 if (best == null || cur.priority > best.priority) { 2535 best = cur; 2536 } 2537 } 2538 2539 if (best != null) { 2540 return best.getComponentInfo().getComponentName(); 2541 } else { 2542 throw new RuntimeException("There must be at least one intent filter verifier"); 2543 } 2544 } 2545 2546 private @Nullable ComponentName getEphemeralResolverLPr() { 2547 final String[] packageArray = 2548 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2549 if (packageArray.length == 0) { 2550 if (DEBUG_EPHEMERAL) { 2551 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2552 } 2553 return null; 2554 } 2555 2556 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2557 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2558 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2559 2560 final int N = resolvers.size(); 2561 if (N == 0) { 2562 if (DEBUG_EPHEMERAL) { 2563 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2564 } 2565 return null; 2566 } 2567 2568 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2569 for (int i = 0; i < N; i++) { 2570 final ResolveInfo info = resolvers.get(i); 2571 2572 if (info.serviceInfo == null) { 2573 continue; 2574 } 2575 2576 final String packageName = info.serviceInfo.packageName; 2577 if (!possiblePackages.contains(packageName)) { 2578 if (DEBUG_EPHEMERAL) { 2579 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2580 + " pkg: " + packageName + ", info:" + info); 2581 } 2582 continue; 2583 } 2584 2585 if (DEBUG_EPHEMERAL) { 2586 Slog.v(TAG, "Ephemeral resolver found;" 2587 + " pkg: " + packageName + ", info:" + info); 2588 } 2589 return new ComponentName(packageName, info.serviceInfo.name); 2590 } 2591 if (DEBUG_EPHEMERAL) { 2592 Slog.v(TAG, "Ephemeral resolver NOT found"); 2593 } 2594 return null; 2595 } 2596 2597 private @Nullable ComponentName getEphemeralInstallerLPr() { 2598 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2599 intent.addCategory(Intent.CATEGORY_DEFAULT); 2600 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2601 2602 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2603 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2604 if (matches.size() == 0) { 2605 return null; 2606 } else if (matches.size() == 1) { 2607 return matches.get(0).getComponentInfo().getComponentName(); 2608 } else { 2609 throw new RuntimeException( 2610 "There must be at most one ephemeral installer; found " + matches); 2611 } 2612 } 2613 2614 private void primeDomainVerificationsLPw(int userId) { 2615 if (DEBUG_DOMAIN_VERIFICATION) { 2616 Slog.d(TAG, "Priming domain verifications in user " + userId); 2617 } 2618 2619 SystemConfig systemConfig = SystemConfig.getInstance(); 2620 ArraySet<String> packages = systemConfig.getLinkedApps(); 2621 ArraySet<String> domains = new ArraySet<String>(); 2622 2623 for (String packageName : packages) { 2624 PackageParser.Package pkg = mPackages.get(packageName); 2625 if (pkg != null) { 2626 if (!pkg.isSystemApp()) { 2627 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2628 continue; 2629 } 2630 2631 domains.clear(); 2632 for (PackageParser.Activity a : pkg.activities) { 2633 for (ActivityIntentInfo filter : a.intents) { 2634 if (hasValidDomains(filter)) { 2635 domains.addAll(filter.getHostsList()); 2636 } 2637 } 2638 } 2639 2640 if (domains.size() > 0) { 2641 if (DEBUG_DOMAIN_VERIFICATION) { 2642 Slog.v(TAG, " + " + packageName); 2643 } 2644 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2645 // state w.r.t. the formal app-linkage "no verification attempted" state; 2646 // and then 'always' in the per-user state actually used for intent resolution. 2647 final IntentFilterVerificationInfo ivi; 2648 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2649 new ArrayList<String>(domains)); 2650 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2651 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2652 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2653 } else { 2654 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2655 + "' does not handle web links"); 2656 } 2657 } else { 2658 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2659 } 2660 } 2661 2662 scheduleWritePackageRestrictionsLocked(userId); 2663 scheduleWriteSettingsLocked(); 2664 } 2665 2666 private void applyFactoryDefaultBrowserLPw(int userId) { 2667 // The default browser app's package name is stored in a string resource, 2668 // with a product-specific overlay used for vendor customization. 2669 String browserPkg = mContext.getResources().getString( 2670 com.android.internal.R.string.default_browser); 2671 if (!TextUtils.isEmpty(browserPkg)) { 2672 // non-empty string => required to be a known package 2673 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2674 if (ps == null) { 2675 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2676 browserPkg = null; 2677 } else { 2678 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2679 } 2680 } 2681 2682 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2683 // default. If there's more than one, just leave everything alone. 2684 if (browserPkg == null) { 2685 calculateDefaultBrowserLPw(userId); 2686 } 2687 } 2688 2689 private void calculateDefaultBrowserLPw(int userId) { 2690 List<String> allBrowsers = resolveAllBrowserApps(userId); 2691 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2692 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2693 } 2694 2695 private List<String> resolveAllBrowserApps(int userId) { 2696 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2697 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2698 PackageManager.MATCH_ALL, userId); 2699 2700 final int count = list.size(); 2701 List<String> result = new ArrayList<String>(count); 2702 for (int i=0; i<count; i++) { 2703 ResolveInfo info = list.get(i); 2704 if (info.activityInfo == null 2705 || !info.handleAllWebDataURI 2706 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2707 || result.contains(info.activityInfo.packageName)) { 2708 continue; 2709 } 2710 result.add(info.activityInfo.packageName); 2711 } 2712 2713 return result; 2714 } 2715 2716 private boolean packageIsBrowser(String packageName, int userId) { 2717 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2718 PackageManager.MATCH_ALL, userId); 2719 final int N = list.size(); 2720 for (int i = 0; i < N; i++) { 2721 ResolveInfo info = list.get(i); 2722 if (packageName.equals(info.activityInfo.packageName)) { 2723 return true; 2724 } 2725 } 2726 return false; 2727 } 2728 2729 private void checkDefaultBrowser() { 2730 final int myUserId = UserHandle.myUserId(); 2731 final String packageName = getDefaultBrowserPackageName(myUserId); 2732 if (packageName != null) { 2733 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2734 if (info == null) { 2735 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2736 synchronized (mPackages) { 2737 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2738 } 2739 } 2740 } 2741 } 2742 2743 @Override 2744 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2745 throws RemoteException { 2746 try { 2747 return super.onTransact(code, data, reply, flags); 2748 } catch (RuntimeException e) { 2749 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2750 Slog.wtf(TAG, "Package Manager Crash", e); 2751 } 2752 throw e; 2753 } 2754 } 2755 2756 void cleanupInstallFailedPackage(PackageSetting ps) { 2757 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2758 2759 removeDataDirsLI(ps.volumeUuid, ps.name); 2760 if (ps.codePath != null) { 2761 removeCodePathLI(ps.codePath); 2762 } 2763 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2764 if (ps.resourcePath.isDirectory()) { 2765 FileUtils.deleteContents(ps.resourcePath); 2766 } 2767 ps.resourcePath.delete(); 2768 } 2769 mSettings.removePackageLPw(ps.name); 2770 } 2771 2772 static int[] appendInts(int[] cur, int[] add) { 2773 if (add == null) return cur; 2774 if (cur == null) return add; 2775 final int N = add.length; 2776 for (int i=0; i<N; i++) { 2777 cur = appendInt(cur, add[i]); 2778 } 2779 return cur; 2780 } 2781 2782 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2783 if (!sUserManager.exists(userId)) return null; 2784 final PackageSetting ps = (PackageSetting) p.mExtras; 2785 if (ps == null) { 2786 return null; 2787 } 2788 2789 final PermissionsState permissionsState = ps.getPermissionsState(); 2790 2791 final int[] gids = permissionsState.computeGids(userId); 2792 final Set<String> permissions = permissionsState.getPermissions(userId); 2793 final PackageUserState state = ps.readUserState(userId); 2794 2795 return PackageParser.generatePackageInfo(p, gids, flags, 2796 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2797 } 2798 2799 @Override 2800 public void checkPackageStartable(String packageName, int userId) { 2801 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2802 2803 synchronized (mPackages) { 2804 final PackageSetting ps = mSettings.mPackages.get(packageName); 2805 if (ps == null) { 2806 throw new SecurityException("Package " + packageName + " was not found!"); 2807 } 2808 2809 if (ps.frozen) { 2810 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2811 } 2812 2813 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2814 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2815 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2816 } 2817 } 2818 } 2819 2820 @Override 2821 public boolean isPackageAvailable(String packageName, int userId) { 2822 if (!sUserManager.exists(userId)) return false; 2823 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2824 synchronized (mPackages) { 2825 PackageParser.Package p = mPackages.get(packageName); 2826 if (p != null) { 2827 final PackageSetting ps = (PackageSetting) p.mExtras; 2828 if (ps != null) { 2829 final PackageUserState state = ps.readUserState(userId); 2830 if (state != null) { 2831 return PackageParser.isAvailable(state); 2832 } 2833 } 2834 } 2835 } 2836 return false; 2837 } 2838 2839 @Override 2840 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2841 if (!sUserManager.exists(userId)) return null; 2842 flags = updateFlagsForPackage(flags, userId, packageName); 2843 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2844 // reader 2845 synchronized (mPackages) { 2846 PackageParser.Package p = mPackages.get(packageName); 2847 if (DEBUG_PACKAGE_INFO) 2848 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2849 if (p != null) { 2850 return generatePackageInfo(p, flags, userId); 2851 } 2852 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2853 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public String[] currentToCanonicalPackageNames(String[] names) { 2861 String[] out = new String[names.length]; 2862 // reader 2863 synchronized (mPackages) { 2864 for (int i=names.length-1; i>=0; i--) { 2865 PackageSetting ps = mSettings.mPackages.get(names[i]); 2866 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2867 } 2868 } 2869 return out; 2870 } 2871 2872 @Override 2873 public String[] canonicalToCurrentPackageNames(String[] names) { 2874 String[] out = new String[names.length]; 2875 // reader 2876 synchronized (mPackages) { 2877 for (int i=names.length-1; i>=0; i--) { 2878 String cur = mSettings.mRenamedPackages.get(names[i]); 2879 out[i] = cur != null ? cur : names[i]; 2880 } 2881 } 2882 return out; 2883 } 2884 2885 @Override 2886 public int getPackageUid(String packageName, int flags, int userId) { 2887 if (!sUserManager.exists(userId)) return -1; 2888 flags = updateFlagsForPackage(flags, userId, packageName); 2889 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2890 2891 // reader 2892 synchronized (mPackages) { 2893 final PackageParser.Package p = mPackages.get(packageName); 2894 if (p != null && p.isMatch(flags)) { 2895 return UserHandle.getUid(userId, p.applicationInfo.uid); 2896 } 2897 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2898 final PackageSetting ps = mSettings.mPackages.get(packageName); 2899 if (ps != null && ps.isMatch(flags)) { 2900 return UserHandle.getUid(userId, ps.appId); 2901 } 2902 } 2903 } 2904 2905 return -1; 2906 } 2907 2908 @Override 2909 public int[] getPackageGids(String packageName, int flags, int userId) { 2910 if (!sUserManager.exists(userId)) return null; 2911 flags = updateFlagsForPackage(flags, userId, packageName); 2912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2913 "getPackageGids"); 2914 2915 // reader 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(packageName); 2918 if (p != null && p.isMatch(flags)) { 2919 PackageSetting ps = (PackageSetting) p.mExtras; 2920 return ps.getPermissionsState().computeGids(userId); 2921 } 2922 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2923 final PackageSetting ps = mSettings.mPackages.get(packageName); 2924 if (ps != null && ps.isMatch(flags)) { 2925 return ps.getPermissionsState().computeGids(userId); 2926 } 2927 } 2928 } 2929 2930 return null; 2931 } 2932 2933 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2934 if (bp.perm != null) { 2935 return PackageParser.generatePermissionInfo(bp.perm, flags); 2936 } 2937 PermissionInfo pi = new PermissionInfo(); 2938 pi.name = bp.name; 2939 pi.packageName = bp.sourcePackage; 2940 pi.nonLocalizedLabel = bp.name; 2941 pi.protectionLevel = bp.protectionLevel; 2942 return pi; 2943 } 2944 2945 @Override 2946 public PermissionInfo getPermissionInfo(String name, int flags) { 2947 // reader 2948 synchronized (mPackages) { 2949 final BasePermission p = mSettings.mPermissions.get(name); 2950 if (p != null) { 2951 return generatePermissionInfo(p, flags); 2952 } 2953 return null; 2954 } 2955 } 2956 2957 @Override 2958 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2959 // reader 2960 synchronized (mPackages) { 2961 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2962 for (BasePermission p : mSettings.mPermissions.values()) { 2963 if (group == null) { 2964 if (p.perm == null || p.perm.info.group == null) { 2965 out.add(generatePermissionInfo(p, flags)); 2966 } 2967 } else { 2968 if (p.perm != null && group.equals(p.perm.info.group)) { 2969 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2970 } 2971 } 2972 } 2973 2974 if (out.size() > 0) { 2975 return out; 2976 } 2977 return mPermissionGroups.containsKey(group) ? out : null; 2978 } 2979 } 2980 2981 @Override 2982 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2983 // reader 2984 synchronized (mPackages) { 2985 return PackageParser.generatePermissionGroupInfo( 2986 mPermissionGroups.get(name), flags); 2987 } 2988 } 2989 2990 @Override 2991 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2992 // reader 2993 synchronized (mPackages) { 2994 final int N = mPermissionGroups.size(); 2995 ArrayList<PermissionGroupInfo> out 2996 = new ArrayList<PermissionGroupInfo>(N); 2997 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2998 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2999 } 3000 return out; 3001 } 3002 } 3003 3004 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3005 int userId) { 3006 if (!sUserManager.exists(userId)) return null; 3007 PackageSetting ps = mSettings.mPackages.get(packageName); 3008 if (ps != null) { 3009 if (ps.pkg == null) { 3010 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3011 flags, userId); 3012 if (pInfo != null) { 3013 return pInfo.applicationInfo; 3014 } 3015 return null; 3016 } 3017 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3018 ps.readUserState(userId), userId); 3019 } 3020 return null; 3021 } 3022 3023 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3024 int userId) { 3025 if (!sUserManager.exists(userId)) return null; 3026 PackageSetting ps = mSettings.mPackages.get(packageName); 3027 if (ps != null) { 3028 PackageParser.Package pkg = ps.pkg; 3029 if (pkg == null) { 3030 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3031 return null; 3032 } 3033 // Only data remains, so we aren't worried about code paths 3034 pkg = new PackageParser.Package(packageName); 3035 pkg.applicationInfo.packageName = packageName; 3036 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3037 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3038 pkg.applicationInfo.uid = ps.appId; 3039 pkg.applicationInfo.initForUser(userId); 3040 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3041 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3042 } 3043 return generatePackageInfo(pkg, flags, userId); 3044 } 3045 return null; 3046 } 3047 3048 @Override 3049 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3050 if (!sUserManager.exists(userId)) return null; 3051 flags = updateFlagsForApplication(flags, userId, packageName); 3052 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3053 // writer 3054 synchronized (mPackages) { 3055 PackageParser.Package p = mPackages.get(packageName); 3056 if (DEBUG_PACKAGE_INFO) Log.v( 3057 TAG, "getApplicationInfo " + packageName 3058 + ": " + p); 3059 if (p != null) { 3060 PackageSetting ps = mSettings.mPackages.get(packageName); 3061 if (ps == null) return null; 3062 // Note: isEnabledLP() does not apply here - always return info 3063 return PackageParser.generateApplicationInfo( 3064 p, flags, ps.readUserState(userId), userId); 3065 } 3066 if ("android".equals(packageName)||"system".equals(packageName)) { 3067 return mAndroidApplication; 3068 } 3069 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3070 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3071 } 3072 } 3073 return null; 3074 } 3075 3076 @Override 3077 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3078 final IPackageDataObserver observer) { 3079 mContext.enforceCallingOrSelfPermission( 3080 android.Manifest.permission.CLEAR_APP_CACHE, null); 3081 // Queue up an async operation since clearing cache may take a little while. 3082 mHandler.post(new Runnable() { 3083 public void run() { 3084 mHandler.removeCallbacks(this); 3085 boolean success = true; 3086 synchronized (mInstallLock) { 3087 try { 3088 mInstaller.freeCache(volumeUuid, freeStorageSize); 3089 } catch (InstallerException e) { 3090 Slog.w(TAG, "Couldn't clear application caches: " + e); 3091 success = false; 3092 } 3093 } 3094 if (observer != null) { 3095 try { 3096 observer.onRemoveCompleted(null, success); 3097 } catch (RemoteException e) { 3098 Slog.w(TAG, "RemoveException when invoking call back"); 3099 } 3100 } 3101 } 3102 }); 3103 } 3104 3105 @Override 3106 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3107 final IntentSender pi) { 3108 mContext.enforceCallingOrSelfPermission( 3109 android.Manifest.permission.CLEAR_APP_CACHE, null); 3110 // Queue up an async operation since clearing cache may take a little while. 3111 mHandler.post(new Runnable() { 3112 public void run() { 3113 mHandler.removeCallbacks(this); 3114 boolean success = true; 3115 synchronized (mInstallLock) { 3116 try { 3117 mInstaller.freeCache(volumeUuid, freeStorageSize); 3118 } catch (InstallerException e) { 3119 Slog.w(TAG, "Couldn't clear application caches: " + e); 3120 success = false; 3121 } 3122 } 3123 if(pi != null) { 3124 try { 3125 // Callback via pending intent 3126 int code = success ? 1 : 0; 3127 pi.sendIntent(null, code, null, 3128 null, null); 3129 } catch (SendIntentException e1) { 3130 Slog.i(TAG, "Failed to send pending intent"); 3131 } 3132 } 3133 } 3134 }); 3135 } 3136 3137 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3138 synchronized (mInstallLock) { 3139 try { 3140 mInstaller.freeCache(volumeUuid, freeStorageSize); 3141 } catch (InstallerException e) { 3142 throw new IOException("Failed to free enough space", e); 3143 } 3144 } 3145 } 3146 3147 /** 3148 * Return if the user key is currently unlocked. 3149 */ 3150 private boolean isUserKeyUnlocked(int userId) { 3151 if (StorageManager.isFileBasedEncryptionEnabled()) { 3152 final IMountService mount = IMountService.Stub 3153 .asInterface(ServiceManager.getService("mount")); 3154 if (mount == null) { 3155 Slog.w(TAG, "Early during boot, assuming locked"); 3156 return false; 3157 } 3158 final long token = Binder.clearCallingIdentity(); 3159 try { 3160 return mount.isUserKeyUnlocked(userId); 3161 } catch (RemoteException e) { 3162 throw e.rethrowAsRuntimeException(); 3163 } finally { 3164 Binder.restoreCallingIdentity(token); 3165 } 3166 } else { 3167 return true; 3168 } 3169 } 3170 3171 /** 3172 * Update given flags based on encryption status of current user. 3173 */ 3174 private int updateFlags(int flags, int userId) { 3175 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3176 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3177 // Caller expressed an explicit opinion about what encryption 3178 // aware/unaware components they want to see, so fall through and 3179 // give them what they want 3180 } else { 3181 // Caller expressed no opinion, so match based on user state 3182 if (isUserKeyUnlocked(userId)) { 3183 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3184 } else { 3185 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3186 } 3187 } 3188 3189 // Safe mode means we should ignore any third-party apps 3190 if (mSafeMode) { 3191 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3192 } 3193 3194 return flags; 3195 } 3196 3197 /** 3198 * Update given flags when being used to request {@link PackageInfo}. 3199 */ 3200 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3201 boolean triaged = true; 3202 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3203 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3204 // Caller is asking for component details, so they'd better be 3205 // asking for specific encryption matching behavior, or be triaged 3206 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3207 | PackageManager.MATCH_ENCRYPTION_AWARE 3208 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3209 triaged = false; 3210 } 3211 } 3212 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3213 | PackageManager.MATCH_SYSTEM_ONLY 3214 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3215 triaged = false; 3216 } 3217 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3218 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3219 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3220 } 3221 return updateFlags(flags, userId); 3222 } 3223 3224 /** 3225 * Update given flags when being used to request {@link ApplicationInfo}. 3226 */ 3227 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3228 return updateFlagsForPackage(flags, userId, cookie); 3229 } 3230 3231 /** 3232 * Update given flags when being used to request {@link ComponentInfo}. 3233 */ 3234 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3235 if (cookie instanceof Intent) { 3236 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3237 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3238 } 3239 } 3240 3241 boolean triaged = true; 3242 // Caller is asking for component details, so they'd better be 3243 // asking for specific encryption matching behavior, or be triaged 3244 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3245 | PackageManager.MATCH_ENCRYPTION_AWARE 3246 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3247 triaged = false; 3248 } 3249 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3250 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3251 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3252 } 3253 return updateFlags(flags, userId); 3254 } 3255 3256 /** 3257 * Update given flags when being used to request {@link ResolveInfo}. 3258 */ 3259 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3260 return updateFlagsForComponent(flags, userId, cookie); 3261 } 3262 3263 @Override 3264 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3265 if (!sUserManager.exists(userId)) return null; 3266 flags = updateFlagsForComponent(flags, userId, component); 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3268 synchronized (mPackages) { 3269 PackageParser.Activity a = mActivities.mActivities.get(component); 3270 3271 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3272 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3274 if (ps == null) return null; 3275 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3276 userId); 3277 } 3278 if (mResolveComponentName.equals(component)) { 3279 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3280 new PackageUserState(), userId); 3281 } 3282 } 3283 return null; 3284 } 3285 3286 @Override 3287 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3288 String resolvedType) { 3289 synchronized (mPackages) { 3290 if (component.equals(mResolveComponentName)) { 3291 // The resolver supports EVERYTHING! 3292 return true; 3293 } 3294 PackageParser.Activity a = mActivities.mActivities.get(component); 3295 if (a == null) { 3296 return false; 3297 } 3298 for (int i=0; i<a.intents.size(); i++) { 3299 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3300 intent.getData(), intent.getCategories(), TAG) >= 0) { 3301 return true; 3302 } 3303 } 3304 return false; 3305 } 3306 } 3307 3308 @Override 3309 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForComponent(flags, userId, component); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3313 synchronized (mPackages) { 3314 PackageParser.Activity a = mReceivers.mActivities.get(component); 3315 if (DEBUG_PACKAGE_INFO) Log.v( 3316 TAG, "getReceiverInfo " + component + ": " + a); 3317 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3318 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3319 if (ps == null) return null; 3320 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3321 userId); 3322 } 3323 } 3324 return null; 3325 } 3326 3327 @Override 3328 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 flags = updateFlagsForComponent(flags, userId, component); 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3332 synchronized (mPackages) { 3333 PackageParser.Service s = mServices.mServices.get(component); 3334 if (DEBUG_PACKAGE_INFO) Log.v( 3335 TAG, "getServiceInfo " + component + ": " + s); 3336 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3337 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3338 if (ps == null) return null; 3339 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3340 userId); 3341 } 3342 } 3343 return null; 3344 } 3345 3346 @Override 3347 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3348 if (!sUserManager.exists(userId)) return null; 3349 flags = updateFlagsForComponent(flags, userId, component); 3350 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3351 synchronized (mPackages) { 3352 PackageParser.Provider p = mProviders.mProviders.get(component); 3353 if (DEBUG_PACKAGE_INFO) Log.v( 3354 TAG, "getProviderInfo " + component + ": " + p); 3355 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3357 if (ps == null) return null; 3358 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3359 userId); 3360 } 3361 } 3362 return null; 3363 } 3364 3365 @Override 3366 public String[] getSystemSharedLibraryNames() { 3367 Set<String> libSet; 3368 synchronized (mPackages) { 3369 libSet = mSharedLibraries.keySet(); 3370 int size = libSet.size(); 3371 if (size > 0) { 3372 String[] libs = new String[size]; 3373 libSet.toArray(libs); 3374 return libs; 3375 } 3376 } 3377 return null; 3378 } 3379 3380 /** 3381 * @hide 3382 */ 3383 PackageParser.Package findSharedNonSystemLibrary(String libName) { 3384 synchronized (mPackages) { 3385 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 3386 if (lib != null && lib.apk != null) { 3387 return mPackages.get(lib.apk); 3388 } 3389 } 3390 return null; 3391 } 3392 3393 @Override 3394 public FeatureInfo[] getSystemAvailableFeatures() { 3395 Collection<FeatureInfo> featSet; 3396 synchronized (mPackages) { 3397 featSet = mAvailableFeatures.values(); 3398 int size = featSet.size(); 3399 if (size > 0) { 3400 FeatureInfo[] features = new FeatureInfo[size+1]; 3401 featSet.toArray(features); 3402 FeatureInfo fi = new FeatureInfo(); 3403 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3404 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3405 features[size] = fi; 3406 return features; 3407 } 3408 } 3409 return null; 3410 } 3411 3412 @Override 3413 public boolean hasSystemFeature(String name) { 3414 synchronized (mPackages) { 3415 return mAvailableFeatures.containsKey(name); 3416 } 3417 } 3418 3419 @Override 3420 public int checkPermission(String permName, String pkgName, int userId) { 3421 if (!sUserManager.exists(userId)) { 3422 return PackageManager.PERMISSION_DENIED; 3423 } 3424 3425 synchronized (mPackages) { 3426 final PackageParser.Package p = mPackages.get(pkgName); 3427 if (p != null && p.mExtras != null) { 3428 final PackageSetting ps = (PackageSetting) p.mExtras; 3429 final PermissionsState permissionsState = ps.getPermissionsState(); 3430 if (permissionsState.hasPermission(permName, userId)) { 3431 return PackageManager.PERMISSION_GRANTED; 3432 } 3433 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3434 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3435 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3436 return PackageManager.PERMISSION_GRANTED; 3437 } 3438 } 3439 } 3440 3441 return PackageManager.PERMISSION_DENIED; 3442 } 3443 3444 @Override 3445 public int checkUidPermission(String permName, int uid) { 3446 final int userId = UserHandle.getUserId(uid); 3447 3448 if (!sUserManager.exists(userId)) { 3449 return PackageManager.PERMISSION_DENIED; 3450 } 3451 3452 synchronized (mPackages) { 3453 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3454 if (obj != null) { 3455 final SettingBase ps = (SettingBase) obj; 3456 final PermissionsState permissionsState = ps.getPermissionsState(); 3457 if (permissionsState.hasPermission(permName, userId)) { 3458 return PackageManager.PERMISSION_GRANTED; 3459 } 3460 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3461 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3462 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3463 return PackageManager.PERMISSION_GRANTED; 3464 } 3465 } else { 3466 ArraySet<String> perms = mSystemPermissions.get(uid); 3467 if (perms != null) { 3468 if (perms.contains(permName)) { 3469 return PackageManager.PERMISSION_GRANTED; 3470 } 3471 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3472 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3473 return PackageManager.PERMISSION_GRANTED; 3474 } 3475 } 3476 } 3477 } 3478 3479 return PackageManager.PERMISSION_DENIED; 3480 } 3481 3482 @Override 3483 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3484 if (UserHandle.getCallingUserId() != userId) { 3485 mContext.enforceCallingPermission( 3486 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3487 "isPermissionRevokedByPolicy for user " + userId); 3488 } 3489 3490 if (checkPermission(permission, packageName, userId) 3491 == PackageManager.PERMISSION_GRANTED) { 3492 return false; 3493 } 3494 3495 final long identity = Binder.clearCallingIdentity(); 3496 try { 3497 final int flags = getPermissionFlags(permission, packageName, userId); 3498 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3499 } finally { 3500 Binder.restoreCallingIdentity(identity); 3501 } 3502 } 3503 3504 @Override 3505 public String getPermissionControllerPackageName() { 3506 synchronized (mPackages) { 3507 return mRequiredInstallerPackage; 3508 } 3509 } 3510 3511 /** 3512 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3513 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3514 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3515 * @param message the message to log on security exception 3516 */ 3517 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3518 boolean checkShell, String message) { 3519 if (userId < 0) { 3520 throw new IllegalArgumentException("Invalid userId " + userId); 3521 } 3522 if (checkShell) { 3523 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3524 } 3525 if (userId == UserHandle.getUserId(callingUid)) return; 3526 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3527 if (requireFullPermission) { 3528 mContext.enforceCallingOrSelfPermission( 3529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3530 } else { 3531 try { 3532 mContext.enforceCallingOrSelfPermission( 3533 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3534 } catch (SecurityException se) { 3535 mContext.enforceCallingOrSelfPermission( 3536 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3537 } 3538 } 3539 } 3540 } 3541 3542 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3543 if (callingUid == Process.SHELL_UID) { 3544 if (userHandle >= 0 3545 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3546 throw new SecurityException("Shell does not have permission to access user " 3547 + userHandle); 3548 } else if (userHandle < 0) { 3549 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3550 + Debug.getCallers(3)); 3551 } 3552 } 3553 } 3554 3555 private BasePermission findPermissionTreeLP(String permName) { 3556 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3557 if (permName.startsWith(bp.name) && 3558 permName.length() > bp.name.length() && 3559 permName.charAt(bp.name.length()) == '.') { 3560 return bp; 3561 } 3562 } 3563 return null; 3564 } 3565 3566 private BasePermission checkPermissionTreeLP(String permName) { 3567 if (permName != null) { 3568 BasePermission bp = findPermissionTreeLP(permName); 3569 if (bp != null) { 3570 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3571 return bp; 3572 } 3573 throw new SecurityException("Calling uid " 3574 + Binder.getCallingUid() 3575 + " is not allowed to add to permission tree " 3576 + bp.name + " owned by uid " + bp.uid); 3577 } 3578 } 3579 throw new SecurityException("No permission tree found for " + permName); 3580 } 3581 3582 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3583 if (s1 == null) { 3584 return s2 == null; 3585 } 3586 if (s2 == null) { 3587 return false; 3588 } 3589 if (s1.getClass() != s2.getClass()) { 3590 return false; 3591 } 3592 return s1.equals(s2); 3593 } 3594 3595 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3596 if (pi1.icon != pi2.icon) return false; 3597 if (pi1.logo != pi2.logo) return false; 3598 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3599 if (!compareStrings(pi1.name, pi2.name)) return false; 3600 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3601 // We'll take care of setting this one. 3602 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3603 // These are not currently stored in settings. 3604 //if (!compareStrings(pi1.group, pi2.group)) return false; 3605 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3606 //if (pi1.labelRes != pi2.labelRes) return false; 3607 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3608 return true; 3609 } 3610 3611 int permissionInfoFootprint(PermissionInfo info) { 3612 int size = info.name.length(); 3613 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3614 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3615 return size; 3616 } 3617 3618 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3619 int size = 0; 3620 for (BasePermission perm : mSettings.mPermissions.values()) { 3621 if (perm.uid == tree.uid) { 3622 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3623 } 3624 } 3625 return size; 3626 } 3627 3628 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3629 // We calculate the max size of permissions defined by this uid and throw 3630 // if that plus the size of 'info' would exceed our stated maximum. 3631 if (tree.uid != Process.SYSTEM_UID) { 3632 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3633 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3634 throw new SecurityException("Permission tree size cap exceeded"); 3635 } 3636 } 3637 } 3638 3639 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3640 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3641 throw new SecurityException("Label must be specified in permission"); 3642 } 3643 BasePermission tree = checkPermissionTreeLP(info.name); 3644 BasePermission bp = mSettings.mPermissions.get(info.name); 3645 boolean added = bp == null; 3646 boolean changed = true; 3647 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3648 if (added) { 3649 enforcePermissionCapLocked(info, tree); 3650 bp = new BasePermission(info.name, tree.sourcePackage, 3651 BasePermission.TYPE_DYNAMIC); 3652 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3653 throw new SecurityException( 3654 "Not allowed to modify non-dynamic permission " 3655 + info.name); 3656 } else { 3657 if (bp.protectionLevel == fixedLevel 3658 && bp.perm.owner.equals(tree.perm.owner) 3659 && bp.uid == tree.uid 3660 && comparePermissionInfos(bp.perm.info, info)) { 3661 changed = false; 3662 } 3663 } 3664 bp.protectionLevel = fixedLevel; 3665 info = new PermissionInfo(info); 3666 info.protectionLevel = fixedLevel; 3667 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3668 bp.perm.info.packageName = tree.perm.info.packageName; 3669 bp.uid = tree.uid; 3670 if (added) { 3671 mSettings.mPermissions.put(info.name, bp); 3672 } 3673 if (changed) { 3674 if (!async) { 3675 mSettings.writeLPr(); 3676 } else { 3677 scheduleWriteSettingsLocked(); 3678 } 3679 } 3680 return added; 3681 } 3682 3683 @Override 3684 public boolean addPermission(PermissionInfo info) { 3685 synchronized (mPackages) { 3686 return addPermissionLocked(info, false); 3687 } 3688 } 3689 3690 @Override 3691 public boolean addPermissionAsync(PermissionInfo info) { 3692 synchronized (mPackages) { 3693 return addPermissionLocked(info, true); 3694 } 3695 } 3696 3697 @Override 3698 public void removePermission(String name) { 3699 synchronized (mPackages) { 3700 checkPermissionTreeLP(name); 3701 BasePermission bp = mSettings.mPermissions.get(name); 3702 if (bp != null) { 3703 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3704 throw new SecurityException( 3705 "Not allowed to modify non-dynamic permission " 3706 + name); 3707 } 3708 mSettings.mPermissions.remove(name); 3709 mSettings.writeLPr(); 3710 } 3711 } 3712 } 3713 3714 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3715 BasePermission bp) { 3716 int index = pkg.requestedPermissions.indexOf(bp.name); 3717 if (index == -1) { 3718 throw new SecurityException("Package " + pkg.packageName 3719 + " has not requested permission " + bp.name); 3720 } 3721 if (!bp.isRuntime() && !bp.isDevelopment()) { 3722 throw new SecurityException("Permission " + bp.name 3723 + " is not a changeable permission type"); 3724 } 3725 } 3726 3727 @Override 3728 public void grantRuntimePermission(String packageName, String name, final int userId) { 3729 if (!sUserManager.exists(userId)) { 3730 Log.e(TAG, "No such user:" + userId); 3731 return; 3732 } 3733 3734 mContext.enforceCallingOrSelfPermission( 3735 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3736 "grantRuntimePermission"); 3737 3738 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3739 "grantRuntimePermission"); 3740 3741 final int uid; 3742 final SettingBase sb; 3743 3744 synchronized (mPackages) { 3745 final PackageParser.Package pkg = mPackages.get(packageName); 3746 if (pkg == null) { 3747 throw new IllegalArgumentException("Unknown package: " + packageName); 3748 } 3749 3750 final BasePermission bp = mSettings.mPermissions.get(name); 3751 if (bp == null) { 3752 throw new IllegalArgumentException("Unknown permission: " + name); 3753 } 3754 3755 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3756 3757 // If a permission review is required for legacy apps we represent 3758 // their permissions as always granted runtime ones since we need 3759 // to keep the review required permission flag per user while an 3760 // install permission's state is shared across all users. 3761 if (Build.PERMISSIONS_REVIEW_REQUIRED 3762 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3763 && bp.isRuntime()) { 3764 return; 3765 } 3766 3767 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3768 sb = (SettingBase) pkg.mExtras; 3769 if (sb == null) { 3770 throw new IllegalArgumentException("Unknown package: " + packageName); 3771 } 3772 3773 final PermissionsState permissionsState = sb.getPermissionsState(); 3774 3775 final int flags = permissionsState.getPermissionFlags(name, userId); 3776 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3777 throw new SecurityException("Cannot grant system fixed permission " 3778 + name + " for package " + packageName); 3779 } 3780 3781 if (bp.isDevelopment()) { 3782 // Development permissions must be handled specially, since they are not 3783 // normal runtime permissions. For now they apply to all users. 3784 if (permissionsState.grantInstallPermission(bp) != 3785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3786 scheduleWriteSettingsLocked(); 3787 } 3788 return; 3789 } 3790 3791 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3792 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3793 return; 3794 } 3795 3796 final int result = permissionsState.grantRuntimePermission(bp, userId); 3797 switch (result) { 3798 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3799 return; 3800 } 3801 3802 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3803 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3804 mHandler.post(new Runnable() { 3805 @Override 3806 public void run() { 3807 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3808 } 3809 }); 3810 } 3811 break; 3812 } 3813 3814 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3815 3816 // Not critical if that is lost - app has to request again. 3817 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3818 } 3819 3820 // Only need to do this if user is initialized. Otherwise it's a new user 3821 // and there are no processes running as the user yet and there's no need 3822 // to make an expensive call to remount processes for the changed permissions. 3823 if (READ_EXTERNAL_STORAGE.equals(name) 3824 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3825 final long token = Binder.clearCallingIdentity(); 3826 try { 3827 if (sUserManager.isInitialized(userId)) { 3828 MountServiceInternal mountServiceInternal = LocalServices.getService( 3829 MountServiceInternal.class); 3830 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3831 } 3832 } finally { 3833 Binder.restoreCallingIdentity(token); 3834 } 3835 } 3836 } 3837 3838 @Override 3839 public void revokeRuntimePermission(String packageName, String name, int userId) { 3840 if (!sUserManager.exists(userId)) { 3841 Log.e(TAG, "No such user:" + userId); 3842 return; 3843 } 3844 3845 mContext.enforceCallingOrSelfPermission( 3846 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3847 "revokeRuntimePermission"); 3848 3849 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3850 "revokeRuntimePermission"); 3851 3852 final int appId; 3853 3854 synchronized (mPackages) { 3855 final PackageParser.Package pkg = mPackages.get(packageName); 3856 if (pkg == null) { 3857 throw new IllegalArgumentException("Unknown package: " + packageName); 3858 } 3859 3860 final BasePermission bp = mSettings.mPermissions.get(name); 3861 if (bp == null) { 3862 throw new IllegalArgumentException("Unknown permission: " + name); 3863 } 3864 3865 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3866 3867 // If a permission review is required for legacy apps we represent 3868 // their permissions as always granted runtime ones since we need 3869 // to keep the review required permission flag per user while an 3870 // install permission's state is shared across all users. 3871 if (Build.PERMISSIONS_REVIEW_REQUIRED 3872 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3873 && bp.isRuntime()) { 3874 return; 3875 } 3876 3877 SettingBase sb = (SettingBase) pkg.mExtras; 3878 if (sb == null) { 3879 throw new IllegalArgumentException("Unknown package: " + packageName); 3880 } 3881 3882 final PermissionsState permissionsState = sb.getPermissionsState(); 3883 3884 final int flags = permissionsState.getPermissionFlags(name, userId); 3885 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3886 throw new SecurityException("Cannot revoke system fixed permission " 3887 + name + " for package " + packageName); 3888 } 3889 3890 if (bp.isDevelopment()) { 3891 // Development permissions must be handled specially, since they are not 3892 // normal runtime permissions. For now they apply to all users. 3893 if (permissionsState.revokeInstallPermission(bp) != 3894 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3895 scheduleWriteSettingsLocked(); 3896 } 3897 return; 3898 } 3899 3900 if (permissionsState.revokeRuntimePermission(bp, userId) == 3901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3902 return; 3903 } 3904 3905 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3906 3907 // Critical, after this call app should never have the permission. 3908 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3909 3910 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3911 } 3912 3913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3914 } 3915 3916 @Override 3917 public void resetRuntimePermissions() { 3918 mContext.enforceCallingOrSelfPermission( 3919 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3920 "revokeRuntimePermission"); 3921 3922 int callingUid = Binder.getCallingUid(); 3923 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3924 mContext.enforceCallingOrSelfPermission( 3925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3926 "resetRuntimePermissions"); 3927 } 3928 3929 synchronized (mPackages) { 3930 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3931 for (int userId : UserManagerService.getInstance().getUserIds()) { 3932 final int packageCount = mPackages.size(); 3933 for (int i = 0; i < packageCount; i++) { 3934 PackageParser.Package pkg = mPackages.valueAt(i); 3935 if (!(pkg.mExtras instanceof PackageSetting)) { 3936 continue; 3937 } 3938 PackageSetting ps = (PackageSetting) pkg.mExtras; 3939 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3940 } 3941 } 3942 } 3943 } 3944 3945 @Override 3946 public int getPermissionFlags(String name, String packageName, int userId) { 3947 if (!sUserManager.exists(userId)) { 3948 return 0; 3949 } 3950 3951 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3952 3953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3954 "getPermissionFlags"); 3955 3956 synchronized (mPackages) { 3957 final PackageParser.Package pkg = mPackages.get(packageName); 3958 if (pkg == null) { 3959 throw new IllegalArgumentException("Unknown package: " + packageName); 3960 } 3961 3962 final BasePermission bp = mSettings.mPermissions.get(name); 3963 if (bp == null) { 3964 throw new IllegalArgumentException("Unknown permission: " + name); 3965 } 3966 3967 SettingBase sb = (SettingBase) pkg.mExtras; 3968 if (sb == null) { 3969 throw new IllegalArgumentException("Unknown package: " + packageName); 3970 } 3971 3972 PermissionsState permissionsState = sb.getPermissionsState(); 3973 return permissionsState.getPermissionFlags(name, userId); 3974 } 3975 } 3976 3977 @Override 3978 public void updatePermissionFlags(String name, String packageName, int flagMask, 3979 int flagValues, int userId) { 3980 if (!sUserManager.exists(userId)) { 3981 return; 3982 } 3983 3984 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 3985 3986 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3987 "updatePermissionFlags"); 3988 3989 // Only the system can change these flags and nothing else. 3990 if (getCallingUid() != Process.SYSTEM_UID) { 3991 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3992 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3993 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3994 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 3995 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 3996 } 3997 3998 synchronized (mPackages) { 3999 final PackageParser.Package pkg = mPackages.get(packageName); 4000 if (pkg == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final BasePermission bp = mSettings.mPermissions.get(name); 4005 if (bp == null) { 4006 throw new IllegalArgumentException("Unknown permission: " + name); 4007 } 4008 4009 SettingBase sb = (SettingBase) pkg.mExtras; 4010 if (sb == null) { 4011 throw new IllegalArgumentException("Unknown package: " + packageName); 4012 } 4013 4014 PermissionsState permissionsState = sb.getPermissionsState(); 4015 4016 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4017 4018 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4019 // Install and runtime permissions are stored in different places, 4020 // so figure out what permission changed and persist the change. 4021 if (permissionsState.getInstallPermissionState(name) != null) { 4022 scheduleWriteSettingsLocked(); 4023 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4024 || hadState) { 4025 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4026 } 4027 } 4028 } 4029 } 4030 4031 /** 4032 * Update the permission flags for all packages and runtime permissions of a user in order 4033 * to allow device or profile owner to remove POLICY_FIXED. 4034 */ 4035 @Override 4036 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4037 if (!sUserManager.exists(userId)) { 4038 return; 4039 } 4040 4041 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4042 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4044 "updatePermissionFlagsForAllApps"); 4045 4046 // Only the system can change system fixed flags. 4047 if (getCallingUid() != Process.SYSTEM_UID) { 4048 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4049 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4050 } 4051 4052 synchronized (mPackages) { 4053 boolean changed = false; 4054 final int packageCount = mPackages.size(); 4055 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4056 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4057 SettingBase sb = (SettingBase) pkg.mExtras; 4058 if (sb == null) { 4059 continue; 4060 } 4061 PermissionsState permissionsState = sb.getPermissionsState(); 4062 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4063 userId, flagMask, flagValues); 4064 } 4065 if (changed) { 4066 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4067 } 4068 } 4069 } 4070 4071 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4072 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4073 != PackageManager.PERMISSION_GRANTED 4074 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4075 != PackageManager.PERMISSION_GRANTED) { 4076 throw new SecurityException(message + " requires " 4077 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4078 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4079 } 4080 } 4081 4082 @Override 4083 public boolean shouldShowRequestPermissionRationale(String permissionName, 4084 String packageName, int userId) { 4085 if (UserHandle.getCallingUserId() != userId) { 4086 mContext.enforceCallingPermission( 4087 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4088 "canShowRequestPermissionRationale for user " + userId); 4089 } 4090 4091 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4092 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4093 return false; 4094 } 4095 4096 if (checkPermission(permissionName, packageName, userId) 4097 == PackageManager.PERMISSION_GRANTED) { 4098 return false; 4099 } 4100 4101 final int flags; 4102 4103 final long identity = Binder.clearCallingIdentity(); 4104 try { 4105 flags = getPermissionFlags(permissionName, 4106 packageName, userId); 4107 } finally { 4108 Binder.restoreCallingIdentity(identity); 4109 } 4110 4111 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4112 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4113 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4114 4115 if ((flags & fixedFlags) != 0) { 4116 return false; 4117 } 4118 4119 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4120 } 4121 4122 @Override 4123 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4124 mContext.enforceCallingOrSelfPermission( 4125 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4126 "addOnPermissionsChangeListener"); 4127 4128 synchronized (mPackages) { 4129 mOnPermissionChangeListeners.addListenerLocked(listener); 4130 } 4131 } 4132 4133 @Override 4134 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4135 synchronized (mPackages) { 4136 mOnPermissionChangeListeners.removeListenerLocked(listener); 4137 } 4138 } 4139 4140 @Override 4141 public boolean isProtectedBroadcast(String actionName) { 4142 synchronized (mPackages) { 4143 if (mProtectedBroadcasts.contains(actionName)) { 4144 return true; 4145 } else if (actionName != null) { 4146 // TODO: remove these terrible hacks 4147 if (actionName.startsWith("android.net.netmon.lingerExpired") 4148 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4149 return true; 4150 } 4151 } 4152 } 4153 return false; 4154 } 4155 4156 @Override 4157 public int checkSignatures(String pkg1, String pkg2) { 4158 synchronized (mPackages) { 4159 final PackageParser.Package p1 = mPackages.get(pkg1); 4160 final PackageParser.Package p2 = mPackages.get(pkg2); 4161 if (p1 == null || p1.mExtras == null 4162 || p2 == null || p2.mExtras == null) { 4163 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4164 } 4165 return compareSignatures(p1.mSignatures, p2.mSignatures); 4166 } 4167 } 4168 4169 @Override 4170 public int checkUidSignatures(int uid1, int uid2) { 4171 // Map to base uids. 4172 uid1 = UserHandle.getAppId(uid1); 4173 uid2 = UserHandle.getAppId(uid2); 4174 // reader 4175 synchronized (mPackages) { 4176 Signature[] s1; 4177 Signature[] s2; 4178 Object obj = mSettings.getUserIdLPr(uid1); 4179 if (obj != null) { 4180 if (obj instanceof SharedUserSetting) { 4181 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4182 } else if (obj instanceof PackageSetting) { 4183 s1 = ((PackageSetting)obj).signatures.mSignatures; 4184 } else { 4185 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4186 } 4187 } else { 4188 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4189 } 4190 obj = mSettings.getUserIdLPr(uid2); 4191 if (obj != null) { 4192 if (obj instanceof SharedUserSetting) { 4193 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4194 } else if (obj instanceof PackageSetting) { 4195 s2 = ((PackageSetting)obj).signatures.mSignatures; 4196 } else { 4197 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4198 } 4199 } else { 4200 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4201 } 4202 return compareSignatures(s1, s2); 4203 } 4204 } 4205 4206 private void killUid(int appId, int userId, String reason) { 4207 final long identity = Binder.clearCallingIdentity(); 4208 try { 4209 IActivityManager am = ActivityManagerNative.getDefault(); 4210 if (am != null) { 4211 try { 4212 am.killUid(appId, userId, reason); 4213 } catch (RemoteException e) { 4214 /* ignore - same process */ 4215 } 4216 } 4217 } finally { 4218 Binder.restoreCallingIdentity(identity); 4219 } 4220 } 4221 4222 /** 4223 * Compares two sets of signatures. Returns: 4224 * <br /> 4225 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4226 * <br /> 4227 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4228 * <br /> 4229 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4230 * <br /> 4231 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4232 * <br /> 4233 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4234 */ 4235 static int compareSignatures(Signature[] s1, Signature[] s2) { 4236 if (s1 == null) { 4237 return s2 == null 4238 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4239 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4240 } 4241 4242 if (s2 == null) { 4243 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4244 } 4245 4246 if (s1.length != s2.length) { 4247 return PackageManager.SIGNATURE_NO_MATCH; 4248 } 4249 4250 // Since both signature sets are of size 1, we can compare without HashSets. 4251 if (s1.length == 1) { 4252 return s1[0].equals(s2[0]) ? 4253 PackageManager.SIGNATURE_MATCH : 4254 PackageManager.SIGNATURE_NO_MATCH; 4255 } 4256 4257 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4258 for (Signature sig : s1) { 4259 set1.add(sig); 4260 } 4261 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4262 for (Signature sig : s2) { 4263 set2.add(sig); 4264 } 4265 // Make sure s2 contains all signatures in s1. 4266 if (set1.equals(set2)) { 4267 return PackageManager.SIGNATURE_MATCH; 4268 } 4269 return PackageManager.SIGNATURE_NO_MATCH; 4270 } 4271 4272 /** 4273 * If the database version for this type of package (internal storage or 4274 * external storage) is less than the version where package signatures 4275 * were updated, return true. 4276 */ 4277 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4278 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4279 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4280 } 4281 4282 /** 4283 * Used for backward compatibility to make sure any packages with 4284 * certificate chains get upgraded to the new style. {@code existingSigs} 4285 * will be in the old format (since they were stored on disk from before the 4286 * system upgrade) and {@code scannedSigs} will be in the newer format. 4287 */ 4288 private int compareSignaturesCompat(PackageSignatures existingSigs, 4289 PackageParser.Package scannedPkg) { 4290 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4291 return PackageManager.SIGNATURE_NO_MATCH; 4292 } 4293 4294 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4295 for (Signature sig : existingSigs.mSignatures) { 4296 existingSet.add(sig); 4297 } 4298 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4299 for (Signature sig : scannedPkg.mSignatures) { 4300 try { 4301 Signature[] chainSignatures = sig.getChainSignatures(); 4302 for (Signature chainSig : chainSignatures) { 4303 scannedCompatSet.add(chainSig); 4304 } 4305 } catch (CertificateEncodingException e) { 4306 scannedCompatSet.add(sig); 4307 } 4308 } 4309 /* 4310 * Make sure the expanded scanned set contains all signatures in the 4311 * existing one. 4312 */ 4313 if (scannedCompatSet.equals(existingSet)) { 4314 // Migrate the old signatures to the new scheme. 4315 existingSigs.assignSignatures(scannedPkg.mSignatures); 4316 // The new KeySets will be re-added later in the scanning process. 4317 synchronized (mPackages) { 4318 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4319 } 4320 return PackageManager.SIGNATURE_MATCH; 4321 } 4322 return PackageManager.SIGNATURE_NO_MATCH; 4323 } 4324 4325 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4326 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4327 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4328 } 4329 4330 private int compareSignaturesRecover(PackageSignatures existingSigs, 4331 PackageParser.Package scannedPkg) { 4332 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4333 return PackageManager.SIGNATURE_NO_MATCH; 4334 } 4335 4336 String msg = null; 4337 try { 4338 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4339 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4340 + scannedPkg.packageName); 4341 return PackageManager.SIGNATURE_MATCH; 4342 } 4343 } catch (CertificateException e) { 4344 msg = e.getMessage(); 4345 } 4346 4347 logCriticalInfo(Log.INFO, 4348 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4349 return PackageManager.SIGNATURE_NO_MATCH; 4350 } 4351 4352 @Override 4353 public String[] getPackagesForUid(int uid) { 4354 uid = UserHandle.getAppId(uid); 4355 // reader 4356 synchronized (mPackages) { 4357 Object obj = mSettings.getUserIdLPr(uid); 4358 if (obj instanceof SharedUserSetting) { 4359 final SharedUserSetting sus = (SharedUserSetting) obj; 4360 final int N = sus.packages.size(); 4361 final String[] res = new String[N]; 4362 final Iterator<PackageSetting> it = sus.packages.iterator(); 4363 int i = 0; 4364 while (it.hasNext()) { 4365 res[i++] = it.next().name; 4366 } 4367 return res; 4368 } else if (obj instanceof PackageSetting) { 4369 final PackageSetting ps = (PackageSetting) obj; 4370 return new String[] { ps.name }; 4371 } 4372 } 4373 return null; 4374 } 4375 4376 @Override 4377 public String getNameForUid(int uid) { 4378 // reader 4379 synchronized (mPackages) { 4380 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4381 if (obj instanceof SharedUserSetting) { 4382 final SharedUserSetting sus = (SharedUserSetting) obj; 4383 return sus.name + ":" + sus.userId; 4384 } else if (obj instanceof PackageSetting) { 4385 final PackageSetting ps = (PackageSetting) obj; 4386 return ps.name; 4387 } 4388 } 4389 return null; 4390 } 4391 4392 @Override 4393 public int getUidForSharedUser(String sharedUserName) { 4394 if(sharedUserName == null) { 4395 return -1; 4396 } 4397 // reader 4398 synchronized (mPackages) { 4399 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4400 if (suid == null) { 4401 return -1; 4402 } 4403 return suid.userId; 4404 } 4405 } 4406 4407 @Override 4408 public int getFlagsForUid(int uid) { 4409 synchronized (mPackages) { 4410 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4411 if (obj instanceof SharedUserSetting) { 4412 final SharedUserSetting sus = (SharedUserSetting) obj; 4413 return sus.pkgFlags; 4414 } else if (obj instanceof PackageSetting) { 4415 final PackageSetting ps = (PackageSetting) obj; 4416 return ps.pkgFlags; 4417 } 4418 } 4419 return 0; 4420 } 4421 4422 @Override 4423 public int getPrivateFlagsForUid(int uid) { 4424 synchronized (mPackages) { 4425 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4426 if (obj instanceof SharedUserSetting) { 4427 final SharedUserSetting sus = (SharedUserSetting) obj; 4428 return sus.pkgPrivateFlags; 4429 } else if (obj instanceof PackageSetting) { 4430 final PackageSetting ps = (PackageSetting) obj; 4431 return ps.pkgPrivateFlags; 4432 } 4433 } 4434 return 0; 4435 } 4436 4437 @Override 4438 public boolean isUidPrivileged(int uid) { 4439 uid = UserHandle.getAppId(uid); 4440 // reader 4441 synchronized (mPackages) { 4442 Object obj = mSettings.getUserIdLPr(uid); 4443 if (obj instanceof SharedUserSetting) { 4444 final SharedUserSetting sus = (SharedUserSetting) obj; 4445 final Iterator<PackageSetting> it = sus.packages.iterator(); 4446 while (it.hasNext()) { 4447 if (it.next().isPrivileged()) { 4448 return true; 4449 } 4450 } 4451 } else if (obj instanceof PackageSetting) { 4452 final PackageSetting ps = (PackageSetting) obj; 4453 return ps.isPrivileged(); 4454 } 4455 } 4456 return false; 4457 } 4458 4459 @Override 4460 public String[] getAppOpPermissionPackages(String permissionName) { 4461 synchronized (mPackages) { 4462 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4463 if (pkgs == null) { 4464 return null; 4465 } 4466 return pkgs.toArray(new String[pkgs.size()]); 4467 } 4468 } 4469 4470 @Override 4471 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4472 int flags, int userId) { 4473 if (!sUserManager.exists(userId)) return null; 4474 flags = updateFlagsForResolve(flags, userId, intent); 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4476 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4477 final ResolveInfo bestChoice = 4478 chooseBestActivity(intent, resolvedType, flags, query, userId); 4479 4480 if (isEphemeralAllowed(intent, query, userId)) { 4481 final EphemeralResolveInfo ai = 4482 getEphemeralResolveInfo(intent, resolvedType, userId); 4483 if (ai != null) { 4484 if (DEBUG_EPHEMERAL) { 4485 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4486 } 4487 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4488 bestChoice.ephemeralResolveInfo = ai; 4489 } 4490 } 4491 return bestChoice; 4492 } 4493 4494 @Override 4495 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4496 IntentFilter filter, int match, ComponentName activity) { 4497 final int userId = UserHandle.getCallingUserId(); 4498 if (DEBUG_PREFERRED) { 4499 Log.v(TAG, "setLastChosenActivity intent=" + intent 4500 + " resolvedType=" + resolvedType 4501 + " flags=" + flags 4502 + " filter=" + filter 4503 + " match=" + match 4504 + " activity=" + activity); 4505 filter.dump(new PrintStreamPrinter(System.out), " "); 4506 } 4507 intent.setComponent(null); 4508 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4509 // Find any earlier preferred or last chosen entries and nuke them 4510 findPreferredActivity(intent, resolvedType, 4511 flags, query, 0, false, true, false, userId); 4512 // Add the new activity as the last chosen for this filter 4513 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4514 "Setting last chosen"); 4515 } 4516 4517 @Override 4518 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4519 final int userId = UserHandle.getCallingUserId(); 4520 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4521 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4522 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4523 false, false, false, userId); 4524 } 4525 4526 4527 private boolean isEphemeralAllowed( 4528 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4529 // Short circuit and return early if possible. 4530 if (DISABLE_EPHEMERAL_APPS) { 4531 return false; 4532 } 4533 final int callingUser = UserHandle.getCallingUserId(); 4534 if (callingUser != UserHandle.USER_SYSTEM) { 4535 return false; 4536 } 4537 if (mEphemeralResolverConnection == null) { 4538 return false; 4539 } 4540 if (intent.getComponent() != null) { 4541 return false; 4542 } 4543 if (intent.getPackage() != null) { 4544 return false; 4545 } 4546 final boolean isWebUri = hasWebURI(intent); 4547 if (!isWebUri) { 4548 return false; 4549 } 4550 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4551 synchronized (mPackages) { 4552 final int count = resolvedActivites.size(); 4553 for (int n = 0; n < count; n++) { 4554 ResolveInfo info = resolvedActivites.get(n); 4555 String packageName = info.activityInfo.packageName; 4556 PackageSetting ps = mSettings.mPackages.get(packageName); 4557 if (ps != null) { 4558 // Try to get the status from User settings first 4559 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4560 int status = (int) (packedStatus >> 32); 4561 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4562 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4563 if (DEBUG_EPHEMERAL) { 4564 Slog.v(TAG, "DENY ephemeral apps;" 4565 + " pkg: " + packageName + ", status: " + status); 4566 } 4567 return false; 4568 } 4569 } 4570 } 4571 } 4572 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4573 return true; 4574 } 4575 4576 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4577 int userId) { 4578 MessageDigest digest = null; 4579 try { 4580 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4581 } catch (NoSuchAlgorithmException e) { 4582 // If we can't create a digest, ignore ephemeral apps. 4583 return null; 4584 } 4585 4586 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4587 final byte[] digestBytes = digest.digest(hostBytes); 4588 int shaPrefix = 4589 digestBytes[0] << 24 4590 | digestBytes[1] << 16 4591 | digestBytes[2] << 8 4592 | digestBytes[3] << 0; 4593 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4594 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4595 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4596 // No hash prefix match; there are no ephemeral apps for this domain. 4597 return null; 4598 } 4599 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4600 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4601 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4602 continue; 4603 } 4604 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4605 // No filters; this should never happen. 4606 if (filters.isEmpty()) { 4607 continue; 4608 } 4609 // We have a domain match; resolve the filters to see if anything matches. 4610 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4611 for (int j = filters.size() - 1; j >= 0; --j) { 4612 final EphemeralResolveIntentInfo intentInfo = 4613 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4614 ephemeralResolver.addFilter(intentInfo); 4615 } 4616 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4617 intent, resolvedType, false /*defaultOnly*/, userId); 4618 if (!matchedResolveInfoList.isEmpty()) { 4619 return matchedResolveInfoList.get(0); 4620 } 4621 } 4622 // Hash or filter mis-match; no ephemeral apps for this domain. 4623 return null; 4624 } 4625 4626 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4627 int flags, List<ResolveInfo> query, int userId) { 4628 if (query != null) { 4629 final int N = query.size(); 4630 if (N == 1) { 4631 return query.get(0); 4632 } else if (N > 1) { 4633 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4634 // If there is more than one activity with the same priority, 4635 // then let the user decide between them. 4636 ResolveInfo r0 = query.get(0); 4637 ResolveInfo r1 = query.get(1); 4638 if (DEBUG_INTENT_MATCHING || debug) { 4639 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4640 + r1.activityInfo.name + "=" + r1.priority); 4641 } 4642 // If the first activity has a higher priority, or a different 4643 // default, then it is always desirable to pick it. 4644 if (r0.priority != r1.priority 4645 || r0.preferredOrder != r1.preferredOrder 4646 || r0.isDefault != r1.isDefault) { 4647 return query.get(0); 4648 } 4649 // If we have saved a preference for a preferred activity for 4650 // this Intent, use that. 4651 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4652 flags, query, r0.priority, true, false, debug, userId); 4653 if (ri != null) { 4654 return ri; 4655 } 4656 ri = new ResolveInfo(mResolveInfo); 4657 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4658 ri.activityInfo.applicationInfo = new ApplicationInfo( 4659 ri.activityInfo.applicationInfo); 4660 if (userId != 0) { 4661 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4662 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4663 } 4664 // Make sure that the resolver is displayable in car mode 4665 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4666 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4667 return ri; 4668 } 4669 } 4670 return null; 4671 } 4672 4673 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4674 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4675 final int N = query.size(); 4676 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4677 .get(userId); 4678 // Get the list of persistent preferred activities that handle the intent 4679 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4680 List<PersistentPreferredActivity> pprefs = ppir != null 4681 ? ppir.queryIntent(intent, resolvedType, 4682 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4683 : null; 4684 if (pprefs != null && pprefs.size() > 0) { 4685 final int M = pprefs.size(); 4686 for (int i=0; i<M; i++) { 4687 final PersistentPreferredActivity ppa = pprefs.get(i); 4688 if (DEBUG_PREFERRED || debug) { 4689 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4690 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4691 + "\n component=" + ppa.mComponent); 4692 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4693 } 4694 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4695 flags | MATCH_DISABLED_COMPONENTS, userId); 4696 if (DEBUG_PREFERRED || debug) { 4697 Slog.v(TAG, "Found persistent preferred activity:"); 4698 if (ai != null) { 4699 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4700 } else { 4701 Slog.v(TAG, " null"); 4702 } 4703 } 4704 if (ai == null) { 4705 // This previously registered persistent preferred activity 4706 // component is no longer known. Ignore it and do NOT remove it. 4707 continue; 4708 } 4709 for (int j=0; j<N; j++) { 4710 final ResolveInfo ri = query.get(j); 4711 if (!ri.activityInfo.applicationInfo.packageName 4712 .equals(ai.applicationInfo.packageName)) { 4713 continue; 4714 } 4715 if (!ri.activityInfo.name.equals(ai.name)) { 4716 continue; 4717 } 4718 // Found a persistent preference that can handle the intent. 4719 if (DEBUG_PREFERRED || debug) { 4720 Slog.v(TAG, "Returning persistent preferred activity: " + 4721 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4722 } 4723 return ri; 4724 } 4725 } 4726 } 4727 return null; 4728 } 4729 4730 // TODO: handle preferred activities missing while user has amnesia 4731 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4732 List<ResolveInfo> query, int priority, boolean always, 4733 boolean removeMatches, boolean debug, int userId) { 4734 if (!sUserManager.exists(userId)) return null; 4735 flags = updateFlagsForResolve(flags, userId, intent); 4736 // writer 4737 synchronized (mPackages) { 4738 if (intent.getSelector() != null) { 4739 intent = intent.getSelector(); 4740 } 4741 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4742 4743 // Try to find a matching persistent preferred activity. 4744 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4745 debug, userId); 4746 4747 // If a persistent preferred activity matched, use it. 4748 if (pri != null) { 4749 return pri; 4750 } 4751 4752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4753 // Get the list of preferred activities that handle the intent 4754 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4755 List<PreferredActivity> prefs = pir != null 4756 ? pir.queryIntent(intent, resolvedType, 4757 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4758 : null; 4759 if (prefs != null && prefs.size() > 0) { 4760 boolean changed = false; 4761 try { 4762 // First figure out how good the original match set is. 4763 // We will only allow preferred activities that came 4764 // from the same match quality. 4765 int match = 0; 4766 4767 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4768 4769 final int N = query.size(); 4770 for (int j=0; j<N; j++) { 4771 final ResolveInfo ri = query.get(j); 4772 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4773 + ": 0x" + Integer.toHexString(match)); 4774 if (ri.match > match) { 4775 match = ri.match; 4776 } 4777 } 4778 4779 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4780 + Integer.toHexString(match)); 4781 4782 match &= IntentFilter.MATCH_CATEGORY_MASK; 4783 final int M = prefs.size(); 4784 for (int i=0; i<M; i++) { 4785 final PreferredActivity pa = prefs.get(i); 4786 if (DEBUG_PREFERRED || debug) { 4787 Slog.v(TAG, "Checking PreferredActivity ds=" 4788 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4789 + "\n component=" + pa.mPref.mComponent); 4790 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4791 } 4792 if (pa.mPref.mMatch != match) { 4793 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4794 + Integer.toHexString(pa.mPref.mMatch)); 4795 continue; 4796 } 4797 // If it's not an "always" type preferred activity and that's what we're 4798 // looking for, skip it. 4799 if (always && !pa.mPref.mAlways) { 4800 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4801 continue; 4802 } 4803 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4804 flags | MATCH_DISABLED_COMPONENTS, userId); 4805 if (DEBUG_PREFERRED || debug) { 4806 Slog.v(TAG, "Found preferred activity:"); 4807 if (ai != null) { 4808 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4809 } else { 4810 Slog.v(TAG, " null"); 4811 } 4812 } 4813 if (ai == null) { 4814 // This previously registered preferred activity 4815 // component is no longer known. Most likely an update 4816 // to the app was installed and in the new version this 4817 // component no longer exists. Clean it up by removing 4818 // it from the preferred activities list, and skip it. 4819 Slog.w(TAG, "Removing dangling preferred activity: " 4820 + pa.mPref.mComponent); 4821 pir.removeFilter(pa); 4822 changed = true; 4823 continue; 4824 } 4825 for (int j=0; j<N; j++) { 4826 final ResolveInfo ri = query.get(j); 4827 if (!ri.activityInfo.applicationInfo.packageName 4828 .equals(ai.applicationInfo.packageName)) { 4829 continue; 4830 } 4831 if (!ri.activityInfo.name.equals(ai.name)) { 4832 continue; 4833 } 4834 4835 if (removeMatches) { 4836 pir.removeFilter(pa); 4837 changed = true; 4838 if (DEBUG_PREFERRED) { 4839 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4840 } 4841 break; 4842 } 4843 4844 // Okay we found a previously set preferred or last chosen app. 4845 // If the result set is different from when this 4846 // was created, we need to clear it and re-ask the 4847 // user their preference, if we're looking for an "always" type entry. 4848 if (always && !pa.mPref.sameSet(query)) { 4849 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4850 + intent + " type " + resolvedType); 4851 if (DEBUG_PREFERRED) { 4852 Slog.v(TAG, "Removing preferred activity since set changed " 4853 + pa.mPref.mComponent); 4854 } 4855 pir.removeFilter(pa); 4856 // Re-add the filter as a "last chosen" entry (!always) 4857 PreferredActivity lastChosen = new PreferredActivity( 4858 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4859 pir.addFilter(lastChosen); 4860 changed = true; 4861 return null; 4862 } 4863 4864 // Yay! Either the set matched or we're looking for the last chosen 4865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4866 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4867 return ri; 4868 } 4869 } 4870 } finally { 4871 if (changed) { 4872 if (DEBUG_PREFERRED) { 4873 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4874 } 4875 scheduleWritePackageRestrictionsLocked(userId); 4876 } 4877 } 4878 } 4879 } 4880 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4881 return null; 4882 } 4883 4884 /* 4885 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4886 */ 4887 @Override 4888 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4889 int targetUserId) { 4890 mContext.enforceCallingOrSelfPermission( 4891 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4892 List<CrossProfileIntentFilter> matches = 4893 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4894 if (matches != null) { 4895 int size = matches.size(); 4896 for (int i = 0; i < size; i++) { 4897 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4898 } 4899 } 4900 if (hasWebURI(intent)) { 4901 // cross-profile app linking works only towards the parent. 4902 final UserInfo parent = getProfileParent(sourceUserId); 4903 synchronized(mPackages) { 4904 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4905 intent, resolvedType, 0, sourceUserId, parent.id); 4906 return xpDomainInfo != null; 4907 } 4908 } 4909 return false; 4910 } 4911 4912 private UserInfo getProfileParent(int userId) { 4913 final long identity = Binder.clearCallingIdentity(); 4914 try { 4915 return sUserManager.getProfileParent(userId); 4916 } finally { 4917 Binder.restoreCallingIdentity(identity); 4918 } 4919 } 4920 4921 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4922 String resolvedType, int userId) { 4923 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4924 if (resolver != null) { 4925 return resolver.queryIntent(intent, resolvedType, false, userId); 4926 } 4927 return null; 4928 } 4929 4930 @Override 4931 public List<ResolveInfo> queryIntentActivities(Intent intent, 4932 String resolvedType, int flags, int userId) { 4933 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4934 flags = updateFlagsForResolve(flags, userId, intent); 4935 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4936 ComponentName comp = intent.getComponent(); 4937 if (comp == null) { 4938 if (intent.getSelector() != null) { 4939 intent = intent.getSelector(); 4940 comp = intent.getComponent(); 4941 } 4942 } 4943 4944 if (comp != null) { 4945 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4946 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4947 if (ai != null) { 4948 final ResolveInfo ri = new ResolveInfo(); 4949 ri.activityInfo = ai; 4950 list.add(ri); 4951 } 4952 return list; 4953 } 4954 4955 // reader 4956 synchronized (mPackages) { 4957 final String pkgName = intent.getPackage(); 4958 if (pkgName == null) { 4959 List<CrossProfileIntentFilter> matchingFilters = 4960 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4961 // Check for results that need to skip the current profile. 4962 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4963 resolvedType, flags, userId); 4964 if (xpResolveInfo != null) { 4965 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4966 result.add(xpResolveInfo); 4967 return filterIfNotSystemUser(result, userId); 4968 } 4969 4970 // Check for results in the current profile. 4971 List<ResolveInfo> result = mActivities.queryIntent( 4972 intent, resolvedType, flags, userId); 4973 result = filterIfNotSystemUser(result, userId); 4974 4975 // Check for cross profile results. 4976 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 4977 xpResolveInfo = queryCrossProfileIntents( 4978 matchingFilters, intent, resolvedType, flags, userId, 4979 hasNonNegativePriorityResult); 4980 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4981 boolean isVisibleToUser = filterIfNotSystemUser( 4982 Collections.singletonList(xpResolveInfo), userId).size() > 0; 4983 if (isVisibleToUser) { 4984 result.add(xpResolveInfo); 4985 Collections.sort(result, mResolvePrioritySorter); 4986 } 4987 } 4988 if (hasWebURI(intent)) { 4989 CrossProfileDomainInfo xpDomainInfo = null; 4990 final UserInfo parent = getProfileParent(userId); 4991 if (parent != null) { 4992 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4993 flags, userId, parent.id); 4994 } 4995 if (xpDomainInfo != null) { 4996 if (xpResolveInfo != null) { 4997 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4998 // in the result. 4999 result.remove(xpResolveInfo); 5000 } 5001 if (result.size() == 0) { 5002 result.add(xpDomainInfo.resolveInfo); 5003 return result; 5004 } 5005 } else if (result.size() <= 1) { 5006 return result; 5007 } 5008 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5009 xpDomainInfo, userId); 5010 Collections.sort(result, mResolvePrioritySorter); 5011 } 5012 return result; 5013 } 5014 final PackageParser.Package pkg = mPackages.get(pkgName); 5015 if (pkg != null) { 5016 return filterIfNotSystemUser( 5017 mActivities.queryIntentForPackage( 5018 intent, resolvedType, flags, pkg.activities, userId), 5019 userId); 5020 } 5021 return new ArrayList<ResolveInfo>(); 5022 } 5023 } 5024 5025 private static class CrossProfileDomainInfo { 5026 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5027 ResolveInfo resolveInfo; 5028 /* Best domain verification status of the activities found in the other profile */ 5029 int bestDomainVerificationStatus; 5030 } 5031 5032 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5033 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5034 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5035 sourceUserId)) { 5036 return null; 5037 } 5038 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5039 resolvedType, flags, parentUserId); 5040 5041 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5042 return null; 5043 } 5044 CrossProfileDomainInfo result = null; 5045 int size = resultTargetUser.size(); 5046 for (int i = 0; i < size; i++) { 5047 ResolveInfo riTargetUser = resultTargetUser.get(i); 5048 // Intent filter verification is only for filters that specify a host. So don't return 5049 // those that handle all web uris. 5050 if (riTargetUser.handleAllWebDataURI) { 5051 continue; 5052 } 5053 String packageName = riTargetUser.activityInfo.packageName; 5054 PackageSetting ps = mSettings.mPackages.get(packageName); 5055 if (ps == null) { 5056 continue; 5057 } 5058 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5059 int status = (int)(verificationState >> 32); 5060 if (result == null) { 5061 result = new CrossProfileDomainInfo(); 5062 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5063 sourceUserId, parentUserId); 5064 result.bestDomainVerificationStatus = status; 5065 } else { 5066 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5067 result.bestDomainVerificationStatus); 5068 } 5069 } 5070 // Don't consider matches with status NEVER across profiles. 5071 if (result != null && result.bestDomainVerificationStatus 5072 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5073 return null; 5074 } 5075 return result; 5076 } 5077 5078 /** 5079 * Verification statuses are ordered from the worse to the best, except for 5080 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5081 */ 5082 private int bestDomainVerificationStatus(int status1, int status2) { 5083 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5084 return status2; 5085 } 5086 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5087 return status1; 5088 } 5089 return (int) MathUtils.max(status1, status2); 5090 } 5091 5092 private boolean isUserEnabled(int userId) { 5093 long callingId = Binder.clearCallingIdentity(); 5094 try { 5095 UserInfo userInfo = sUserManager.getUserInfo(userId); 5096 return userInfo != null && userInfo.isEnabled(); 5097 } finally { 5098 Binder.restoreCallingIdentity(callingId); 5099 } 5100 } 5101 5102 /** 5103 * Filter out activities with systemUserOnly flag set, when current user is not System. 5104 * 5105 * @return filtered list 5106 */ 5107 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5108 if (userId == UserHandle.USER_SYSTEM) { 5109 return resolveInfos; 5110 } 5111 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5112 ResolveInfo info = resolveInfos.get(i); 5113 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5114 resolveInfos.remove(i); 5115 } 5116 } 5117 return resolveInfos; 5118 } 5119 5120 /** 5121 * @param resolveInfos list of resolve infos in descending priority order 5122 * @return if the list contains a resolve info with non-negative priority 5123 */ 5124 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5125 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5126 } 5127 5128 private static boolean hasWebURI(Intent intent) { 5129 if (intent.getData() == null) { 5130 return false; 5131 } 5132 final String scheme = intent.getScheme(); 5133 if (TextUtils.isEmpty(scheme)) { 5134 return false; 5135 } 5136 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5137 } 5138 5139 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5140 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5141 int userId) { 5142 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5143 5144 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5145 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5146 candidates.size()); 5147 } 5148 5149 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5150 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5151 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5152 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5153 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5154 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5155 5156 synchronized (mPackages) { 5157 final int count = candidates.size(); 5158 // First, try to use linked apps. Partition the candidates into four lists: 5159 // one for the final results, one for the "do not use ever", one for "undefined status" 5160 // and finally one for "browser app type". 5161 for (int n=0; n<count; n++) { 5162 ResolveInfo info = candidates.get(n); 5163 String packageName = info.activityInfo.packageName; 5164 PackageSetting ps = mSettings.mPackages.get(packageName); 5165 if (ps != null) { 5166 // Add to the special match all list (Browser use case) 5167 if (info.handleAllWebDataURI) { 5168 matchAllList.add(info); 5169 continue; 5170 } 5171 // Try to get the status from User settings first 5172 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5173 int status = (int)(packedStatus >> 32); 5174 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5175 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5176 if (DEBUG_DOMAIN_VERIFICATION) { 5177 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5178 + " : linkgen=" + linkGeneration); 5179 } 5180 // Use link-enabled generation as preferredOrder, i.e. 5181 // prefer newly-enabled over earlier-enabled. 5182 info.preferredOrder = linkGeneration; 5183 alwaysList.add(info); 5184 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5185 if (DEBUG_DOMAIN_VERIFICATION) { 5186 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5187 } 5188 neverList.add(info); 5189 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5190 if (DEBUG_DOMAIN_VERIFICATION) { 5191 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5192 } 5193 alwaysAskList.add(info); 5194 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5195 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5196 if (DEBUG_DOMAIN_VERIFICATION) { 5197 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5198 } 5199 undefinedList.add(info); 5200 } 5201 } 5202 } 5203 5204 // We'll want to include browser possibilities in a few cases 5205 boolean includeBrowser = false; 5206 5207 // First try to add the "always" resolution(s) for the current user, if any 5208 if (alwaysList.size() > 0) { 5209 result.addAll(alwaysList); 5210 } else { 5211 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5212 result.addAll(undefinedList); 5213 // Maybe add one for the other profile. 5214 if (xpDomainInfo != null && ( 5215 xpDomainInfo.bestDomainVerificationStatus 5216 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5217 result.add(xpDomainInfo.resolveInfo); 5218 } 5219 includeBrowser = true; 5220 } 5221 5222 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5223 // If there were 'always' entries their preferred order has been set, so we also 5224 // back that off to make the alternatives equivalent 5225 if (alwaysAskList.size() > 0) { 5226 for (ResolveInfo i : result) { 5227 i.preferredOrder = 0; 5228 } 5229 result.addAll(alwaysAskList); 5230 includeBrowser = true; 5231 } 5232 5233 if (includeBrowser) { 5234 // Also add browsers (all of them or only the default one) 5235 if (DEBUG_DOMAIN_VERIFICATION) { 5236 Slog.v(TAG, " ...including browsers in candidate set"); 5237 } 5238 if ((matchFlags & MATCH_ALL) != 0) { 5239 result.addAll(matchAllList); 5240 } else { 5241 // Browser/generic handling case. If there's a default browser, go straight 5242 // to that (but only if there is no other higher-priority match). 5243 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5244 int maxMatchPrio = 0; 5245 ResolveInfo defaultBrowserMatch = null; 5246 final int numCandidates = matchAllList.size(); 5247 for (int n = 0; n < numCandidates; n++) { 5248 ResolveInfo info = matchAllList.get(n); 5249 // track the highest overall match priority... 5250 if (info.priority > maxMatchPrio) { 5251 maxMatchPrio = info.priority; 5252 } 5253 // ...and the highest-priority default browser match 5254 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5255 if (defaultBrowserMatch == null 5256 || (defaultBrowserMatch.priority < info.priority)) { 5257 if (debug) { 5258 Slog.v(TAG, "Considering default browser match " + info); 5259 } 5260 defaultBrowserMatch = info; 5261 } 5262 } 5263 } 5264 if (defaultBrowserMatch != null 5265 && defaultBrowserMatch.priority >= maxMatchPrio 5266 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5267 { 5268 if (debug) { 5269 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5270 } 5271 result.add(defaultBrowserMatch); 5272 } else { 5273 result.addAll(matchAllList); 5274 } 5275 } 5276 5277 // If there is nothing selected, add all candidates and remove the ones that the user 5278 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5279 if (result.size() == 0) { 5280 result.addAll(candidates); 5281 result.removeAll(neverList); 5282 } 5283 } 5284 } 5285 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5286 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5287 result.size()); 5288 for (ResolveInfo info : result) { 5289 Slog.v(TAG, " + " + info.activityInfo); 5290 } 5291 } 5292 return result; 5293 } 5294 5295 // Returns a packed value as a long: 5296 // 5297 // high 'int'-sized word: link status: undefined/ask/never/always. 5298 // low 'int'-sized word: relative priority among 'always' results. 5299 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5300 long result = ps.getDomainVerificationStatusForUser(userId); 5301 // if none available, get the master status 5302 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5303 if (ps.getIntentFilterVerificationInfo() != null) { 5304 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5305 } 5306 } 5307 return result; 5308 } 5309 5310 private ResolveInfo querySkipCurrentProfileIntents( 5311 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5312 int flags, int sourceUserId) { 5313 if (matchingFilters != null) { 5314 int size = matchingFilters.size(); 5315 for (int i = 0; i < size; i ++) { 5316 CrossProfileIntentFilter filter = matchingFilters.get(i); 5317 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5318 // Checking if there are activities in the target user that can handle the 5319 // intent. 5320 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5321 resolvedType, flags, sourceUserId); 5322 if (resolveInfo != null) { 5323 return resolveInfo; 5324 } 5325 } 5326 } 5327 } 5328 return null; 5329 } 5330 5331 // Return matching ResolveInfo in target user if any. 5332 private ResolveInfo queryCrossProfileIntents( 5333 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5334 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5335 if (matchingFilters != null) { 5336 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5337 // match the same intent. For performance reasons, it is better not to 5338 // run queryIntent twice for the same userId 5339 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5340 int size = matchingFilters.size(); 5341 for (int i = 0; i < size; i++) { 5342 CrossProfileIntentFilter filter = matchingFilters.get(i); 5343 int targetUserId = filter.getTargetUserId(); 5344 boolean skipCurrentProfile = 5345 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5346 boolean skipCurrentProfileIfNoMatchFound = 5347 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5348 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5349 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5350 // Checking if there are activities in the target user that can handle the 5351 // intent. 5352 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5353 resolvedType, flags, sourceUserId); 5354 if (resolveInfo != null) return resolveInfo; 5355 alreadyTriedUserIds.put(targetUserId, true); 5356 } 5357 } 5358 } 5359 return null; 5360 } 5361 5362 /** 5363 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5364 * will forward the intent to the filter's target user. 5365 * Otherwise, returns null. 5366 */ 5367 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5368 String resolvedType, int flags, int sourceUserId) { 5369 int targetUserId = filter.getTargetUserId(); 5370 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5371 resolvedType, flags, targetUserId); 5372 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5373 // If all the matches in the target profile are suspended, return null. 5374 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5375 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5376 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5377 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5378 targetUserId); 5379 } 5380 } 5381 } 5382 return null; 5383 } 5384 5385 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5386 int sourceUserId, int targetUserId) { 5387 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5388 long ident = Binder.clearCallingIdentity(); 5389 boolean targetIsProfile; 5390 try { 5391 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5392 } finally { 5393 Binder.restoreCallingIdentity(ident); 5394 } 5395 String className; 5396 if (targetIsProfile) { 5397 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5398 } else { 5399 className = FORWARD_INTENT_TO_PARENT; 5400 } 5401 ComponentName forwardingActivityComponentName = new ComponentName( 5402 mAndroidApplication.packageName, className); 5403 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5404 sourceUserId); 5405 if (!targetIsProfile) { 5406 forwardingActivityInfo.showUserIcon = targetUserId; 5407 forwardingResolveInfo.noResourceId = true; 5408 } 5409 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5410 forwardingResolveInfo.priority = 0; 5411 forwardingResolveInfo.preferredOrder = 0; 5412 forwardingResolveInfo.match = 0; 5413 forwardingResolveInfo.isDefault = true; 5414 forwardingResolveInfo.filter = filter; 5415 forwardingResolveInfo.targetUserId = targetUserId; 5416 return forwardingResolveInfo; 5417 } 5418 5419 @Override 5420 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5421 Intent[] specifics, String[] specificTypes, Intent intent, 5422 String resolvedType, int flags, int userId) { 5423 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5424 flags = updateFlagsForResolve(flags, userId, intent); 5425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5426 false, "query intent activity options"); 5427 final String resultsAction = intent.getAction(); 5428 5429 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5430 | PackageManager.GET_RESOLVED_FILTER, userId); 5431 5432 if (DEBUG_INTENT_MATCHING) { 5433 Log.v(TAG, "Query " + intent + ": " + results); 5434 } 5435 5436 int specificsPos = 0; 5437 int N; 5438 5439 // todo: note that the algorithm used here is O(N^2). This 5440 // isn't a problem in our current environment, but if we start running 5441 // into situations where we have more than 5 or 10 matches then this 5442 // should probably be changed to something smarter... 5443 5444 // First we go through and resolve each of the specific items 5445 // that were supplied, taking care of removing any corresponding 5446 // duplicate items in the generic resolve list. 5447 if (specifics != null) { 5448 for (int i=0; i<specifics.length; i++) { 5449 final Intent sintent = specifics[i]; 5450 if (sintent == null) { 5451 continue; 5452 } 5453 5454 if (DEBUG_INTENT_MATCHING) { 5455 Log.v(TAG, "Specific #" + i + ": " + sintent); 5456 } 5457 5458 String action = sintent.getAction(); 5459 if (resultsAction != null && resultsAction.equals(action)) { 5460 // If this action was explicitly requested, then don't 5461 // remove things that have it. 5462 action = null; 5463 } 5464 5465 ResolveInfo ri = null; 5466 ActivityInfo ai = null; 5467 5468 ComponentName comp = sintent.getComponent(); 5469 if (comp == null) { 5470 ri = resolveIntent( 5471 sintent, 5472 specificTypes != null ? specificTypes[i] : null, 5473 flags, userId); 5474 if (ri == null) { 5475 continue; 5476 } 5477 if (ri == mResolveInfo) { 5478 // ACK! Must do something better with this. 5479 } 5480 ai = ri.activityInfo; 5481 comp = new ComponentName(ai.applicationInfo.packageName, 5482 ai.name); 5483 } else { 5484 ai = getActivityInfo(comp, flags, userId); 5485 if (ai == null) { 5486 continue; 5487 } 5488 } 5489 5490 // Look for any generic query activities that are duplicates 5491 // of this specific one, and remove them from the results. 5492 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5493 N = results.size(); 5494 int j; 5495 for (j=specificsPos; j<N; j++) { 5496 ResolveInfo sri = results.get(j); 5497 if ((sri.activityInfo.name.equals(comp.getClassName()) 5498 && sri.activityInfo.applicationInfo.packageName.equals( 5499 comp.getPackageName())) 5500 || (action != null && sri.filter.matchAction(action))) { 5501 results.remove(j); 5502 if (DEBUG_INTENT_MATCHING) Log.v( 5503 TAG, "Removing duplicate item from " + j 5504 + " due to specific " + specificsPos); 5505 if (ri == null) { 5506 ri = sri; 5507 } 5508 j--; 5509 N--; 5510 } 5511 } 5512 5513 // Add this specific item to its proper place. 5514 if (ri == null) { 5515 ri = new ResolveInfo(); 5516 ri.activityInfo = ai; 5517 } 5518 results.add(specificsPos, ri); 5519 ri.specificIndex = i; 5520 specificsPos++; 5521 } 5522 } 5523 5524 // Now we go through the remaining generic results and remove any 5525 // duplicate actions that are found here. 5526 N = results.size(); 5527 for (int i=specificsPos; i<N-1; i++) { 5528 final ResolveInfo rii = results.get(i); 5529 if (rii.filter == null) { 5530 continue; 5531 } 5532 5533 // Iterate over all of the actions of this result's intent 5534 // filter... typically this should be just one. 5535 final Iterator<String> it = rii.filter.actionsIterator(); 5536 if (it == null) { 5537 continue; 5538 } 5539 while (it.hasNext()) { 5540 final String action = it.next(); 5541 if (resultsAction != null && resultsAction.equals(action)) { 5542 // If this action was explicitly requested, then don't 5543 // remove things that have it. 5544 continue; 5545 } 5546 for (int j=i+1; j<N; j++) { 5547 final ResolveInfo rij = results.get(j); 5548 if (rij.filter != null && rij.filter.hasAction(action)) { 5549 results.remove(j); 5550 if (DEBUG_INTENT_MATCHING) Log.v( 5551 TAG, "Removing duplicate item from " + j 5552 + " due to action " + action + " at " + i); 5553 j--; 5554 N--; 5555 } 5556 } 5557 } 5558 5559 // If the caller didn't request filter information, drop it now 5560 // so we don't have to marshall/unmarshall it. 5561 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5562 rii.filter = null; 5563 } 5564 } 5565 5566 // Filter out the caller activity if so requested. 5567 if (caller != null) { 5568 N = results.size(); 5569 for (int i=0; i<N; i++) { 5570 ActivityInfo ainfo = results.get(i).activityInfo; 5571 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5572 && caller.getClassName().equals(ainfo.name)) { 5573 results.remove(i); 5574 break; 5575 } 5576 } 5577 } 5578 5579 // If the caller didn't request filter information, 5580 // drop them now so we don't have to 5581 // marshall/unmarshall it. 5582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5583 N = results.size(); 5584 for (int i=0; i<N; i++) { 5585 results.get(i).filter = null; 5586 } 5587 } 5588 5589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5590 return results; 5591 } 5592 5593 @Override 5594 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5595 int userId) { 5596 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5597 flags = updateFlagsForResolve(flags, userId, intent); 5598 ComponentName comp = intent.getComponent(); 5599 if (comp == null) { 5600 if (intent.getSelector() != null) { 5601 intent = intent.getSelector(); 5602 comp = intent.getComponent(); 5603 } 5604 } 5605 if (comp != null) { 5606 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5607 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5608 if (ai != null) { 5609 ResolveInfo ri = new ResolveInfo(); 5610 ri.activityInfo = ai; 5611 list.add(ri); 5612 } 5613 return list; 5614 } 5615 5616 // reader 5617 synchronized (mPackages) { 5618 String pkgName = intent.getPackage(); 5619 if (pkgName == null) { 5620 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5621 } 5622 final PackageParser.Package pkg = mPackages.get(pkgName); 5623 if (pkg != null) { 5624 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5625 userId); 5626 } 5627 return null; 5628 } 5629 } 5630 5631 @Override 5632 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5633 if (!sUserManager.exists(userId)) return null; 5634 flags = updateFlagsForResolve(flags, userId, intent); 5635 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5636 if (query != null) { 5637 if (query.size() >= 1) { 5638 // If there is more than one service with the same priority, 5639 // just arbitrarily pick the first one. 5640 return query.get(0); 5641 } 5642 } 5643 return null; 5644 } 5645 5646 @Override 5647 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5648 int userId) { 5649 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5650 flags = updateFlagsForResolve(flags, userId, intent); 5651 ComponentName comp = intent.getComponent(); 5652 if (comp == null) { 5653 if (intent.getSelector() != null) { 5654 intent = intent.getSelector(); 5655 comp = intent.getComponent(); 5656 } 5657 } 5658 if (comp != null) { 5659 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5660 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5661 if (si != null) { 5662 final ResolveInfo ri = new ResolveInfo(); 5663 ri.serviceInfo = si; 5664 list.add(ri); 5665 } 5666 return list; 5667 } 5668 5669 // reader 5670 synchronized (mPackages) { 5671 String pkgName = intent.getPackage(); 5672 if (pkgName == null) { 5673 return mServices.queryIntent(intent, resolvedType, flags, userId); 5674 } 5675 final PackageParser.Package pkg = mPackages.get(pkgName); 5676 if (pkg != null) { 5677 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5678 userId); 5679 } 5680 return null; 5681 } 5682 } 5683 5684 @Override 5685 public List<ResolveInfo> queryIntentContentProviders( 5686 Intent intent, String resolvedType, int flags, int userId) { 5687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5688 flags = updateFlagsForResolve(flags, userId, intent); 5689 ComponentName comp = intent.getComponent(); 5690 if (comp == null) { 5691 if (intent.getSelector() != null) { 5692 intent = intent.getSelector(); 5693 comp = intent.getComponent(); 5694 } 5695 } 5696 if (comp != null) { 5697 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5698 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5699 if (pi != null) { 5700 final ResolveInfo ri = new ResolveInfo(); 5701 ri.providerInfo = pi; 5702 list.add(ri); 5703 } 5704 return list; 5705 } 5706 5707 // reader 5708 synchronized (mPackages) { 5709 String pkgName = intent.getPackage(); 5710 if (pkgName == null) { 5711 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5712 } 5713 final PackageParser.Package pkg = mPackages.get(pkgName); 5714 if (pkg != null) { 5715 return mProviders.queryIntentForPackage( 5716 intent, resolvedType, flags, pkg.providers, userId); 5717 } 5718 return null; 5719 } 5720 } 5721 5722 @Override 5723 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5724 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5725 flags = updateFlagsForPackage(flags, userId, null); 5726 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5727 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5728 5729 // writer 5730 synchronized (mPackages) { 5731 ArrayList<PackageInfo> list; 5732 if (listUninstalled) { 5733 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5734 for (PackageSetting ps : mSettings.mPackages.values()) { 5735 PackageInfo pi; 5736 if (ps.pkg != null) { 5737 pi = generatePackageInfo(ps.pkg, flags, userId); 5738 } else { 5739 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5740 } 5741 if (pi != null) { 5742 list.add(pi); 5743 } 5744 } 5745 } else { 5746 list = new ArrayList<PackageInfo>(mPackages.size()); 5747 for (PackageParser.Package p : mPackages.values()) { 5748 PackageInfo pi = generatePackageInfo(p, flags, userId); 5749 if (pi != null) { 5750 list.add(pi); 5751 } 5752 } 5753 } 5754 5755 return new ParceledListSlice<PackageInfo>(list); 5756 } 5757 } 5758 5759 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5760 String[] permissions, boolean[] tmp, int flags, int userId) { 5761 int numMatch = 0; 5762 final PermissionsState permissionsState = ps.getPermissionsState(); 5763 for (int i=0; i<permissions.length; i++) { 5764 final String permission = permissions[i]; 5765 if (permissionsState.hasPermission(permission, userId)) { 5766 tmp[i] = true; 5767 numMatch++; 5768 } else { 5769 tmp[i] = false; 5770 } 5771 } 5772 if (numMatch == 0) { 5773 return; 5774 } 5775 PackageInfo pi; 5776 if (ps.pkg != null) { 5777 pi = generatePackageInfo(ps.pkg, flags, userId); 5778 } else { 5779 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5780 } 5781 // The above might return null in cases of uninstalled apps or install-state 5782 // skew across users/profiles. 5783 if (pi != null) { 5784 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5785 if (numMatch == permissions.length) { 5786 pi.requestedPermissions = permissions; 5787 } else { 5788 pi.requestedPermissions = new String[numMatch]; 5789 numMatch = 0; 5790 for (int i=0; i<permissions.length; i++) { 5791 if (tmp[i]) { 5792 pi.requestedPermissions[numMatch] = permissions[i]; 5793 numMatch++; 5794 } 5795 } 5796 } 5797 } 5798 list.add(pi); 5799 } 5800 } 5801 5802 @Override 5803 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5804 String[] permissions, int flags, int userId) { 5805 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5806 flags = updateFlagsForPackage(flags, userId, permissions); 5807 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5808 5809 // writer 5810 synchronized (mPackages) { 5811 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5812 boolean[] tmpBools = new boolean[permissions.length]; 5813 if (listUninstalled) { 5814 for (PackageSetting ps : mSettings.mPackages.values()) { 5815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5816 } 5817 } else { 5818 for (PackageParser.Package pkg : mPackages.values()) { 5819 PackageSetting ps = (PackageSetting)pkg.mExtras; 5820 if (ps != null) { 5821 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5822 userId); 5823 } 5824 } 5825 } 5826 5827 return new ParceledListSlice<PackageInfo>(list); 5828 } 5829 } 5830 5831 @Override 5832 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5833 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5834 flags = updateFlagsForApplication(flags, userId, null); 5835 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5836 5837 // writer 5838 synchronized (mPackages) { 5839 ArrayList<ApplicationInfo> list; 5840 if (listUninstalled) { 5841 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5842 for (PackageSetting ps : mSettings.mPackages.values()) { 5843 ApplicationInfo ai; 5844 if (ps.pkg != null) { 5845 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5846 ps.readUserState(userId), userId); 5847 } else { 5848 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5849 } 5850 if (ai != null) { 5851 list.add(ai); 5852 } 5853 } 5854 } else { 5855 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5856 for (PackageParser.Package p : mPackages.values()) { 5857 if (p.mExtras != null) { 5858 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5859 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5860 if (ai != null) { 5861 list.add(ai); 5862 } 5863 } 5864 } 5865 } 5866 5867 return new ParceledListSlice<ApplicationInfo>(list); 5868 } 5869 } 5870 5871 @Override 5872 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5873 if (DISABLE_EPHEMERAL_APPS) { 5874 return null; 5875 } 5876 5877 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5878 "getEphemeralApplications"); 5879 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5880 "getEphemeralApplications"); 5881 synchronized (mPackages) { 5882 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5883 .getEphemeralApplicationsLPw(userId); 5884 if (ephemeralApps != null) { 5885 return new ParceledListSlice<>(ephemeralApps); 5886 } 5887 } 5888 return null; 5889 } 5890 5891 @Override 5892 public boolean isEphemeralApplication(String packageName, int userId) { 5893 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5894 "isEphemeral"); 5895 if (DISABLE_EPHEMERAL_APPS) { 5896 return false; 5897 } 5898 5899 if (!isCallerSameApp(packageName)) { 5900 return false; 5901 } 5902 synchronized (mPackages) { 5903 PackageParser.Package pkg = mPackages.get(packageName); 5904 if (pkg != null) { 5905 return pkg.applicationInfo.isEphemeralApp(); 5906 } 5907 } 5908 return false; 5909 } 5910 5911 @Override 5912 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5913 if (DISABLE_EPHEMERAL_APPS) { 5914 return null; 5915 } 5916 5917 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5918 "getCookie"); 5919 if (!isCallerSameApp(packageName)) { 5920 return null; 5921 } 5922 synchronized (mPackages) { 5923 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5924 packageName, userId); 5925 } 5926 } 5927 5928 @Override 5929 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5930 if (DISABLE_EPHEMERAL_APPS) { 5931 return true; 5932 } 5933 5934 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5935 "setCookie"); 5936 if (!isCallerSameApp(packageName)) { 5937 return false; 5938 } 5939 synchronized (mPackages) { 5940 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5941 packageName, cookie, userId); 5942 } 5943 } 5944 5945 @Override 5946 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5947 if (DISABLE_EPHEMERAL_APPS) { 5948 return null; 5949 } 5950 5951 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5952 "getEphemeralApplicationIcon"); 5953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5954 "getEphemeralApplicationIcon"); 5955 synchronized (mPackages) { 5956 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5957 packageName, userId); 5958 } 5959 } 5960 5961 private boolean isCallerSameApp(String packageName) { 5962 PackageParser.Package pkg = mPackages.get(packageName); 5963 return pkg != null 5964 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 5965 } 5966 5967 public List<ApplicationInfo> getPersistentApplications(int flags) { 5968 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 5969 5970 // reader 5971 synchronized (mPackages) { 5972 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 5973 final int userId = UserHandle.getCallingUserId(); 5974 while (i.hasNext()) { 5975 final PackageParser.Package p = i.next(); 5976 if (p.applicationInfo != null 5977 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 5978 && (!mSafeMode || isSystemApp(p))) { 5979 PackageSetting ps = mSettings.mPackages.get(p.packageName); 5980 if (ps != null) { 5981 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5982 ps.readUserState(userId), userId); 5983 if (ai != null) { 5984 finalList.add(ai); 5985 } 5986 } 5987 } 5988 } 5989 } 5990 5991 return finalList; 5992 } 5993 5994 @Override 5995 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5996 if (!sUserManager.exists(userId)) return null; 5997 flags = updateFlagsForComponent(flags, userId, name); 5998 // reader 5999 synchronized (mPackages) { 6000 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6001 PackageSetting ps = provider != null 6002 ? mSettings.mPackages.get(provider.owner.packageName) 6003 : null; 6004 return ps != null 6005 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6006 ? PackageParser.generateProviderInfo(provider, flags, 6007 ps.readUserState(userId), userId) 6008 : null; 6009 } 6010 } 6011 6012 /** 6013 * @deprecated 6014 */ 6015 @Deprecated 6016 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6017 // reader 6018 synchronized (mPackages) { 6019 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6020 .entrySet().iterator(); 6021 final int userId = UserHandle.getCallingUserId(); 6022 while (i.hasNext()) { 6023 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6024 PackageParser.Provider p = entry.getValue(); 6025 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6026 6027 if (ps != null && p.syncable 6028 && (!mSafeMode || (p.info.applicationInfo.flags 6029 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6030 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6031 ps.readUserState(userId), userId); 6032 if (info != null) { 6033 outNames.add(entry.getKey()); 6034 outInfo.add(info); 6035 } 6036 } 6037 } 6038 } 6039 } 6040 6041 @Override 6042 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6043 int uid, int flags) { 6044 final int userId = processName != null ? UserHandle.getUserId(uid) 6045 : UserHandle.getCallingUserId(); 6046 if (!sUserManager.exists(userId)) return null; 6047 flags = updateFlagsForComponent(flags, userId, processName); 6048 6049 ArrayList<ProviderInfo> finalList = null; 6050 // reader 6051 synchronized (mPackages) { 6052 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6053 while (i.hasNext()) { 6054 final PackageParser.Provider p = i.next(); 6055 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6056 if (ps != null && p.info.authority != null 6057 && (processName == null 6058 || (p.info.processName.equals(processName) 6059 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6060 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6061 if (finalList == null) { 6062 finalList = new ArrayList<ProviderInfo>(3); 6063 } 6064 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6065 ps.readUserState(userId), userId); 6066 if (info != null) { 6067 finalList.add(info); 6068 } 6069 } 6070 } 6071 } 6072 6073 if (finalList != null) { 6074 Collections.sort(finalList, mProviderInitOrderSorter); 6075 return new ParceledListSlice<ProviderInfo>(finalList); 6076 } 6077 6078 return null; 6079 } 6080 6081 @Override 6082 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6083 // reader 6084 synchronized (mPackages) { 6085 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6086 return PackageParser.generateInstrumentationInfo(i, flags); 6087 } 6088 } 6089 6090 @Override 6091 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6092 int flags) { 6093 ArrayList<InstrumentationInfo> finalList = 6094 new ArrayList<InstrumentationInfo>(); 6095 6096 // reader 6097 synchronized (mPackages) { 6098 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6099 while (i.hasNext()) { 6100 final PackageParser.Instrumentation p = i.next(); 6101 if (targetPackage == null 6102 || targetPackage.equals(p.info.targetPackage)) { 6103 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6104 flags); 6105 if (ii != null) { 6106 finalList.add(ii); 6107 } 6108 } 6109 } 6110 } 6111 6112 return finalList; 6113 } 6114 6115 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6116 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6117 if (overlays == null) { 6118 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6119 return; 6120 } 6121 for (PackageParser.Package opkg : overlays.values()) { 6122 // Not much to do if idmap fails: we already logged the error 6123 // and we certainly don't want to abort installation of pkg simply 6124 // because an overlay didn't fit properly. For these reasons, 6125 // ignore the return value of createIdmapForPackagePairLI. 6126 createIdmapForPackagePairLI(pkg, opkg); 6127 } 6128 } 6129 6130 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6131 PackageParser.Package opkg) { 6132 if (!opkg.mTrustedOverlay) { 6133 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6134 opkg.baseCodePath + ": overlay not trusted"); 6135 return false; 6136 } 6137 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6138 if (overlaySet == null) { 6139 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6140 opkg.baseCodePath + " but target package has no known overlays"); 6141 return false; 6142 } 6143 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6144 // TODO: generate idmap for split APKs 6145 try { 6146 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6147 } catch (InstallerException e) { 6148 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6149 + opkg.baseCodePath); 6150 return false; 6151 } 6152 PackageParser.Package[] overlayArray = 6153 overlaySet.values().toArray(new PackageParser.Package[0]); 6154 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6155 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6156 return p1.mOverlayPriority - p2.mOverlayPriority; 6157 } 6158 }; 6159 Arrays.sort(overlayArray, cmp); 6160 6161 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6162 int i = 0; 6163 for (PackageParser.Package p : overlayArray) { 6164 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6165 } 6166 return true; 6167 } 6168 6169 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6170 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6171 try { 6172 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6173 } finally { 6174 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6175 } 6176 } 6177 6178 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6179 final File[] files = dir.listFiles(); 6180 if (ArrayUtils.isEmpty(files)) { 6181 Log.d(TAG, "No files in app dir " + dir); 6182 return; 6183 } 6184 6185 if (DEBUG_PACKAGE_SCANNING) { 6186 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6187 + " flags=0x" + Integer.toHexString(parseFlags)); 6188 } 6189 6190 for (File file : files) { 6191 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6192 && !PackageInstallerService.isStageName(file.getName()); 6193 if (!isPackage) { 6194 // Ignore entries which are not packages 6195 continue; 6196 } 6197 try { 6198 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6199 scanFlags, currentTime, null); 6200 } catch (PackageManagerException e) { 6201 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6202 6203 // Delete invalid userdata apps 6204 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6205 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6206 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6207 removeCodePathLI(file); 6208 } 6209 } 6210 } 6211 } 6212 6213 private static File getSettingsProblemFile() { 6214 File dataDir = Environment.getDataDirectory(); 6215 File systemDir = new File(dataDir, "system"); 6216 File fname = new File(systemDir, "uiderrors.txt"); 6217 return fname; 6218 } 6219 6220 static void reportSettingsProblem(int priority, String msg) { 6221 logCriticalInfo(priority, msg); 6222 } 6223 6224 static void logCriticalInfo(int priority, String msg) { 6225 Slog.println(priority, TAG, msg); 6226 EventLogTags.writePmCriticalInfo(msg); 6227 try { 6228 File fname = getSettingsProblemFile(); 6229 FileOutputStream out = new FileOutputStream(fname, true); 6230 PrintWriter pw = new FastPrintWriter(out); 6231 SimpleDateFormat formatter = new SimpleDateFormat(); 6232 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6233 pw.println(dateString + ": " + msg); 6234 pw.close(); 6235 FileUtils.setPermissions( 6236 fname.toString(), 6237 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6238 -1, -1); 6239 } catch (java.io.IOException e) { 6240 } 6241 } 6242 6243 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 6244 PackageParser.Package pkg, File srcFile, int parseFlags) 6245 throws PackageManagerException { 6246 if (ps != null 6247 && ps.codePath.equals(srcFile) 6248 && ps.timeStamp == srcFile.lastModified() 6249 && !isCompatSignatureUpdateNeeded(pkg) 6250 && !isRecoverSignatureUpdateNeeded(pkg)) { 6251 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6252 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6253 ArraySet<PublicKey> signingKs; 6254 synchronized (mPackages) { 6255 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6256 } 6257 if (ps.signatures.mSignatures != null 6258 && ps.signatures.mSignatures.length != 0 6259 && signingKs != null) { 6260 // Optimization: reuse the existing cached certificates 6261 // if the package appears to be unchanged. 6262 pkg.mSignatures = ps.signatures.mSignatures; 6263 pkg.mSigningKeys = signingKs; 6264 return; 6265 } 6266 6267 Slog.w(TAG, "PackageSetting for " + ps.name 6268 + " is missing signatures. Collecting certs again to recover them."); 6269 } else { 6270 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6271 } 6272 6273 try { 6274 pp.collectCertificates(pkg, parseFlags); 6275 } catch (PackageParserException e) { 6276 throw PackageManagerException.from(e); 6277 } 6278 } 6279 6280 /** 6281 * Traces a package scan. 6282 * @see #scanPackageLI(File, int, int, long, UserHandle) 6283 */ 6284 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6285 long currentTime, UserHandle user) throws PackageManagerException { 6286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6287 try { 6288 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6289 } finally { 6290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6291 } 6292 } 6293 6294 /** 6295 * Scans a package and returns the newly parsed package. 6296 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6297 */ 6298 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6299 long currentTime, UserHandle user) throws PackageManagerException { 6300 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6301 parseFlags |= mDefParseFlags; 6302 PackageParser pp = new PackageParser(); 6303 pp.setSeparateProcesses(mSeparateProcesses); 6304 pp.setOnlyCoreApps(mOnlyCore); 6305 pp.setDisplayMetrics(mMetrics); 6306 6307 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6308 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6309 } 6310 6311 final PackageParser.Package pkg; 6312 try { 6313 pkg = pp.parsePackage(scanFile, parseFlags); 6314 } catch (PackageParserException e) { 6315 throw PackageManagerException.from(e); 6316 } 6317 6318 PackageSetting ps = null; 6319 PackageSetting updatedPkg; 6320 // reader 6321 synchronized (mPackages) { 6322 // Look to see if we already know about this package. 6323 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6324 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6325 // This package has been renamed to its original name. Let's 6326 // use that. 6327 ps = mSettings.peekPackageLPr(oldName); 6328 } 6329 // If there was no original package, see one for the real package name. 6330 if (ps == null) { 6331 ps = mSettings.peekPackageLPr(pkg.packageName); 6332 } 6333 // Check to see if this package could be hiding/updating a system 6334 // package. Must look for it either under the original or real 6335 // package name depending on our state. 6336 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6337 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6338 } 6339 boolean updatedPkgBetter = false; 6340 // First check if this is a system package that may involve an update 6341 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6342 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6343 // it needs to drop FLAG_PRIVILEGED. 6344 if (locationIsPrivileged(scanFile)) { 6345 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6346 } else { 6347 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6348 } 6349 6350 if (ps != null && !ps.codePath.equals(scanFile)) { 6351 // The path has changed from what was last scanned... check the 6352 // version of the new path against what we have stored to determine 6353 // what to do. 6354 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6355 if (pkg.mVersionCode <= ps.versionCode) { 6356 // The system package has been updated and the code path does not match 6357 // Ignore entry. Skip it. 6358 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6359 + " ignored: updated version " + ps.versionCode 6360 + " better than this " + pkg.mVersionCode); 6361 if (!updatedPkg.codePath.equals(scanFile)) { 6362 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6363 + ps.name + " changing from " + updatedPkg.codePathString 6364 + " to " + scanFile); 6365 updatedPkg.codePath = scanFile; 6366 updatedPkg.codePathString = scanFile.toString(); 6367 updatedPkg.resourcePath = scanFile; 6368 updatedPkg.resourcePathString = scanFile.toString(); 6369 } 6370 updatedPkg.pkg = pkg; 6371 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6372 "Package " + ps.name + " at " + scanFile 6373 + " ignored: updated version " + ps.versionCode 6374 + " better than this " + pkg.mVersionCode); 6375 } else { 6376 // The current app on the system partition is better than 6377 // what we have updated to on the data partition; switch 6378 // back to the system partition version. 6379 // At this point, its safely assumed that package installation for 6380 // apps in system partition will go through. If not there won't be a working 6381 // version of the app 6382 // writer 6383 synchronized (mPackages) { 6384 // Just remove the loaded entries from package lists. 6385 mPackages.remove(ps.name); 6386 } 6387 6388 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6389 + " reverting from " + ps.codePathString 6390 + ": new version " + pkg.mVersionCode 6391 + " better than installed " + ps.versionCode); 6392 6393 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6394 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6395 synchronized (mInstallLock) { 6396 args.cleanUpResourcesLI(); 6397 } 6398 synchronized (mPackages) { 6399 mSettings.enableSystemPackageLPw(ps.name); 6400 } 6401 updatedPkgBetter = true; 6402 } 6403 } 6404 } 6405 6406 if (updatedPkg != null) { 6407 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6408 // initially 6409 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6410 6411 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6412 // flag set initially 6413 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6414 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6415 } 6416 } 6417 6418 // Verify certificates against what was last scanned 6419 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 6420 6421 /* 6422 * A new system app appeared, but we already had a non-system one of the 6423 * same name installed earlier. 6424 */ 6425 boolean shouldHideSystemApp = false; 6426 if (updatedPkg == null && ps != null 6427 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6428 /* 6429 * Check to make sure the signatures match first. If they don't, 6430 * wipe the installed application and its data. 6431 */ 6432 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6433 != PackageManager.SIGNATURE_MATCH) { 6434 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6435 + " signatures don't match existing userdata copy; removing"); 6436 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 6437 ps = null; 6438 } else { 6439 /* 6440 * If the newly-added system app is an older version than the 6441 * already installed version, hide it. It will be scanned later 6442 * and re-added like an update. 6443 */ 6444 if (pkg.mVersionCode <= ps.versionCode) { 6445 shouldHideSystemApp = true; 6446 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6447 + " but new version " + pkg.mVersionCode + " better than installed " 6448 + ps.versionCode + "; hiding system"); 6449 } else { 6450 /* 6451 * The newly found system app is a newer version that the 6452 * one previously installed. Simply remove the 6453 * already-installed application and replace it with our own 6454 * while keeping the application data. 6455 */ 6456 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6457 + " reverting from " + ps.codePathString + ": new version " 6458 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6459 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6460 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6461 synchronized (mInstallLock) { 6462 args.cleanUpResourcesLI(); 6463 } 6464 } 6465 } 6466 } 6467 6468 // The apk is forward locked (not public) if its code and resources 6469 // are kept in different files. (except for app in either system or 6470 // vendor path). 6471 // TODO grab this value from PackageSettings 6472 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6473 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6474 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6475 } 6476 } 6477 6478 // TODO: extend to support forward-locked splits 6479 String resourcePath = null; 6480 String baseResourcePath = null; 6481 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6482 if (ps != null && ps.resourcePathString != null) { 6483 resourcePath = ps.resourcePathString; 6484 baseResourcePath = ps.resourcePathString; 6485 } else { 6486 // Should not happen at all. Just log an error. 6487 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6488 } 6489 } else { 6490 resourcePath = pkg.codePath; 6491 baseResourcePath = pkg.baseCodePath; 6492 } 6493 6494 // Set application objects path explicitly. 6495 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 6496 pkg.applicationInfo.setCodePath(pkg.codePath); 6497 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 6498 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 6499 pkg.applicationInfo.setResourcePath(resourcePath); 6500 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 6501 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 6502 6503 // Note that we invoke the following method only if we are about to unpack an application 6504 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6505 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6506 6507 /* 6508 * If the system app should be overridden by a previously installed 6509 * data, hide the system app now and let the /data/app scan pick it up 6510 * again. 6511 */ 6512 if (shouldHideSystemApp) { 6513 synchronized (mPackages) { 6514 mSettings.disableSystemPackageLPw(pkg.packageName); 6515 } 6516 } 6517 6518 return scannedPkg; 6519 } 6520 6521 private static String fixProcessName(String defProcessName, 6522 String processName, int uid) { 6523 if (processName == null) { 6524 return defProcessName; 6525 } 6526 return processName; 6527 } 6528 6529 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6530 throws PackageManagerException { 6531 if (pkgSetting.signatures.mSignatures != null) { 6532 // Already existing package. Make sure signatures match 6533 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6534 == PackageManager.SIGNATURE_MATCH; 6535 if (!match) { 6536 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6537 == PackageManager.SIGNATURE_MATCH; 6538 } 6539 if (!match) { 6540 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6541 == PackageManager.SIGNATURE_MATCH; 6542 } 6543 if (!match) { 6544 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6545 + pkg.packageName + " signatures do not match the " 6546 + "previously installed version; ignoring!"); 6547 } 6548 } 6549 6550 // Check for shared user signatures 6551 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6552 // Already existing package. Make sure signatures match 6553 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6554 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6555 if (!match) { 6556 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6557 == PackageManager.SIGNATURE_MATCH; 6558 } 6559 if (!match) { 6560 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6561 == PackageManager.SIGNATURE_MATCH; 6562 } 6563 if (!match) { 6564 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6565 "Package " + pkg.packageName 6566 + " has no signatures that match those in shared user " 6567 + pkgSetting.sharedUser.name + "; ignoring!"); 6568 } 6569 } 6570 } 6571 6572 /** 6573 * Enforces that only the system UID or root's UID can call a method exposed 6574 * via Binder. 6575 * 6576 * @param message used as message if SecurityException is thrown 6577 * @throws SecurityException if the caller is not system or root 6578 */ 6579 private static final void enforceSystemOrRoot(String message) { 6580 final int uid = Binder.getCallingUid(); 6581 if (uid != Process.SYSTEM_UID && uid != 0) { 6582 throw new SecurityException(message); 6583 } 6584 } 6585 6586 @Override 6587 public void performFstrimIfNeeded() { 6588 enforceSystemOrRoot("Only the system can request fstrim"); 6589 6590 // Before everything else, see whether we need to fstrim. 6591 try { 6592 IMountService ms = PackageHelper.getMountService(); 6593 if (ms != null) { 6594 final boolean isUpgrade = isUpgrade(); 6595 boolean doTrim = isUpgrade; 6596 if (doTrim) { 6597 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6598 } else { 6599 final long interval = android.provider.Settings.Global.getLong( 6600 mContext.getContentResolver(), 6601 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6602 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6603 if (interval > 0) { 6604 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6605 if (timeSinceLast > interval) { 6606 doTrim = true; 6607 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6608 + "; running immediately"); 6609 } 6610 } 6611 } 6612 if (doTrim) { 6613 if (!isFirstBoot()) { 6614 try { 6615 ActivityManagerNative.getDefault().showBootMessage( 6616 mContext.getResources().getString( 6617 R.string.android_upgrading_fstrim), true); 6618 } catch (RemoteException e) { 6619 } 6620 } 6621 ms.runMaintenance(); 6622 } 6623 } else { 6624 Slog.e(TAG, "Mount service unavailable!"); 6625 } 6626 } catch (RemoteException e) { 6627 // Can't happen; MountService is local 6628 } 6629 } 6630 6631 @Override 6632 public void extractPackagesIfNeeded() { 6633 enforceSystemOrRoot("Only the system can request package extraction"); 6634 6635 // Extract pacakges only if profile-guided compilation is enabled because 6636 // otherwise BackgroundDexOptService will not dexopt them later. 6637 if (mUseJitProfiles) { 6638 ArraySet<String> pkgs = getOptimizablePackages(); 6639 if (pkgs != null) { 6640 for (String pkg : pkgs) { 6641 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6642 true /* extractOnly */, false /* force */); 6643 } 6644 } 6645 } 6646 } 6647 6648 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6649 List<ResolveInfo> ris = null; 6650 try { 6651 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6652 intent, null, 0, userId); 6653 } catch (RemoteException e) { 6654 } 6655 ArraySet<String> pkgNames = new ArraySet<String>(); 6656 if (ris != null) { 6657 for (ResolveInfo ri : ris) { 6658 pkgNames.add(ri.activityInfo.packageName); 6659 } 6660 } 6661 return pkgNames; 6662 } 6663 6664 @Override 6665 public void notifyPackageUse(String packageName) { 6666 synchronized (mPackages) { 6667 PackageParser.Package p = mPackages.get(packageName); 6668 if (p == null) { 6669 return; 6670 } 6671 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6672 } 6673 } 6674 6675 // TODO: this is not used nor needed. Delete it. 6676 @Override 6677 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6678 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6679 false /* extractOnly */, false /* force */); 6680 } 6681 6682 @Override 6683 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6684 boolean extractOnly, boolean force) { 6685 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6686 } 6687 6688 private boolean performDexOptTraced(String packageName, String instructionSet, 6689 boolean useProfiles, boolean extractOnly, boolean force) { 6690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6691 try { 6692 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6693 force); 6694 } finally { 6695 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6696 } 6697 } 6698 6699 private boolean performDexOptInternal(String packageName, String instructionSet, 6700 boolean useProfiles, boolean extractOnly, boolean force) { 6701 PackageParser.Package p; 6702 final String targetInstructionSet; 6703 synchronized (mPackages) { 6704 p = mPackages.get(packageName); 6705 if (p == null) { 6706 return false; 6707 } 6708 mPackageUsage.write(false); 6709 6710 targetInstructionSet = instructionSet != null ? instructionSet : 6711 getPrimaryInstructionSet(p.applicationInfo); 6712 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6713 // Skip only if we do not use profiles since they might trigger a recompilation. 6714 return false; 6715 } 6716 } 6717 long callingId = Binder.clearCallingIdentity(); 6718 try { 6719 synchronized (mInstallLock) { 6720 final String[] instructionSets = new String[] { targetInstructionSet }; 6721 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 6722 true /* inclDependencies */, useProfiles, extractOnly, force); 6723 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6724 } 6725 } finally { 6726 Binder.restoreCallingIdentity(callingId); 6727 } 6728 } 6729 6730 public ArraySet<String> getOptimizablePackages() { 6731 ArraySet<String> pkgs = new ArraySet<String>(); 6732 synchronized (mPackages) { 6733 for (PackageParser.Package p : mPackages.values()) { 6734 if (PackageDexOptimizer.canOptimizePackage(p)) { 6735 pkgs.add(p.packageName); 6736 } 6737 } 6738 } 6739 return pkgs; 6740 } 6741 6742 public void shutdown() { 6743 mPackageUsage.write(true); 6744 } 6745 6746 @Override 6747 public void forceDexOpt(String packageName) { 6748 enforceSystemOrRoot("forceDexOpt"); 6749 6750 PackageParser.Package pkg; 6751 synchronized (mPackages) { 6752 pkg = mPackages.get(packageName); 6753 if (pkg == null) { 6754 throw new IllegalArgumentException("Unknown package: " + packageName); 6755 } 6756 } 6757 6758 synchronized (mInstallLock) { 6759 final String[] instructionSets = new String[] { 6760 getPrimaryInstructionSet(pkg.applicationInfo) }; 6761 6762 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6763 6764 // Whoever is calling forceDexOpt wants a fully compiled package. 6765 // Don't use profiles since that may cause compilation to be skipped. 6766 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 6767 true /* inclDependencies */, false /* useProfiles */, 6768 false /* extractOnly */, true /* force */); 6769 6770 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6771 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6772 throw new IllegalStateException("Failed to dexopt: " + res); 6773 } 6774 } 6775 } 6776 6777 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6778 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6779 Slog.w(TAG, "Unable to update from " + oldPkg.name 6780 + " to " + newPkg.packageName 6781 + ": old package not in system partition"); 6782 return false; 6783 } else if (mPackages.get(oldPkg.name) != null) { 6784 Slog.w(TAG, "Unable to update from " + oldPkg.name 6785 + " to " + newPkg.packageName 6786 + ": old package still exists"); 6787 return false; 6788 } 6789 return true; 6790 } 6791 6792 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6793 // TODO: triage flags as part of 26466827 6794 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6795 6796 boolean res = true; 6797 final int[] users = sUserManager.getUserIds(); 6798 for (int user : users) { 6799 try { 6800 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 6801 } catch (InstallerException e) { 6802 Slog.w(TAG, "Failed to delete data directory", e); 6803 res = false; 6804 } 6805 } 6806 return res; 6807 } 6808 6809 void removeCodePathLI(File codePath) { 6810 if (codePath.isDirectory()) { 6811 try { 6812 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 6813 } catch (InstallerException e) { 6814 Slog.w(TAG, "Failed to remove code path", e); 6815 } 6816 } else { 6817 codePath.delete(); 6818 } 6819 } 6820 6821 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 6822 try { 6823 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 6824 } catch (InstallerException e) { 6825 Slog.w(TAG, "Failed to destroy app data", e); 6826 } 6827 } 6828 6829 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 6830 int appId, String seinfo) { 6831 try { 6832 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 6833 } catch (InstallerException e) { 6834 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 6835 } 6836 } 6837 6838 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 6839 // TODO: triage flags as part of 26466827 6840 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 6841 6842 final int[] users = sUserManager.getUserIds(); 6843 for (int user : users) { 6844 try { 6845 mInstaller.clearAppData(volumeUuid, packageName, user, 6846 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 6847 } catch (InstallerException e) { 6848 Slog.w(TAG, "Failed to delete code cache directory", e); 6849 } 6850 } 6851 } 6852 6853 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 6854 PackageParser.Package changingLib) { 6855 if (file.path != null) { 6856 usesLibraryFiles.add(file.path); 6857 return; 6858 } 6859 PackageParser.Package p = mPackages.get(file.apk); 6860 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 6861 // If we are doing this while in the middle of updating a library apk, 6862 // then we need to make sure to use that new apk for determining the 6863 // dependencies here. (We haven't yet finished committing the new apk 6864 // to the package manager state.) 6865 if (p == null || p.packageName.equals(changingLib.packageName)) { 6866 p = changingLib; 6867 } 6868 } 6869 if (p != null) { 6870 usesLibraryFiles.addAll(p.getAllCodePaths()); 6871 } 6872 } 6873 6874 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 6875 PackageParser.Package changingLib) throws PackageManagerException { 6876 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 6877 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 6878 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 6879 for (int i=0; i<N; i++) { 6880 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 6881 if (file == null) { 6882 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 6883 "Package " + pkg.packageName + " requires unavailable shared library " 6884 + pkg.usesLibraries.get(i) + "; failing!"); 6885 } 6886 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6887 } 6888 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 6889 for (int i=0; i<N; i++) { 6890 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 6891 if (file == null) { 6892 Slog.w(TAG, "Package " + pkg.packageName 6893 + " desires unavailable shared library " 6894 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 6895 } else { 6896 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 6897 } 6898 } 6899 N = usesLibraryFiles.size(); 6900 if (N > 0) { 6901 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 6902 } else { 6903 pkg.usesLibraryFiles = null; 6904 } 6905 } 6906 } 6907 6908 private static boolean hasString(List<String> list, List<String> which) { 6909 if (list == null) { 6910 return false; 6911 } 6912 for (int i=list.size()-1; i>=0; i--) { 6913 for (int j=which.size()-1; j>=0; j--) { 6914 if (which.get(j).equals(list.get(i))) { 6915 return true; 6916 } 6917 } 6918 } 6919 return false; 6920 } 6921 6922 private void updateAllSharedLibrariesLPw() { 6923 for (PackageParser.Package pkg : mPackages.values()) { 6924 try { 6925 updateSharedLibrariesLPw(pkg, null); 6926 } catch (PackageManagerException e) { 6927 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6928 } 6929 } 6930 } 6931 6932 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6933 PackageParser.Package changingPkg) { 6934 ArrayList<PackageParser.Package> res = null; 6935 for (PackageParser.Package pkg : mPackages.values()) { 6936 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6937 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6938 if (res == null) { 6939 res = new ArrayList<PackageParser.Package>(); 6940 } 6941 res.add(pkg); 6942 try { 6943 updateSharedLibrariesLPw(pkg, changingPkg); 6944 } catch (PackageManagerException e) { 6945 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6946 } 6947 } 6948 } 6949 return res; 6950 } 6951 6952 /** 6953 * Derive the value of the {@code cpuAbiOverride} based on the provided 6954 * value and an optional stored value from the package settings. 6955 */ 6956 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6957 String cpuAbiOverride = null; 6958 6959 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6960 cpuAbiOverride = null; 6961 } else if (abiOverride != null) { 6962 cpuAbiOverride = abiOverride; 6963 } else if (settings != null) { 6964 cpuAbiOverride = settings.cpuAbiOverrideString; 6965 } 6966 6967 return cpuAbiOverride; 6968 } 6969 6970 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 6971 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6972 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6973 try { 6974 return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 6975 } finally { 6976 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6977 } 6978 } 6979 6980 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6981 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6982 boolean success = false; 6983 try { 6984 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6985 currentTime, user); 6986 success = true; 6987 return res; 6988 } finally { 6989 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6990 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6991 } 6992 } 6993 } 6994 6995 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6996 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6997 final File scanFile = new File(pkg.codePath); 6998 if (pkg.applicationInfo.getCodePath() == null || 6999 pkg.applicationInfo.getResourcePath() == null) { 7000 // Bail out. The resource and code paths haven't been set. 7001 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7002 "Code and resource paths haven't been set correctly"); 7003 } 7004 7005 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7006 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7007 } else { 7008 // Only allow system apps to be flagged as core apps. 7009 pkg.coreApp = false; 7010 } 7011 7012 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7013 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7014 } 7015 7016 if (mCustomResolverComponentName != null && 7017 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7018 setUpCustomResolverActivity(pkg); 7019 } 7020 7021 if (pkg.packageName.equals("android")) { 7022 synchronized (mPackages) { 7023 if (mAndroidApplication != null) { 7024 Slog.w(TAG, "*************************************************"); 7025 Slog.w(TAG, "Core android package being redefined. Skipping."); 7026 Slog.w(TAG, " file=" + scanFile); 7027 Slog.w(TAG, "*************************************************"); 7028 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7029 "Core android package being redefined. Skipping."); 7030 } 7031 7032 // Set up information for our fall-back user intent resolution activity. 7033 mPlatformPackage = pkg; 7034 pkg.mVersionCode = mSdkVersion; 7035 mAndroidApplication = pkg.applicationInfo; 7036 7037 if (!mResolverReplaced) { 7038 mResolveActivity.applicationInfo = mAndroidApplication; 7039 mResolveActivity.name = ResolverActivity.class.getName(); 7040 mResolveActivity.packageName = mAndroidApplication.packageName; 7041 mResolveActivity.processName = "system:ui"; 7042 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7043 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7044 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7045 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7046 mResolveActivity.exported = true; 7047 mResolveActivity.enabled = true; 7048 mResolveInfo.activityInfo = mResolveActivity; 7049 mResolveInfo.priority = 0; 7050 mResolveInfo.preferredOrder = 0; 7051 mResolveInfo.match = 0; 7052 mResolveComponentName = new ComponentName( 7053 mAndroidApplication.packageName, mResolveActivity.name); 7054 } 7055 } 7056 } 7057 7058 if (DEBUG_PACKAGE_SCANNING) { 7059 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7060 Log.d(TAG, "Scanning package " + pkg.packageName); 7061 } 7062 7063 if (mPackages.containsKey(pkg.packageName) 7064 || mSharedLibraries.containsKey(pkg.packageName)) { 7065 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7066 "Application package " + pkg.packageName 7067 + " already installed. Skipping duplicate."); 7068 } 7069 7070 // If we're only installing presumed-existing packages, require that the 7071 // scanned APK is both already known and at the path previously established 7072 // for it. Previously unknown packages we pick up normally, but if we have an 7073 // a priori expectation about this package's install presence, enforce it. 7074 // With a singular exception for new system packages. When an OTA contains 7075 // a new system package, we allow the codepath to change from a system location 7076 // to the user-installed location. If we don't allow this change, any newer, 7077 // user-installed version of the application will be ignored. 7078 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7079 if (mExpectingBetter.containsKey(pkg.packageName)) { 7080 logCriticalInfo(Log.WARN, 7081 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7082 } else { 7083 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7084 if (known != null) { 7085 if (DEBUG_PACKAGE_SCANNING) { 7086 Log.d(TAG, "Examining " + pkg.codePath 7087 + " and requiring known paths " + known.codePathString 7088 + " & " + known.resourcePathString); 7089 } 7090 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7091 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 7092 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7093 "Application package " + pkg.packageName 7094 + " found at " + pkg.applicationInfo.getCodePath() 7095 + " but expected at " + known.codePathString + "; ignoring."); 7096 } 7097 } 7098 } 7099 } 7100 7101 // Initialize package source and resource directories 7102 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7103 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7104 7105 SharedUserSetting suid = null; 7106 PackageSetting pkgSetting = null; 7107 7108 if (!isSystemApp(pkg)) { 7109 // Only system apps can use these features. 7110 pkg.mOriginalPackages = null; 7111 pkg.mRealPackage = null; 7112 pkg.mAdoptPermissions = null; 7113 } 7114 7115 // writer 7116 synchronized (mPackages) { 7117 if (pkg.mSharedUserId != null) { 7118 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7119 if (suid == null) { 7120 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7121 "Creating application package " + pkg.packageName 7122 + " for shared user failed"); 7123 } 7124 if (DEBUG_PACKAGE_SCANNING) { 7125 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7126 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7127 + "): packages=" + suid.packages); 7128 } 7129 } 7130 7131 // Check if we are renaming from an original package name. 7132 PackageSetting origPackage = null; 7133 String realName = null; 7134 if (pkg.mOriginalPackages != null) { 7135 // This package may need to be renamed to a previously 7136 // installed name. Let's check on that... 7137 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7138 if (pkg.mOriginalPackages.contains(renamed)) { 7139 // This package had originally been installed as the 7140 // original name, and we have already taken care of 7141 // transitioning to the new one. Just update the new 7142 // one to continue using the old name. 7143 realName = pkg.mRealPackage; 7144 if (!pkg.packageName.equals(renamed)) { 7145 // Callers into this function may have already taken 7146 // care of renaming the package; only do it here if 7147 // it is not already done. 7148 pkg.setPackageName(renamed); 7149 } 7150 7151 } else { 7152 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7153 if ((origPackage = mSettings.peekPackageLPr( 7154 pkg.mOriginalPackages.get(i))) != null) { 7155 // We do have the package already installed under its 7156 // original name... should we use it? 7157 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7158 // New package is not compatible with original. 7159 origPackage = null; 7160 continue; 7161 } else if (origPackage.sharedUser != null) { 7162 // Make sure uid is compatible between packages. 7163 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7164 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7165 + " to " + pkg.packageName + ": old uid " 7166 + origPackage.sharedUser.name 7167 + " differs from " + pkg.mSharedUserId); 7168 origPackage = null; 7169 continue; 7170 } 7171 } else { 7172 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7173 + pkg.packageName + " to old name " + origPackage.name); 7174 } 7175 break; 7176 } 7177 } 7178 } 7179 } 7180 7181 if (mTransferedPackages.contains(pkg.packageName)) { 7182 Slog.w(TAG, "Package " + pkg.packageName 7183 + " was transferred to another, but its .apk remains"); 7184 } 7185 7186 // Just create the setting, don't add it yet. For already existing packages 7187 // the PkgSetting exists already and doesn't have to be created. 7188 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7189 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7190 pkg.applicationInfo.primaryCpuAbi, 7191 pkg.applicationInfo.secondaryCpuAbi, 7192 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7193 user, false); 7194 if (pkgSetting == null) { 7195 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7196 "Creating application package " + pkg.packageName + " failed"); 7197 } 7198 7199 if (pkgSetting.origPackage != null) { 7200 // If we are first transitioning from an original package, 7201 // fix up the new package's name now. We need to do this after 7202 // looking up the package under its new name, so getPackageLP 7203 // can take care of fiddling things correctly. 7204 pkg.setPackageName(origPackage.name); 7205 7206 // File a report about this. 7207 String msg = "New package " + pkgSetting.realName 7208 + " renamed to replace old package " + pkgSetting.name; 7209 reportSettingsProblem(Log.WARN, msg); 7210 7211 // Make a note of it. 7212 mTransferedPackages.add(origPackage.name); 7213 7214 // No longer need to retain this. 7215 pkgSetting.origPackage = null; 7216 } 7217 7218 if (realName != null) { 7219 // Make a note of it. 7220 mTransferedPackages.add(pkg.packageName); 7221 } 7222 7223 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7224 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7225 } 7226 7227 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7228 // Check all shared libraries and map to their actual file path. 7229 // We only do this here for apps not on a system dir, because those 7230 // are the only ones that can fail an install due to this. We 7231 // will take care of the system apps by updating all of their 7232 // library paths after the scan is done. 7233 updateSharedLibrariesLPw(pkg, null); 7234 } 7235 7236 if (mFoundPolicyFile) { 7237 SELinuxMMAC.assignSeinfoValue(pkg); 7238 } 7239 7240 pkg.applicationInfo.uid = pkgSetting.appId; 7241 pkg.mExtras = pkgSetting; 7242 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7243 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7244 // We just determined the app is signed correctly, so bring 7245 // over the latest parsed certs. 7246 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7247 } else { 7248 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7249 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7250 "Package " + pkg.packageName + " upgrade keys do not match the " 7251 + "previously installed version"); 7252 } else { 7253 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7254 String msg = "System package " + pkg.packageName 7255 + " signature changed; retaining data."; 7256 reportSettingsProblem(Log.WARN, msg); 7257 } 7258 } 7259 } else { 7260 try { 7261 verifySignaturesLP(pkgSetting, pkg); 7262 // We just determined the app is signed correctly, so bring 7263 // over the latest parsed certs. 7264 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7265 } catch (PackageManagerException e) { 7266 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7267 throw e; 7268 } 7269 // The signature has changed, but this package is in the system 7270 // image... let's recover! 7271 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7272 // However... if this package is part of a shared user, but it 7273 // doesn't match the signature of the shared user, let's fail. 7274 // What this means is that you can't change the signatures 7275 // associated with an overall shared user, which doesn't seem all 7276 // that unreasonable. 7277 if (pkgSetting.sharedUser != null) { 7278 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7279 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7280 throw new PackageManagerException( 7281 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7282 "Signature mismatch for shared user: " 7283 + pkgSetting.sharedUser); 7284 } 7285 } 7286 // File a report about this. 7287 String msg = "System package " + pkg.packageName 7288 + " signature changed; retaining data."; 7289 reportSettingsProblem(Log.WARN, msg); 7290 } 7291 } 7292 // Verify that this new package doesn't have any content providers 7293 // that conflict with existing packages. Only do this if the 7294 // package isn't already installed, since we don't want to break 7295 // things that are installed. 7296 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7297 final int N = pkg.providers.size(); 7298 int i; 7299 for (i=0; i<N; i++) { 7300 PackageParser.Provider p = pkg.providers.get(i); 7301 if (p.info.authority != null) { 7302 String names[] = p.info.authority.split(";"); 7303 for (int j = 0; j < names.length; j++) { 7304 if (mProvidersByAuthority.containsKey(names[j])) { 7305 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7306 final String otherPackageName = 7307 ((other != null && other.getComponentName() != null) ? 7308 other.getComponentName().getPackageName() : "?"); 7309 throw new PackageManagerException( 7310 INSTALL_FAILED_CONFLICTING_PROVIDER, 7311 "Can't install because provider name " + names[j] 7312 + " (in package " + pkg.applicationInfo.packageName 7313 + ") is already used by " + otherPackageName); 7314 } 7315 } 7316 } 7317 } 7318 } 7319 7320 if (pkg.mAdoptPermissions != null) { 7321 // This package wants to adopt ownership of permissions from 7322 // another package. 7323 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7324 final String origName = pkg.mAdoptPermissions.get(i); 7325 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7326 if (orig != null) { 7327 if (verifyPackageUpdateLPr(orig, pkg)) { 7328 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7329 + pkg.packageName); 7330 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7331 } 7332 } 7333 } 7334 } 7335 } 7336 7337 final String pkgName = pkg.packageName; 7338 7339 final long scanFileTime = scanFile.lastModified(); 7340 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7341 pkg.applicationInfo.processName = fixProcessName( 7342 pkg.applicationInfo.packageName, 7343 pkg.applicationInfo.processName, 7344 pkg.applicationInfo.uid); 7345 7346 if (pkg != mPlatformPackage) { 7347 // Get all of our default paths setup 7348 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7349 } 7350 7351 final String path = scanFile.getPath(); 7352 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7353 7354 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7355 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7356 7357 // Some system apps still use directory structure for native libraries 7358 // in which case we might end up not detecting abi solely based on apk 7359 // structure. Try to detect abi based on directory structure. 7360 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7361 pkg.applicationInfo.primaryCpuAbi == null) { 7362 setBundledAppAbisAndRoots(pkg, pkgSetting); 7363 setNativeLibraryPaths(pkg); 7364 } 7365 7366 } else { 7367 if ((scanFlags & SCAN_MOVE) != 0) { 7368 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7369 // but we already have this packages package info in the PackageSetting. We just 7370 // use that and derive the native library path based on the new codepath. 7371 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7372 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7373 } 7374 7375 // Set native library paths again. For moves, the path will be updated based on the 7376 // ABIs we've determined above. For non-moves, the path will be updated based on the 7377 // ABIs we determined during compilation, but the path will depend on the final 7378 // package path (after the rename away from the stage path). 7379 setNativeLibraryPaths(pkg); 7380 } 7381 7382 // This is a special case for the "system" package, where the ABI is 7383 // dictated by the zygote configuration (and init.rc). We should keep track 7384 // of this ABI so that we can deal with "normal" applications that run under 7385 // the same UID correctly. 7386 if (mPlatformPackage == pkg) { 7387 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7388 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7389 } 7390 7391 // If there's a mismatch between the abi-override in the package setting 7392 // and the abiOverride specified for the install. Warn about this because we 7393 // would've already compiled the app without taking the package setting into 7394 // account. 7395 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7396 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7397 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7398 " for package " + pkg.packageName); 7399 } 7400 } 7401 7402 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7403 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7404 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7405 7406 // Copy the derived override back to the parsed package, so that we can 7407 // update the package settings accordingly. 7408 pkg.cpuAbiOverride = cpuAbiOverride; 7409 7410 if (DEBUG_ABI_SELECTION) { 7411 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7412 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7413 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7414 } 7415 7416 // Push the derived path down into PackageSettings so we know what to 7417 // clean up at uninstall time. 7418 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7419 7420 if (DEBUG_ABI_SELECTION) { 7421 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7422 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7423 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7424 } 7425 7426 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7427 // We don't do this here during boot because we can do it all 7428 // at once after scanning all existing packages. 7429 // 7430 // We also do this *before* we perform dexopt on this package, so that 7431 // we can avoid redundant dexopts, and also to make sure we've got the 7432 // code and package path correct. 7433 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7434 pkg, true /* boot complete */); 7435 } 7436 7437 if (mFactoryTest && pkg.requestedPermissions.contains( 7438 android.Manifest.permission.FACTORY_TEST)) { 7439 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7440 } 7441 7442 ArrayList<PackageParser.Package> clientLibPkgs = null; 7443 7444 // writer 7445 synchronized (mPackages) { 7446 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7447 // Only system apps can add new shared libraries. 7448 if (pkg.libraryNames != null) { 7449 for (int i=0; i<pkg.libraryNames.size(); i++) { 7450 String name = pkg.libraryNames.get(i); 7451 boolean allowed = false; 7452 if (pkg.isUpdatedSystemApp()) { 7453 // New library entries can only be added through the 7454 // system image. This is important to get rid of a lot 7455 // of nasty edge cases: for example if we allowed a non- 7456 // system update of the app to add a library, then uninstalling 7457 // the update would make the library go away, and assumptions 7458 // we made such as through app install filtering would now 7459 // have allowed apps on the device which aren't compatible 7460 // with it. Better to just have the restriction here, be 7461 // conservative, and create many fewer cases that can negatively 7462 // impact the user experience. 7463 final PackageSetting sysPs = mSettings 7464 .getDisabledSystemPkgLPr(pkg.packageName); 7465 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7466 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7467 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7468 allowed = true; 7469 break; 7470 } 7471 } 7472 } 7473 } else { 7474 allowed = true; 7475 } 7476 if (allowed) { 7477 if (!mSharedLibraries.containsKey(name)) { 7478 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7479 } else if (!name.equals(pkg.packageName)) { 7480 Slog.w(TAG, "Package " + pkg.packageName + " library " 7481 + name + " already exists; skipping"); 7482 } 7483 } else { 7484 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7485 + name + " that is not declared on system image; skipping"); 7486 } 7487 } 7488 if ((scanFlags & SCAN_BOOTING) == 0) { 7489 // If we are not booting, we need to update any applications 7490 // that are clients of our shared library. If we are booting, 7491 // this will all be done once the scan is complete. 7492 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7493 } 7494 } 7495 } 7496 } 7497 7498 // Request the ActivityManager to kill the process(only for existing packages) 7499 // so that we do not end up in a confused state while the user is still using the older 7500 // version of the application while the new one gets installed. 7501 if ((scanFlags & SCAN_REPLACING) != 0) { 7502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7503 7504 killApplication(pkg.applicationInfo.packageName, 7505 pkg.applicationInfo.uid, "replace pkg"); 7506 7507 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7508 } 7509 7510 // Also need to kill any apps that are dependent on the library. 7511 if (clientLibPkgs != null) { 7512 for (int i=0; i<clientLibPkgs.size(); i++) { 7513 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7514 killApplication(clientPkg.applicationInfo.packageName, 7515 clientPkg.applicationInfo.uid, "update lib"); 7516 } 7517 } 7518 7519 // Make sure we're not adding any bogus keyset info 7520 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7521 ksms.assertScannedPackageValid(pkg); 7522 7523 // writer 7524 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7525 7526 boolean createIdmapFailed = false; 7527 synchronized (mPackages) { 7528 // We don't expect installation to fail beyond this point 7529 7530 // Add the new setting to mSettings 7531 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7532 // Add the new setting to mPackages 7533 mPackages.put(pkg.applicationInfo.packageName, pkg); 7534 // Make sure we don't accidentally delete its data. 7535 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7536 while (iter.hasNext()) { 7537 PackageCleanItem item = iter.next(); 7538 if (pkgName.equals(item.packageName)) { 7539 iter.remove(); 7540 } 7541 } 7542 7543 // Take care of first install / last update times. 7544 if (currentTime != 0) { 7545 if (pkgSetting.firstInstallTime == 0) { 7546 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7547 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7548 pkgSetting.lastUpdateTime = currentTime; 7549 } 7550 } else if (pkgSetting.firstInstallTime == 0) { 7551 // We need *something*. Take time time stamp of the file. 7552 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7553 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7554 if (scanFileTime != pkgSetting.timeStamp) { 7555 // A package on the system image has changed; consider this 7556 // to be an update. 7557 pkgSetting.lastUpdateTime = scanFileTime; 7558 } 7559 } 7560 7561 // Add the package's KeySets to the global KeySetManagerService 7562 ksms.addScannedPackageLPw(pkg); 7563 7564 int N = pkg.providers.size(); 7565 StringBuilder r = null; 7566 int i; 7567 for (i=0; i<N; i++) { 7568 PackageParser.Provider p = pkg.providers.get(i); 7569 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7570 p.info.processName, pkg.applicationInfo.uid); 7571 mProviders.addProvider(p); 7572 p.syncable = p.info.isSyncable; 7573 if (p.info.authority != null) { 7574 String names[] = p.info.authority.split(";"); 7575 p.info.authority = null; 7576 for (int j = 0; j < names.length; j++) { 7577 if (j == 1 && p.syncable) { 7578 // We only want the first authority for a provider to possibly be 7579 // syncable, so if we already added this provider using a different 7580 // authority clear the syncable flag. We copy the provider before 7581 // changing it because the mProviders object contains a reference 7582 // to a provider that we don't want to change. 7583 // Only do this for the second authority since the resulting provider 7584 // object can be the same for all future authorities for this provider. 7585 p = new PackageParser.Provider(p); 7586 p.syncable = false; 7587 } 7588 if (!mProvidersByAuthority.containsKey(names[j])) { 7589 mProvidersByAuthority.put(names[j], p); 7590 if (p.info.authority == null) { 7591 p.info.authority = names[j]; 7592 } else { 7593 p.info.authority = p.info.authority + ";" + names[j]; 7594 } 7595 if (DEBUG_PACKAGE_SCANNING) { 7596 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7597 Log.d(TAG, "Registered content provider: " + names[j] 7598 + ", className = " + p.info.name + ", isSyncable = " 7599 + p.info.isSyncable); 7600 } 7601 } else { 7602 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7603 Slog.w(TAG, "Skipping provider name " + names[j] + 7604 " (in package " + pkg.applicationInfo.packageName + 7605 "): name already used by " 7606 + ((other != null && other.getComponentName() != null) 7607 ? other.getComponentName().getPackageName() : "?")); 7608 } 7609 } 7610 } 7611 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7612 if (r == null) { 7613 r = new StringBuilder(256); 7614 } else { 7615 r.append(' '); 7616 } 7617 r.append(p.info.name); 7618 } 7619 } 7620 if (r != null) { 7621 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7622 } 7623 7624 N = pkg.services.size(); 7625 r = null; 7626 for (i=0; i<N; i++) { 7627 PackageParser.Service s = pkg.services.get(i); 7628 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7629 s.info.processName, pkg.applicationInfo.uid); 7630 mServices.addService(s); 7631 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7632 if (r == null) { 7633 r = new StringBuilder(256); 7634 } else { 7635 r.append(' '); 7636 } 7637 r.append(s.info.name); 7638 } 7639 } 7640 if (r != null) { 7641 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7642 } 7643 7644 N = pkg.receivers.size(); 7645 r = null; 7646 for (i=0; i<N; i++) { 7647 PackageParser.Activity a = pkg.receivers.get(i); 7648 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7649 a.info.processName, pkg.applicationInfo.uid); 7650 mReceivers.addActivity(a, "receiver"); 7651 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7652 if (r == null) { 7653 r = new StringBuilder(256); 7654 } else { 7655 r.append(' '); 7656 } 7657 r.append(a.info.name); 7658 } 7659 } 7660 if (r != null) { 7661 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7662 } 7663 7664 N = pkg.activities.size(); 7665 r = null; 7666 for (i=0; i<N; i++) { 7667 PackageParser.Activity a = pkg.activities.get(i); 7668 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7669 a.info.processName, pkg.applicationInfo.uid); 7670 mActivities.addActivity(a, "activity"); 7671 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7672 if (r == null) { 7673 r = new StringBuilder(256); 7674 } else { 7675 r.append(' '); 7676 } 7677 r.append(a.info.name); 7678 } 7679 } 7680 if (r != null) { 7681 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 7682 } 7683 7684 N = pkg.permissionGroups.size(); 7685 r = null; 7686 for (i=0; i<N; i++) { 7687 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 7688 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 7689 if (cur == null) { 7690 mPermissionGroups.put(pg.info.name, pg); 7691 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7692 if (r == null) { 7693 r = new StringBuilder(256); 7694 } else { 7695 r.append(' '); 7696 } 7697 r.append(pg.info.name); 7698 } 7699 } else { 7700 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 7701 + pg.info.packageName + " ignored: original from " 7702 + cur.info.packageName); 7703 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7704 if (r == null) { 7705 r = new StringBuilder(256); 7706 } else { 7707 r.append(' '); 7708 } 7709 r.append("DUP:"); 7710 r.append(pg.info.name); 7711 } 7712 } 7713 } 7714 if (r != null) { 7715 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 7716 } 7717 7718 N = pkg.permissions.size(); 7719 r = null; 7720 for (i=0; i<N; i++) { 7721 PackageParser.Permission p = pkg.permissions.get(i); 7722 7723 // Assume by default that we did not install this permission into the system. 7724 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 7725 7726 // Now that permission groups have a special meaning, we ignore permission 7727 // groups for legacy apps to prevent unexpected behavior. In particular, 7728 // permissions for one app being granted to someone just becuase they happen 7729 // to be in a group defined by another app (before this had no implications). 7730 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 7731 p.group = mPermissionGroups.get(p.info.group); 7732 // Warn for a permission in an unknown group. 7733 if (p.info.group != null && p.group == null) { 7734 Slog.w(TAG, "Permission " + p.info.name + " from package " 7735 + p.info.packageName + " in an unknown group " + p.info.group); 7736 } 7737 } 7738 7739 ArrayMap<String, BasePermission> permissionMap = 7740 p.tree ? mSettings.mPermissionTrees 7741 : mSettings.mPermissions; 7742 BasePermission bp = permissionMap.get(p.info.name); 7743 7744 // Allow system apps to redefine non-system permissions 7745 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 7746 final boolean currentOwnerIsSystem = (bp.perm != null 7747 && isSystemApp(bp.perm.owner)); 7748 if (isSystemApp(p.owner)) { 7749 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 7750 // It's a built-in permission and no owner, take ownership now 7751 bp.packageSetting = pkgSetting; 7752 bp.perm = p; 7753 bp.uid = pkg.applicationInfo.uid; 7754 bp.sourcePackage = p.info.packageName; 7755 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7756 } else if (!currentOwnerIsSystem) { 7757 String msg = "New decl " + p.owner + " of permission " 7758 + p.info.name + " is system; overriding " + bp.sourcePackage; 7759 reportSettingsProblem(Log.WARN, msg); 7760 bp = null; 7761 } 7762 } 7763 } 7764 7765 if (bp == null) { 7766 bp = new BasePermission(p.info.name, p.info.packageName, 7767 BasePermission.TYPE_NORMAL); 7768 permissionMap.put(p.info.name, bp); 7769 } 7770 7771 if (bp.perm == null) { 7772 if (bp.sourcePackage == null 7773 || bp.sourcePackage.equals(p.info.packageName)) { 7774 BasePermission tree = findPermissionTreeLP(p.info.name); 7775 if (tree == null 7776 || tree.sourcePackage.equals(p.info.packageName)) { 7777 bp.packageSetting = pkgSetting; 7778 bp.perm = p; 7779 bp.uid = pkg.applicationInfo.uid; 7780 bp.sourcePackage = p.info.packageName; 7781 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 7782 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7783 if (r == null) { 7784 r = new StringBuilder(256); 7785 } else { 7786 r.append(' '); 7787 } 7788 r.append(p.info.name); 7789 } 7790 } else { 7791 Slog.w(TAG, "Permission " + p.info.name + " from package " 7792 + p.info.packageName + " ignored: base tree " 7793 + tree.name + " is from package " 7794 + tree.sourcePackage); 7795 } 7796 } else { 7797 Slog.w(TAG, "Permission " + p.info.name + " from package " 7798 + p.info.packageName + " ignored: original from " 7799 + bp.sourcePackage); 7800 } 7801 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7802 if (r == null) { 7803 r = new StringBuilder(256); 7804 } else { 7805 r.append(' '); 7806 } 7807 r.append("DUP:"); 7808 r.append(p.info.name); 7809 } 7810 if (bp.perm == p) { 7811 bp.protectionLevel = p.info.protectionLevel; 7812 } 7813 } 7814 7815 if (r != null) { 7816 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7817 } 7818 7819 N = pkg.instrumentation.size(); 7820 r = null; 7821 for (i=0; i<N; i++) { 7822 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7823 a.info.packageName = pkg.applicationInfo.packageName; 7824 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7825 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7826 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7827 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7828 a.info.dataDir = pkg.applicationInfo.dataDir; 7829 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 7830 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 7831 7832 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7833 // need other information about the application, like the ABI and what not ? 7834 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7835 mInstrumentation.put(a.getComponentName(), a); 7836 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7837 if (r == null) { 7838 r = new StringBuilder(256); 7839 } else { 7840 r.append(' '); 7841 } 7842 r.append(a.info.name); 7843 } 7844 } 7845 if (r != null) { 7846 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7847 } 7848 7849 if (pkg.protectedBroadcasts != null) { 7850 N = pkg.protectedBroadcasts.size(); 7851 for (i=0; i<N; i++) { 7852 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7853 } 7854 } 7855 7856 pkgSetting.setTimeStamp(scanFileTime); 7857 7858 // Create idmap files for pairs of (packages, overlay packages). 7859 // Note: "android", ie framework-res.apk, is handled by native layers. 7860 if (pkg.mOverlayTarget != null) { 7861 // This is an overlay package. 7862 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7863 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7864 mOverlays.put(pkg.mOverlayTarget, 7865 new ArrayMap<String, PackageParser.Package>()); 7866 } 7867 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7868 map.put(pkg.packageName, pkg); 7869 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7870 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7871 createIdmapFailed = true; 7872 } 7873 } 7874 } else if (mOverlays.containsKey(pkg.packageName) && 7875 !pkg.packageName.equals("android")) { 7876 // This is a regular package, with one or more known overlay packages. 7877 createIdmapsForPackageLI(pkg); 7878 } 7879 } 7880 7881 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7882 7883 if (createIdmapFailed) { 7884 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7885 "scanPackageLI failed to createIdmap"); 7886 } 7887 return pkg; 7888 } 7889 7890 /** 7891 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7892 * is derived purely on the basis of the contents of {@code scanFile} and 7893 * {@code cpuAbiOverride}. 7894 * 7895 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7896 */ 7897 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7898 String cpuAbiOverride, boolean extractLibs) 7899 throws PackageManagerException { 7900 // TODO: We can probably be smarter about this stuff. For installed apps, 7901 // we can calculate this information at install time once and for all. For 7902 // system apps, we can probably assume that this information doesn't change 7903 // after the first boot scan. As things stand, we do lots of unnecessary work. 7904 7905 // Give ourselves some initial paths; we'll come back for another 7906 // pass once we've determined ABI below. 7907 setNativeLibraryPaths(pkg); 7908 7909 // We would never need to extract libs for forward-locked and external packages, 7910 // since the container service will do it for us. We shouldn't attempt to 7911 // extract libs from system app when it was not updated. 7912 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 7913 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 7914 extractLibs = false; 7915 } 7916 7917 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7918 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7919 7920 NativeLibraryHelper.Handle handle = null; 7921 try { 7922 handle = NativeLibraryHelper.Handle.create(pkg); 7923 // TODO(multiArch): This can be null for apps that didn't go through the 7924 // usual installation process. We can calculate it again, like we 7925 // do during install time. 7926 // 7927 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7928 // unnecessary. 7929 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7930 7931 // Null out the abis so that they can be recalculated. 7932 pkg.applicationInfo.primaryCpuAbi = null; 7933 pkg.applicationInfo.secondaryCpuAbi = null; 7934 if (isMultiArch(pkg.applicationInfo)) { 7935 // Warn if we've set an abiOverride for multi-lib packages.. 7936 // By definition, we need to copy both 32 and 64 bit libraries for 7937 // such packages. 7938 if (pkg.cpuAbiOverride != null 7939 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7940 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7941 } 7942 7943 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7944 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7945 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7946 if (extractLibs) { 7947 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7948 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7949 useIsaSpecificSubdirs); 7950 } else { 7951 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7952 } 7953 } 7954 7955 maybeThrowExceptionForMultiArchCopy( 7956 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7957 7958 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7959 if (extractLibs) { 7960 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7961 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7962 useIsaSpecificSubdirs); 7963 } else { 7964 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7965 } 7966 } 7967 7968 maybeThrowExceptionForMultiArchCopy( 7969 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7970 7971 if (abi64 >= 0) { 7972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7973 } 7974 7975 if (abi32 >= 0) { 7976 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7977 if (abi64 >= 0) { 7978 pkg.applicationInfo.secondaryCpuAbi = abi; 7979 } else { 7980 pkg.applicationInfo.primaryCpuAbi = abi; 7981 } 7982 } 7983 if (cpuAbiOverride != null && 7984 cpuAbiOverride.equals(pkg.applicationInfo.secondaryCpuAbi)) { 7985 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 7986 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7987 } 7988 } else { 7989 String[] abiList = (cpuAbiOverride != null) ? 7990 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7991 7992 // Enable gross and lame hacks for apps that are built with old 7993 // SDK tools. We must scan their APKs for renderscript bitcode and 7994 // not launch them if it's present. Don't bother checking on devices 7995 // that don't have 64 bit support. 7996 boolean needsRenderScriptOverride = false; 7997 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7998 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7999 abiList = Build.SUPPORTED_32_BIT_ABIS; 8000 needsRenderScriptOverride = true; 8001 } 8002 8003 final int copyRet; 8004 if (extractLibs) { 8005 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8006 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8007 } else { 8008 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8009 } 8010 8011 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8012 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8013 "Error unpackaging native libs for app, errorCode=" + copyRet); 8014 } 8015 8016 if (copyRet >= 0) { 8017 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8018 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8019 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8020 } else if (needsRenderScriptOverride) { 8021 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8022 } 8023 } 8024 } catch (IOException ioe) { 8025 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8026 } finally { 8027 IoUtils.closeQuietly(handle); 8028 } 8029 8030 // Now that we've calculated the ABIs and determined if it's an internal app, 8031 // we will go ahead and populate the nativeLibraryPath. 8032 setNativeLibraryPaths(pkg); 8033 } 8034 8035 /** 8036 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8037 * i.e, so that all packages can be run inside a single process if required. 8038 * 8039 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8040 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8041 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8042 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8043 * updating a package that belongs to a shared user. 8044 * 8045 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8046 * adds unnecessary complexity. 8047 */ 8048 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8049 PackageParser.Package scannedPackage, boolean bootComplete) { 8050 String requiredInstructionSet = null; 8051 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8052 requiredInstructionSet = VMRuntime.getInstructionSet( 8053 scannedPackage.applicationInfo.primaryCpuAbi); 8054 } 8055 8056 PackageSetting requirer = null; 8057 for (PackageSetting ps : packagesForUser) { 8058 // If packagesForUser contains scannedPackage, we skip it. This will happen 8059 // when scannedPackage is an update of an existing package. Without this check, 8060 // we will never be able to change the ABI of any package belonging to a shared 8061 // user, even if it's compatible with other packages. 8062 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8063 if (ps.primaryCpuAbiString == null) { 8064 continue; 8065 } 8066 8067 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8068 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8069 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8070 // this but there's not much we can do. 8071 String errorMessage = "Instruction set mismatch, " 8072 + ((requirer == null) ? "[caller]" : requirer) 8073 + " requires " + requiredInstructionSet + " whereas " + ps 8074 + " requires " + instructionSet; 8075 Slog.w(TAG, errorMessage); 8076 } 8077 8078 if (requiredInstructionSet == null) { 8079 requiredInstructionSet = instructionSet; 8080 requirer = ps; 8081 } 8082 } 8083 } 8084 8085 if (requiredInstructionSet != null) { 8086 String adjustedAbi; 8087 if (requirer != null) { 8088 // requirer != null implies that either scannedPackage was null or that scannedPackage 8089 // did not require an ABI, in which case we have to adjust scannedPackage to match 8090 // the ABI of the set (which is the same as requirer's ABI) 8091 adjustedAbi = requirer.primaryCpuAbiString; 8092 if (scannedPackage != null) { 8093 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8094 } 8095 } else { 8096 // requirer == null implies that we're updating all ABIs in the set to 8097 // match scannedPackage. 8098 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8099 } 8100 8101 for (PackageSetting ps : packagesForUser) { 8102 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8103 if (ps.primaryCpuAbiString != null) { 8104 continue; 8105 } 8106 8107 ps.primaryCpuAbiString = adjustedAbi; 8108 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8109 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8110 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8111 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8112 + " (requirer=" 8113 + (requirer == null ? "null" : requirer.pkg.packageName) 8114 + ", scannedPackage=" 8115 + (scannedPackage != null ? scannedPackage.packageName : "null") 8116 + ")"); 8117 try { 8118 mInstaller.rmdex(ps.codePathString, 8119 getDexCodeInstructionSet(getPreferredInstructionSet())); 8120 } catch (InstallerException ignored) { 8121 } 8122 } 8123 } 8124 } 8125 } 8126 } 8127 8128 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8129 synchronized (mPackages) { 8130 mResolverReplaced = true; 8131 // Set up information for custom user intent resolution activity. 8132 mResolveActivity.applicationInfo = pkg.applicationInfo; 8133 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8134 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8135 mResolveActivity.processName = pkg.applicationInfo.packageName; 8136 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8137 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8138 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8139 mResolveActivity.theme = 0; 8140 mResolveActivity.exported = true; 8141 mResolveActivity.enabled = true; 8142 mResolveInfo.activityInfo = mResolveActivity; 8143 mResolveInfo.priority = 0; 8144 mResolveInfo.preferredOrder = 0; 8145 mResolveInfo.match = 0; 8146 mResolveComponentName = mCustomResolverComponentName; 8147 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8148 mResolveComponentName); 8149 } 8150 } 8151 8152 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8153 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8154 8155 // Set up information for ephemeral installer activity 8156 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8157 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8158 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8159 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8160 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8161 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8162 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8163 mEphemeralInstallerActivity.theme = 0; 8164 mEphemeralInstallerActivity.exported = true; 8165 mEphemeralInstallerActivity.enabled = true; 8166 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8167 mEphemeralInstallerInfo.priority = 0; 8168 mEphemeralInstallerInfo.preferredOrder = 0; 8169 mEphemeralInstallerInfo.match = 0; 8170 8171 if (DEBUG_EPHEMERAL) { 8172 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8173 } 8174 } 8175 8176 private static String calculateBundledApkRoot(final String codePathString) { 8177 final File codePath = new File(codePathString); 8178 final File codeRoot; 8179 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8180 codeRoot = Environment.getRootDirectory(); 8181 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8182 codeRoot = Environment.getOemDirectory(); 8183 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8184 codeRoot = Environment.getVendorDirectory(); 8185 } else { 8186 // Unrecognized code path; take its top real segment as the apk root: 8187 // e.g. /something/app/blah.apk => /something 8188 try { 8189 File f = codePath.getCanonicalFile(); 8190 File parent = f.getParentFile(); // non-null because codePath is a file 8191 File tmp; 8192 while ((tmp = parent.getParentFile()) != null) { 8193 f = parent; 8194 parent = tmp; 8195 } 8196 codeRoot = f; 8197 Slog.w(TAG, "Unrecognized code path " 8198 + codePath + " - using " + codeRoot); 8199 } catch (IOException e) { 8200 // Can't canonicalize the code path -- shenanigans? 8201 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8202 return Environment.getRootDirectory().getPath(); 8203 } 8204 } 8205 return codeRoot.getPath(); 8206 } 8207 8208 /** 8209 * Derive and set the location of native libraries for the given package, 8210 * which varies depending on where and how the package was installed. 8211 */ 8212 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8213 final ApplicationInfo info = pkg.applicationInfo; 8214 final String codePath = pkg.codePath; 8215 final File codeFile = new File(codePath); 8216 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8217 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8218 8219 info.nativeLibraryRootDir = null; 8220 info.nativeLibraryRootRequiresIsa = false; 8221 info.nativeLibraryDir = null; 8222 info.secondaryNativeLibraryDir = null; 8223 8224 if (isApkFile(codeFile)) { 8225 // Monolithic install 8226 if (bundledApp) { 8227 // If "/system/lib64/apkname" exists, assume that is the per-package 8228 // native library directory to use; otherwise use "/system/lib/apkname". 8229 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8230 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8231 getPrimaryInstructionSet(info)); 8232 8233 // This is a bundled system app so choose the path based on the ABI. 8234 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8235 // is just the default path. 8236 final String apkName = deriveCodePathName(codePath); 8237 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8238 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8239 apkName).getAbsolutePath(); 8240 8241 if (info.secondaryCpuAbi != null) { 8242 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8243 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8244 secondaryLibDir, apkName).getAbsolutePath(); 8245 } 8246 } else if (asecApp) { 8247 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8248 .getAbsolutePath(); 8249 } else { 8250 final String apkName = deriveCodePathName(codePath); 8251 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8252 .getAbsolutePath(); 8253 } 8254 8255 info.nativeLibraryRootRequiresIsa = false; 8256 info.nativeLibraryDir = info.nativeLibraryRootDir; 8257 } else { 8258 // Cluster install 8259 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8260 info.nativeLibraryRootRequiresIsa = true; 8261 8262 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8263 getPrimaryInstructionSet(info)).getAbsolutePath(); 8264 8265 if (info.secondaryCpuAbi != null) { 8266 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8267 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8268 } 8269 } 8270 } 8271 8272 /** 8273 * Calculate the abis and roots for a bundled app. These can uniquely 8274 * be determined from the contents of the system partition, i.e whether 8275 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8276 * of this information, and instead assume that the system was built 8277 * sensibly. 8278 */ 8279 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8280 PackageSetting pkgSetting) { 8281 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8282 8283 // If "/system/lib64/apkname" exists, assume that is the per-package 8284 // native library directory to use; otherwise use "/system/lib/apkname". 8285 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8286 setBundledAppAbi(pkg, apkRoot, apkName); 8287 // pkgSetting might be null during rescan following uninstall of updates 8288 // to a bundled app, so accommodate that possibility. The settings in 8289 // that case will be established later from the parsed package. 8290 // 8291 // If the settings aren't null, sync them up with what we've just derived. 8292 // note that apkRoot isn't stored in the package settings. 8293 if (pkgSetting != null) { 8294 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8295 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8296 } 8297 } 8298 8299 /** 8300 * Deduces the ABI of a bundled app and sets the relevant fields on the 8301 * parsed pkg object. 8302 * 8303 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8304 * under which system libraries are installed. 8305 * @param apkName the name of the installed package. 8306 */ 8307 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8308 final File codeFile = new File(pkg.codePath); 8309 8310 final boolean has64BitLibs; 8311 final boolean has32BitLibs; 8312 if (isApkFile(codeFile)) { 8313 // Monolithic install 8314 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8315 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8316 } else { 8317 // Cluster install 8318 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8319 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8320 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8321 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8322 has64BitLibs = (new File(rootDir, isa)).exists(); 8323 } else { 8324 has64BitLibs = false; 8325 } 8326 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8327 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8328 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8329 has32BitLibs = (new File(rootDir, isa)).exists(); 8330 } else { 8331 has32BitLibs = false; 8332 } 8333 } 8334 8335 if (has64BitLibs && !has32BitLibs) { 8336 // The package has 64 bit libs, but not 32 bit libs. Its primary 8337 // ABI should be 64 bit. We can safely assume here that the bundled 8338 // native libraries correspond to the most preferred ABI in the list. 8339 8340 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8341 pkg.applicationInfo.secondaryCpuAbi = null; 8342 } else if (has32BitLibs && !has64BitLibs) { 8343 // The package has 32 bit libs but not 64 bit libs. Its primary 8344 // ABI should be 32 bit. 8345 8346 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8347 pkg.applicationInfo.secondaryCpuAbi = null; 8348 } else if (has32BitLibs && has64BitLibs) { 8349 // The application has both 64 and 32 bit bundled libraries. We check 8350 // here that the app declares multiArch support, and warn if it doesn't. 8351 // 8352 // We will be lenient here and record both ABIs. The primary will be the 8353 // ABI that's higher on the list, i.e, a device that's configured to prefer 8354 // 64 bit apps will see a 64 bit primary ABI, 8355 8356 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8357 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8358 } 8359 8360 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8361 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8362 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8363 } else { 8364 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8365 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8366 } 8367 } else { 8368 pkg.applicationInfo.primaryCpuAbi = null; 8369 pkg.applicationInfo.secondaryCpuAbi = null; 8370 } 8371 } 8372 8373 private void killApplication(String pkgName, int appId, String reason) { 8374 // Request the ActivityManager to kill the process(only for existing packages) 8375 // so that we do not end up in a confused state while the user is still using the older 8376 // version of the application while the new one gets installed. 8377 IActivityManager am = ActivityManagerNative.getDefault(); 8378 if (am != null) { 8379 try { 8380 am.killApplicationWithAppId(pkgName, appId, reason); 8381 } catch (RemoteException e) { 8382 } 8383 } 8384 } 8385 8386 void removePackageLI(PackageSetting ps, boolean chatty) { 8387 if (DEBUG_INSTALL) { 8388 if (chatty) 8389 Log.d(TAG, "Removing package " + ps.name); 8390 } 8391 8392 // writer 8393 synchronized (mPackages) { 8394 mPackages.remove(ps.name); 8395 final PackageParser.Package pkg = ps.pkg; 8396 if (pkg != null) { 8397 cleanPackageDataStructuresLILPw(pkg, chatty); 8398 } 8399 } 8400 } 8401 8402 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8403 if (DEBUG_INSTALL) { 8404 if (chatty) 8405 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8406 } 8407 8408 // writer 8409 synchronized (mPackages) { 8410 mPackages.remove(pkg.applicationInfo.packageName); 8411 cleanPackageDataStructuresLILPw(pkg, chatty); 8412 } 8413 } 8414 8415 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8416 int N = pkg.providers.size(); 8417 StringBuilder r = null; 8418 int i; 8419 for (i=0; i<N; i++) { 8420 PackageParser.Provider p = pkg.providers.get(i); 8421 mProviders.removeProvider(p); 8422 if (p.info.authority == null) { 8423 8424 /* There was another ContentProvider with this authority when 8425 * this app was installed so this authority is null, 8426 * Ignore it as we don't have to unregister the provider. 8427 */ 8428 continue; 8429 } 8430 String names[] = p.info.authority.split(";"); 8431 for (int j = 0; j < names.length; j++) { 8432 if (mProvidersByAuthority.get(names[j]) == p) { 8433 mProvidersByAuthority.remove(names[j]); 8434 if (DEBUG_REMOVE) { 8435 if (chatty) 8436 Log.d(TAG, "Unregistered content provider: " + names[j] 8437 + ", className = " + p.info.name + ", isSyncable = " 8438 + p.info.isSyncable); 8439 } 8440 } 8441 } 8442 if (DEBUG_REMOVE && chatty) { 8443 if (r == null) { 8444 r = new StringBuilder(256); 8445 } else { 8446 r.append(' '); 8447 } 8448 r.append(p.info.name); 8449 } 8450 } 8451 if (r != null) { 8452 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8453 } 8454 8455 N = pkg.services.size(); 8456 r = null; 8457 for (i=0; i<N; i++) { 8458 PackageParser.Service s = pkg.services.get(i); 8459 mServices.removeService(s); 8460 if (chatty) { 8461 if (r == null) { 8462 r = new StringBuilder(256); 8463 } else { 8464 r.append(' '); 8465 } 8466 r.append(s.info.name); 8467 } 8468 } 8469 if (r != null) { 8470 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8471 } 8472 8473 N = pkg.receivers.size(); 8474 r = null; 8475 for (i=0; i<N; i++) { 8476 PackageParser.Activity a = pkg.receivers.get(i); 8477 mReceivers.removeActivity(a, "receiver"); 8478 if (DEBUG_REMOVE && chatty) { 8479 if (r == null) { 8480 r = new StringBuilder(256); 8481 } else { 8482 r.append(' '); 8483 } 8484 r.append(a.info.name); 8485 } 8486 } 8487 if (r != null) { 8488 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8489 } 8490 8491 N = pkg.activities.size(); 8492 r = null; 8493 for (i=0; i<N; i++) { 8494 PackageParser.Activity a = pkg.activities.get(i); 8495 mActivities.removeActivity(a, "activity"); 8496 if (DEBUG_REMOVE && chatty) { 8497 if (r == null) { 8498 r = new StringBuilder(256); 8499 } else { 8500 r.append(' '); 8501 } 8502 r.append(a.info.name); 8503 } 8504 } 8505 if (r != null) { 8506 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8507 } 8508 8509 N = pkg.permissions.size(); 8510 r = null; 8511 for (i=0; i<N; i++) { 8512 PackageParser.Permission p = pkg.permissions.get(i); 8513 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8514 if (bp == null) { 8515 bp = mSettings.mPermissionTrees.get(p.info.name); 8516 } 8517 if (bp != null && bp.perm == p) { 8518 bp.perm = null; 8519 if (DEBUG_REMOVE && chatty) { 8520 if (r == null) { 8521 r = new StringBuilder(256); 8522 } else { 8523 r.append(' '); 8524 } 8525 r.append(p.info.name); 8526 } 8527 } 8528 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8529 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8530 if (appOpPkgs != null) { 8531 appOpPkgs.remove(pkg.packageName); 8532 } 8533 } 8534 } 8535 if (r != null) { 8536 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8537 } 8538 8539 N = pkg.requestedPermissions.size(); 8540 r = null; 8541 for (i=0; i<N; i++) { 8542 String perm = pkg.requestedPermissions.get(i); 8543 BasePermission bp = mSettings.mPermissions.get(perm); 8544 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8545 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8546 if (appOpPkgs != null) { 8547 appOpPkgs.remove(pkg.packageName); 8548 if (appOpPkgs.isEmpty()) { 8549 mAppOpPermissionPackages.remove(perm); 8550 } 8551 } 8552 } 8553 } 8554 if (r != null) { 8555 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8556 } 8557 8558 N = pkg.instrumentation.size(); 8559 r = null; 8560 for (i=0; i<N; i++) { 8561 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8562 mInstrumentation.remove(a.getComponentName()); 8563 if (DEBUG_REMOVE && chatty) { 8564 if (r == null) { 8565 r = new StringBuilder(256); 8566 } else { 8567 r.append(' '); 8568 } 8569 r.append(a.info.name); 8570 } 8571 } 8572 if (r != null) { 8573 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8574 } 8575 8576 r = null; 8577 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8578 // Only system apps can hold shared libraries. 8579 if (pkg.libraryNames != null) { 8580 for (i=0; i<pkg.libraryNames.size(); i++) { 8581 String name = pkg.libraryNames.get(i); 8582 SharedLibraryEntry cur = mSharedLibraries.get(name); 8583 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8584 mSharedLibraries.remove(name); 8585 if (DEBUG_REMOVE && chatty) { 8586 if (r == null) { 8587 r = new StringBuilder(256); 8588 } else { 8589 r.append(' '); 8590 } 8591 r.append(name); 8592 } 8593 } 8594 } 8595 } 8596 } 8597 if (r != null) { 8598 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8599 } 8600 } 8601 8602 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8603 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8604 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8605 return true; 8606 } 8607 } 8608 return false; 8609 } 8610 8611 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8612 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8613 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8614 8615 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8616 int flags) { 8617 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8618 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8619 } 8620 8621 private void updatePermissionsLPw(String changingPkg, 8622 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8623 // Make sure there are no dangling permission trees. 8624 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 8625 while (it.hasNext()) { 8626 final BasePermission bp = it.next(); 8627 if (bp.packageSetting == null) { 8628 // We may not yet have parsed the package, so just see if 8629 // we still know about its settings. 8630 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8631 } 8632 if (bp.packageSetting == null) { 8633 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 8634 + " from package " + bp.sourcePackage); 8635 it.remove(); 8636 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8637 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8638 Slog.i(TAG, "Removing old permission tree: " + bp.name 8639 + " from package " + bp.sourcePackage); 8640 flags |= UPDATE_PERMISSIONS_ALL; 8641 it.remove(); 8642 } 8643 } 8644 } 8645 8646 // Make sure all dynamic permissions have been assigned to a package, 8647 // and make sure there are no dangling permissions. 8648 it = mSettings.mPermissions.values().iterator(); 8649 while (it.hasNext()) { 8650 final BasePermission bp = it.next(); 8651 if (bp.type == BasePermission.TYPE_DYNAMIC) { 8652 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 8653 + bp.name + " pkg=" + bp.sourcePackage 8654 + " info=" + bp.pendingInfo); 8655 if (bp.packageSetting == null && bp.pendingInfo != null) { 8656 final BasePermission tree = findPermissionTreeLP(bp.name); 8657 if (tree != null && tree.perm != null) { 8658 bp.packageSetting = tree.packageSetting; 8659 bp.perm = new PackageParser.Permission(tree.perm.owner, 8660 new PermissionInfo(bp.pendingInfo)); 8661 bp.perm.info.packageName = tree.perm.info.packageName; 8662 bp.perm.info.name = bp.name; 8663 bp.uid = tree.uid; 8664 } 8665 } 8666 } 8667 if (bp.packageSetting == null) { 8668 // We may not yet have parsed the package, so just see if 8669 // we still know about its settings. 8670 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 8671 } 8672 if (bp.packageSetting == null) { 8673 Slog.w(TAG, "Removing dangling permission: " + bp.name 8674 + " from package " + bp.sourcePackage); 8675 it.remove(); 8676 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 8677 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 8678 Slog.i(TAG, "Removing old permission: " + bp.name 8679 + " from package " + bp.sourcePackage); 8680 flags |= UPDATE_PERMISSIONS_ALL; 8681 it.remove(); 8682 } 8683 } 8684 } 8685 8686 // Now update the permissions for all packages, in particular 8687 // replace the granted permissions of the system packages. 8688 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 8689 for (PackageParser.Package pkg : mPackages.values()) { 8690 if (pkg != pkgInfo) { 8691 // Only replace for packages on requested volume 8692 final String volumeUuid = getVolumeUuidForPackage(pkg); 8693 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 8694 && Objects.equals(replaceVolumeUuid, volumeUuid); 8695 grantPermissionsLPw(pkg, replace, changingPkg); 8696 } 8697 } 8698 } 8699 8700 if (pkgInfo != null) { 8701 // Only replace for packages on requested volume 8702 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 8703 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 8704 && Objects.equals(replaceVolumeUuid, volumeUuid); 8705 grantPermissionsLPw(pkgInfo, replace, changingPkg); 8706 } 8707 } 8708 8709 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 8710 String packageOfInterest) { 8711 // IMPORTANT: There are two types of permissions: install and runtime. 8712 // Install time permissions are granted when the app is installed to 8713 // all device users and users added in the future. Runtime permissions 8714 // are granted at runtime explicitly to specific users. Normal and signature 8715 // protected permissions are install time permissions. Dangerous permissions 8716 // are install permissions if the app's target SDK is Lollipop MR1 or older, 8717 // otherwise they are runtime permissions. This function does not manage 8718 // runtime permissions except for the case an app targeting Lollipop MR1 8719 // being upgraded to target a newer SDK, in which case dangerous permissions 8720 // are transformed from install time to runtime ones. 8721 8722 final PackageSetting ps = (PackageSetting) pkg.mExtras; 8723 if (ps == null) { 8724 return; 8725 } 8726 8727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 8728 8729 PermissionsState permissionsState = ps.getPermissionsState(); 8730 PermissionsState origPermissions = permissionsState; 8731 8732 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 8733 8734 boolean runtimePermissionsRevoked = false; 8735 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 8736 8737 boolean changedInstallPermission = false; 8738 8739 if (replace) { 8740 ps.installPermissionsFixed = false; 8741 if (!ps.isSharedUser()) { 8742 origPermissions = new PermissionsState(permissionsState); 8743 permissionsState.reset(); 8744 } else { 8745 // We need to know only about runtime permission changes since the 8746 // calling code always writes the install permissions state but 8747 // the runtime ones are written only if changed. The only cases of 8748 // changed runtime permissions here are promotion of an install to 8749 // runtime and revocation of a runtime from a shared user. 8750 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 8751 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 8752 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 8753 runtimePermissionsRevoked = true; 8754 } 8755 } 8756 } 8757 8758 permissionsState.setGlobalGids(mGlobalGids); 8759 8760 final int N = pkg.requestedPermissions.size(); 8761 for (int i=0; i<N; i++) { 8762 final String name = pkg.requestedPermissions.get(i); 8763 final BasePermission bp = mSettings.mPermissions.get(name); 8764 8765 if (DEBUG_INSTALL) { 8766 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 8767 } 8768 8769 if (bp == null || bp.packageSetting == null) { 8770 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8771 Slog.w(TAG, "Unknown permission " + name 8772 + " in package " + pkg.packageName); 8773 } 8774 continue; 8775 } 8776 8777 final String perm = bp.name; 8778 boolean allowedSig = false; 8779 int grant = GRANT_DENIED; 8780 8781 // Keep track of app op permissions. 8782 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8783 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 8784 if (pkgs == null) { 8785 pkgs = new ArraySet<>(); 8786 mAppOpPermissionPackages.put(bp.name, pkgs); 8787 } 8788 pkgs.add(pkg.packageName); 8789 } 8790 8791 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 8792 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 8793 >= Build.VERSION_CODES.M; 8794 switch (level) { 8795 case PermissionInfo.PROTECTION_NORMAL: { 8796 // For all apps normal permissions are install time ones. 8797 grant = GRANT_INSTALL; 8798 } break; 8799 8800 case PermissionInfo.PROTECTION_DANGEROUS: { 8801 // If a permission review is required for legacy apps we represent 8802 // their permissions as always granted runtime ones since we need 8803 // to keep the review required permission flag per user while an 8804 // install permission's state is shared across all users. 8805 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 8806 // For legacy apps dangerous permissions are install time ones. 8807 grant = GRANT_INSTALL; 8808 } else if (origPermissions.hasInstallPermission(bp.name)) { 8809 // For legacy apps that became modern, install becomes runtime. 8810 grant = GRANT_UPGRADE; 8811 } else if (mPromoteSystemApps 8812 && isSystemApp(ps) 8813 && mExistingSystemPackages.contains(ps.name)) { 8814 // For legacy system apps, install becomes runtime. 8815 // We cannot check hasInstallPermission() for system apps since those 8816 // permissions were granted implicitly and not persisted pre-M. 8817 grant = GRANT_UPGRADE; 8818 } else { 8819 // For modern apps keep runtime permissions unchanged. 8820 grant = GRANT_RUNTIME; 8821 } 8822 } break; 8823 8824 case PermissionInfo.PROTECTION_SIGNATURE: { 8825 // For all apps signature permissions are install time ones. 8826 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 8827 if (allowedSig) { 8828 grant = GRANT_INSTALL; 8829 } 8830 } break; 8831 } 8832 8833 if (DEBUG_INSTALL) { 8834 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 8835 } 8836 8837 if (grant != GRANT_DENIED) { 8838 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 8839 // If this is an existing, non-system package, then 8840 // we can't add any new permissions to it. 8841 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 8842 // Except... if this is a permission that was added 8843 // to the platform (note: need to only do this when 8844 // updating the platform). 8845 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 8846 grant = GRANT_DENIED; 8847 } 8848 } 8849 } 8850 8851 switch (grant) { 8852 case GRANT_INSTALL: { 8853 // Revoke this as runtime permission to handle the case of 8854 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 8855 for (int userId : UserManagerService.getInstance().getUserIds()) { 8856 if (origPermissions.getRuntimePermissionState( 8857 bp.name, userId) != null) { 8858 // Revoke the runtime permission and clear the flags. 8859 origPermissions.revokeRuntimePermission(bp, userId); 8860 origPermissions.updatePermissionFlags(bp, userId, 8861 PackageManager.MASK_PERMISSION_FLAGS, 0); 8862 // If we revoked a permission permission, we have to write. 8863 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8864 changedRuntimePermissionUserIds, userId); 8865 } 8866 } 8867 // Grant an install permission. 8868 if (permissionsState.grantInstallPermission(bp) != 8869 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8870 changedInstallPermission = true; 8871 } 8872 } break; 8873 8874 case GRANT_RUNTIME: { 8875 // Grant previously granted runtime permissions. 8876 for (int userId : UserManagerService.getInstance().getUserIds()) { 8877 PermissionState permissionState = origPermissions 8878 .getRuntimePermissionState(bp.name, userId); 8879 int flags = permissionState != null 8880 ? permissionState.getFlags() : 0; 8881 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8882 if (permissionsState.grantRuntimePermission(bp, userId) == 8883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8884 // If we cannot put the permission as it was, we have to write. 8885 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8886 changedRuntimePermissionUserIds, userId); 8887 } 8888 // If the app supports runtime permissions no need for a review. 8889 if (Build.PERMISSIONS_REVIEW_REQUIRED 8890 && appSupportsRuntimePermissions 8891 && (flags & PackageManager 8892 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 8893 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 8894 // Since we changed the flags, we have to write. 8895 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8896 changedRuntimePermissionUserIds, userId); 8897 } 8898 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 8899 && !appSupportsRuntimePermissions) { 8900 // For legacy apps that need a permission review, every new 8901 // runtime permission is granted but it is pending a review. 8902 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 8903 permissionsState.grantRuntimePermission(bp, userId); 8904 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 8905 // We changed the permission and flags, hence have to write. 8906 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8907 changedRuntimePermissionUserIds, userId); 8908 } 8909 } 8910 // Propagate the permission flags. 8911 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8912 } 8913 } break; 8914 8915 case GRANT_UPGRADE: { 8916 // Grant runtime permissions for a previously held install permission. 8917 PermissionState permissionState = origPermissions 8918 .getInstallPermissionState(bp.name); 8919 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8920 8921 if (origPermissions.revokeInstallPermission(bp) 8922 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8923 // We will be transferring the permission flags, so clear them. 8924 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8925 PackageManager.MASK_PERMISSION_FLAGS, 0); 8926 changedInstallPermission = true; 8927 } 8928 8929 // If the permission is not to be promoted to runtime we ignore it and 8930 // also its other flags as they are not applicable to install permissions. 8931 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8932 for (int userId : currentUserIds) { 8933 if (permissionsState.grantRuntimePermission(bp, userId) != 8934 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8935 // Transfer the permission flags. 8936 permissionsState.updatePermissionFlags(bp, userId, 8937 flags, flags); 8938 // If we granted the permission, we have to write. 8939 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8940 changedRuntimePermissionUserIds, userId); 8941 } 8942 } 8943 } 8944 } break; 8945 8946 default: { 8947 if (packageOfInterest == null 8948 || packageOfInterest.equals(pkg.packageName)) { 8949 Slog.w(TAG, "Not granting permission " + perm 8950 + " to package " + pkg.packageName 8951 + " because it was previously installed without"); 8952 } 8953 } break; 8954 } 8955 } else { 8956 if (permissionsState.revokeInstallPermission(bp) != 8957 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8958 // Also drop the permission flags. 8959 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8960 PackageManager.MASK_PERMISSION_FLAGS, 0); 8961 changedInstallPermission = true; 8962 Slog.i(TAG, "Un-granting permission " + perm 8963 + " from package " + pkg.packageName 8964 + " (protectionLevel=" + bp.protectionLevel 8965 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8966 + ")"); 8967 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8968 // Don't print warning for app op permissions, since it is fine for them 8969 // not to be granted, there is a UI for the user to decide. 8970 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8971 Slog.w(TAG, "Not granting permission " + perm 8972 + " to package " + pkg.packageName 8973 + " (protectionLevel=" + bp.protectionLevel 8974 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8975 + ")"); 8976 } 8977 } 8978 } 8979 } 8980 8981 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8982 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8983 // This is the first that we have heard about this package, so the 8984 // permissions we have now selected are fixed until explicitly 8985 // changed. 8986 ps.installPermissionsFixed = true; 8987 } 8988 8989 // Persist the runtime permissions state for users with changes. If permissions 8990 // were revoked because no app in the shared user declares them we have to 8991 // write synchronously to avoid losing runtime permissions state. 8992 for (int userId : changedRuntimePermissionUserIds) { 8993 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 8994 } 8995 8996 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8997 } 8998 8999 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9000 boolean allowed = false; 9001 final int NP = PackageParser.NEW_PERMISSIONS.length; 9002 for (int ip=0; ip<NP; ip++) { 9003 final PackageParser.NewPermissionInfo npi 9004 = PackageParser.NEW_PERMISSIONS[ip]; 9005 if (npi.name.equals(perm) 9006 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9007 allowed = true; 9008 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9009 + pkg.packageName); 9010 break; 9011 } 9012 } 9013 return allowed; 9014 } 9015 9016 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9017 BasePermission bp, PermissionsState origPermissions) { 9018 boolean allowed; 9019 allowed = (compareSignatures( 9020 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9021 == PackageManager.SIGNATURE_MATCH) 9022 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9023 == PackageManager.SIGNATURE_MATCH); 9024 if (!allowed && (bp.protectionLevel 9025 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9026 if (isSystemApp(pkg)) { 9027 // For updated system applications, a system permission 9028 // is granted only if it had been defined by the original application. 9029 if (pkg.isUpdatedSystemApp()) { 9030 final PackageSetting sysPs = mSettings 9031 .getDisabledSystemPkgLPr(pkg.packageName); 9032 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 9033 // If the original was granted this permission, we take 9034 // that grant decision as read and propagate it to the 9035 // update. 9036 if (sysPs.isPrivileged()) { 9037 allowed = true; 9038 } 9039 } else { 9040 // The system apk may have been updated with an older 9041 // version of the one on the data partition, but which 9042 // granted a new system permission that it didn't have 9043 // before. In this case we do want to allow the app to 9044 // now get the new permission if the ancestral apk is 9045 // privileged to get it. 9046 if (sysPs.pkg != null && sysPs.isPrivileged()) { 9047 for (int j=0; 9048 j<sysPs.pkg.requestedPermissions.size(); j++) { 9049 if (perm.equals( 9050 sysPs.pkg.requestedPermissions.get(j))) { 9051 allowed = true; 9052 break; 9053 } 9054 } 9055 } 9056 } 9057 } else { 9058 allowed = isPrivilegedApp(pkg); 9059 } 9060 } 9061 } 9062 if (!allowed) { 9063 if (!allowed && (bp.protectionLevel 9064 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9065 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9066 // If this was a previously normal/dangerous permission that got moved 9067 // to a system permission as part of the runtime permission redesign, then 9068 // we still want to blindly grant it to old apps. 9069 allowed = true; 9070 } 9071 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9072 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9073 // If this permission is to be granted to the system installer and 9074 // this app is an installer, then it gets the permission. 9075 allowed = true; 9076 } 9077 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9078 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9079 // If this permission is to be granted to the system verifier and 9080 // this app is a verifier, then it gets the permission. 9081 allowed = true; 9082 } 9083 if (!allowed && (bp.protectionLevel 9084 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9085 && isSystemApp(pkg)) { 9086 // Any pre-installed system app is allowed to get this permission. 9087 allowed = true; 9088 } 9089 if (!allowed && (bp.protectionLevel 9090 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9091 // For development permissions, a development permission 9092 // is granted only if it was already granted. 9093 allowed = origPermissions.hasInstallPermission(perm); 9094 } 9095 } 9096 return allowed; 9097 } 9098 9099 final class ActivityIntentResolver 9100 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9102 boolean defaultOnly, int userId) { 9103 if (!sUserManager.exists(userId)) return null; 9104 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9105 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9106 } 9107 9108 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9109 int userId) { 9110 if (!sUserManager.exists(userId)) return null; 9111 mFlags = flags; 9112 return super.queryIntent(intent, resolvedType, 9113 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9114 } 9115 9116 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9117 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9118 if (!sUserManager.exists(userId)) return null; 9119 if (packageActivities == null) { 9120 return null; 9121 } 9122 mFlags = flags; 9123 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9124 final int N = packageActivities.size(); 9125 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9126 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9127 9128 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9129 for (int i = 0; i < N; ++i) { 9130 intentFilters = packageActivities.get(i).intents; 9131 if (intentFilters != null && intentFilters.size() > 0) { 9132 PackageParser.ActivityIntentInfo[] array = 9133 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9134 intentFilters.toArray(array); 9135 listCut.add(array); 9136 } 9137 } 9138 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9139 } 9140 9141 public final void addActivity(PackageParser.Activity a, String type) { 9142 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9143 mActivities.put(a.getComponentName(), a); 9144 if (DEBUG_SHOW_INFO) 9145 Log.v( 9146 TAG, " " + type + " " + 9147 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9148 if (DEBUG_SHOW_INFO) 9149 Log.v(TAG, " Class=" + a.info.name); 9150 final int NI = a.intents.size(); 9151 for (int j=0; j<NI; j++) { 9152 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9153 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9154 intent.setPriority(0); 9155 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9156 + a.className + " with priority > 0, forcing to 0"); 9157 } 9158 if (DEBUG_SHOW_INFO) { 9159 Log.v(TAG, " IntentFilter:"); 9160 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9161 } 9162 if (!intent.debugCheck()) { 9163 Log.w(TAG, "==> For Activity " + a.info.name); 9164 } 9165 addFilter(intent); 9166 } 9167 } 9168 9169 public final void removeActivity(PackageParser.Activity a, String type) { 9170 mActivities.remove(a.getComponentName()); 9171 if (DEBUG_SHOW_INFO) { 9172 Log.v(TAG, " " + type + " " 9173 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9174 : a.info.name) + ":"); 9175 Log.v(TAG, " Class=" + a.info.name); 9176 } 9177 final int NI = a.intents.size(); 9178 for (int j=0; j<NI; j++) { 9179 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9180 if (DEBUG_SHOW_INFO) { 9181 Log.v(TAG, " IntentFilter:"); 9182 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9183 } 9184 removeFilter(intent); 9185 } 9186 } 9187 9188 @Override 9189 protected boolean allowFilterResult( 9190 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9191 ActivityInfo filterAi = filter.activity.info; 9192 for (int i=dest.size()-1; i>=0; i--) { 9193 ActivityInfo destAi = dest.get(i).activityInfo; 9194 if (destAi.name == filterAi.name 9195 && destAi.packageName == filterAi.packageName) { 9196 return false; 9197 } 9198 } 9199 return true; 9200 } 9201 9202 @Override 9203 protected ActivityIntentInfo[] newArray(int size) { 9204 return new ActivityIntentInfo[size]; 9205 } 9206 9207 @Override 9208 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9209 if (!sUserManager.exists(userId)) return true; 9210 PackageParser.Package p = filter.activity.owner; 9211 if (p != null) { 9212 PackageSetting ps = (PackageSetting)p.mExtras; 9213 if (ps != null) { 9214 // System apps are never considered stopped for purposes of 9215 // filtering, because there may be no way for the user to 9216 // actually re-launch them. 9217 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9218 && ps.getStopped(userId); 9219 } 9220 } 9221 return false; 9222 } 9223 9224 @Override 9225 protected boolean isPackageForFilter(String packageName, 9226 PackageParser.ActivityIntentInfo info) { 9227 return packageName.equals(info.activity.owner.packageName); 9228 } 9229 9230 @Override 9231 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9232 int match, int userId) { 9233 if (!sUserManager.exists(userId)) return null; 9234 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9235 return null; 9236 } 9237 final PackageParser.Activity activity = info.activity; 9238 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9239 if (ps == null) { 9240 return null; 9241 } 9242 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9243 ps.readUserState(userId), userId); 9244 if (ai == null) { 9245 return null; 9246 } 9247 final ResolveInfo res = new ResolveInfo(); 9248 res.activityInfo = ai; 9249 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9250 res.filter = info; 9251 } 9252 if (info != null) { 9253 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9254 } 9255 res.priority = info.getPriority(); 9256 res.preferredOrder = activity.owner.mPreferredOrder; 9257 //System.out.println("Result: " + res.activityInfo.className + 9258 // " = " + res.priority); 9259 res.match = match; 9260 res.isDefault = info.hasDefault; 9261 res.labelRes = info.labelRes; 9262 res.nonLocalizedLabel = info.nonLocalizedLabel; 9263 if (userNeedsBadging(userId)) { 9264 res.noResourceId = true; 9265 } else { 9266 res.icon = info.icon; 9267 } 9268 res.iconResourceId = info.icon; 9269 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9270 return res; 9271 } 9272 9273 @Override 9274 protected void sortResults(List<ResolveInfo> results) { 9275 Collections.sort(results, mResolvePrioritySorter); 9276 } 9277 9278 @Override 9279 protected void dumpFilter(PrintWriter out, String prefix, 9280 PackageParser.ActivityIntentInfo filter) { 9281 out.print(prefix); out.print( 9282 Integer.toHexString(System.identityHashCode(filter.activity))); 9283 out.print(' '); 9284 filter.activity.printComponentShortName(out); 9285 out.print(" filter "); 9286 out.println(Integer.toHexString(System.identityHashCode(filter))); 9287 } 9288 9289 @Override 9290 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9291 return filter.activity; 9292 } 9293 9294 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9295 PackageParser.Activity activity = (PackageParser.Activity)label; 9296 out.print(prefix); out.print( 9297 Integer.toHexString(System.identityHashCode(activity))); 9298 out.print(' '); 9299 activity.printComponentShortName(out); 9300 if (count > 1) { 9301 out.print(" ("); out.print(count); out.print(" filters)"); 9302 } 9303 out.println(); 9304 } 9305 9306// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9307// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9308// final List<ResolveInfo> retList = Lists.newArrayList(); 9309// while (i.hasNext()) { 9310// final ResolveInfo resolveInfo = i.next(); 9311// if (isEnabledLP(resolveInfo.activityInfo)) { 9312// retList.add(resolveInfo); 9313// } 9314// } 9315// return retList; 9316// } 9317 9318 // Keys are String (activity class name), values are Activity. 9319 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9320 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9321 private int mFlags; 9322 } 9323 9324 private final class ServiceIntentResolver 9325 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9326 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9327 boolean defaultOnly, int userId) { 9328 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9329 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9330 } 9331 9332 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9333 int userId) { 9334 if (!sUserManager.exists(userId)) return null; 9335 mFlags = flags; 9336 return super.queryIntent(intent, resolvedType, 9337 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9338 } 9339 9340 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9341 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9342 if (!sUserManager.exists(userId)) return null; 9343 if (packageServices == null) { 9344 return null; 9345 } 9346 mFlags = flags; 9347 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9348 final int N = packageServices.size(); 9349 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9350 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9351 9352 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9353 for (int i = 0; i < N; ++i) { 9354 intentFilters = packageServices.get(i).intents; 9355 if (intentFilters != null && intentFilters.size() > 0) { 9356 PackageParser.ServiceIntentInfo[] array = 9357 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9358 intentFilters.toArray(array); 9359 listCut.add(array); 9360 } 9361 } 9362 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9363 } 9364 9365 public final void addService(PackageParser.Service s) { 9366 mServices.put(s.getComponentName(), s); 9367 if (DEBUG_SHOW_INFO) { 9368 Log.v(TAG, " " 9369 + (s.info.nonLocalizedLabel != null 9370 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9371 Log.v(TAG, " Class=" + s.info.name); 9372 } 9373 final int NI = s.intents.size(); 9374 int j; 9375 for (j=0; j<NI; j++) { 9376 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9377 if (DEBUG_SHOW_INFO) { 9378 Log.v(TAG, " IntentFilter:"); 9379 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9380 } 9381 if (!intent.debugCheck()) { 9382 Log.w(TAG, "==> For Service " + s.info.name); 9383 } 9384 addFilter(intent); 9385 } 9386 } 9387 9388 public final void removeService(PackageParser.Service s) { 9389 mServices.remove(s.getComponentName()); 9390 if (DEBUG_SHOW_INFO) { 9391 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9392 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9393 Log.v(TAG, " Class=" + s.info.name); 9394 } 9395 final int NI = s.intents.size(); 9396 int j; 9397 for (j=0; j<NI; j++) { 9398 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9399 if (DEBUG_SHOW_INFO) { 9400 Log.v(TAG, " IntentFilter:"); 9401 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9402 } 9403 removeFilter(intent); 9404 } 9405 } 9406 9407 @Override 9408 protected boolean allowFilterResult( 9409 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9410 ServiceInfo filterSi = filter.service.info; 9411 for (int i=dest.size()-1; i>=0; i--) { 9412 ServiceInfo destAi = dest.get(i).serviceInfo; 9413 if (destAi.name == filterSi.name 9414 && destAi.packageName == filterSi.packageName) { 9415 return false; 9416 } 9417 } 9418 return true; 9419 } 9420 9421 @Override 9422 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9423 return new PackageParser.ServiceIntentInfo[size]; 9424 } 9425 9426 @Override 9427 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9428 if (!sUserManager.exists(userId)) return true; 9429 PackageParser.Package p = filter.service.owner; 9430 if (p != null) { 9431 PackageSetting ps = (PackageSetting)p.mExtras; 9432 if (ps != null) { 9433 // System apps are never considered stopped for purposes of 9434 // filtering, because there may be no way for the user to 9435 // actually re-launch them. 9436 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9437 && ps.getStopped(userId); 9438 } 9439 } 9440 return false; 9441 } 9442 9443 @Override 9444 protected boolean isPackageForFilter(String packageName, 9445 PackageParser.ServiceIntentInfo info) { 9446 return packageName.equals(info.service.owner.packageName); 9447 } 9448 9449 @Override 9450 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9451 int match, int userId) { 9452 if (!sUserManager.exists(userId)) return null; 9453 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9454 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9455 return null; 9456 } 9457 final PackageParser.Service service = info.service; 9458 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9459 if (ps == null) { 9460 return null; 9461 } 9462 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9463 ps.readUserState(userId), userId); 9464 if (si == null) { 9465 return null; 9466 } 9467 final ResolveInfo res = new ResolveInfo(); 9468 res.serviceInfo = si; 9469 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9470 res.filter = filter; 9471 } 9472 res.priority = info.getPriority(); 9473 res.preferredOrder = service.owner.mPreferredOrder; 9474 res.match = match; 9475 res.isDefault = info.hasDefault; 9476 res.labelRes = info.labelRes; 9477 res.nonLocalizedLabel = info.nonLocalizedLabel; 9478 res.icon = info.icon; 9479 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9480 return res; 9481 } 9482 9483 @Override 9484 protected void sortResults(List<ResolveInfo> results) { 9485 Collections.sort(results, mResolvePrioritySorter); 9486 } 9487 9488 @Override 9489 protected void dumpFilter(PrintWriter out, String prefix, 9490 PackageParser.ServiceIntentInfo filter) { 9491 out.print(prefix); out.print( 9492 Integer.toHexString(System.identityHashCode(filter.service))); 9493 out.print(' '); 9494 filter.service.printComponentShortName(out); 9495 out.print(" filter "); 9496 out.println(Integer.toHexString(System.identityHashCode(filter))); 9497 } 9498 9499 @Override 9500 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9501 return filter.service; 9502 } 9503 9504 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9505 PackageParser.Service service = (PackageParser.Service)label; 9506 out.print(prefix); out.print( 9507 Integer.toHexString(System.identityHashCode(service))); 9508 out.print(' '); 9509 service.printComponentShortName(out); 9510 if (count > 1) { 9511 out.print(" ("); out.print(count); out.print(" filters)"); 9512 } 9513 out.println(); 9514 } 9515 9516// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9517// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9518// final List<ResolveInfo> retList = Lists.newArrayList(); 9519// while (i.hasNext()) { 9520// final ResolveInfo resolveInfo = (ResolveInfo) i; 9521// if (isEnabledLP(resolveInfo.serviceInfo)) { 9522// retList.add(resolveInfo); 9523// } 9524// } 9525// return retList; 9526// } 9527 9528 // Keys are String (activity class name), values are Activity. 9529 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9530 = new ArrayMap<ComponentName, PackageParser.Service>(); 9531 private int mFlags; 9532 }; 9533 9534 private final class ProviderIntentResolver 9535 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9536 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9537 boolean defaultOnly, int userId) { 9538 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9539 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9540 } 9541 9542 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9543 int userId) { 9544 if (!sUserManager.exists(userId)) 9545 return null; 9546 mFlags = flags; 9547 return super.queryIntent(intent, resolvedType, 9548 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9549 } 9550 9551 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9552 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9553 if (!sUserManager.exists(userId)) 9554 return null; 9555 if (packageProviders == null) { 9556 return null; 9557 } 9558 mFlags = flags; 9559 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9560 final int N = packageProviders.size(); 9561 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9562 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9563 9564 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9565 for (int i = 0; i < N; ++i) { 9566 intentFilters = packageProviders.get(i).intents; 9567 if (intentFilters != null && intentFilters.size() > 0) { 9568 PackageParser.ProviderIntentInfo[] array = 9569 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9570 intentFilters.toArray(array); 9571 listCut.add(array); 9572 } 9573 } 9574 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9575 } 9576 9577 public final void addProvider(PackageParser.Provider p) { 9578 if (mProviders.containsKey(p.getComponentName())) { 9579 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9580 return; 9581 } 9582 9583 mProviders.put(p.getComponentName(), p); 9584 if (DEBUG_SHOW_INFO) { 9585 Log.v(TAG, " " 9586 + (p.info.nonLocalizedLabel != null 9587 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9588 Log.v(TAG, " Class=" + p.info.name); 9589 } 9590 final int NI = p.intents.size(); 9591 int j; 9592 for (j = 0; j < NI; j++) { 9593 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9594 if (DEBUG_SHOW_INFO) { 9595 Log.v(TAG, " IntentFilter:"); 9596 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9597 } 9598 if (!intent.debugCheck()) { 9599 Log.w(TAG, "==> For Provider " + p.info.name); 9600 } 9601 addFilter(intent); 9602 } 9603 } 9604 9605 public final void removeProvider(PackageParser.Provider p) { 9606 mProviders.remove(p.getComponentName()); 9607 if (DEBUG_SHOW_INFO) { 9608 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 9609 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9610 Log.v(TAG, " Class=" + p.info.name); 9611 } 9612 final int NI = p.intents.size(); 9613 int j; 9614 for (j = 0; j < NI; j++) { 9615 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 9616 if (DEBUG_SHOW_INFO) { 9617 Log.v(TAG, " IntentFilter:"); 9618 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9619 } 9620 removeFilter(intent); 9621 } 9622 } 9623 9624 @Override 9625 protected boolean allowFilterResult( 9626 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 9627 ProviderInfo filterPi = filter.provider.info; 9628 for (int i = dest.size() - 1; i >= 0; i--) { 9629 ProviderInfo destPi = dest.get(i).providerInfo; 9630 if (destPi.name == filterPi.name 9631 && destPi.packageName == filterPi.packageName) { 9632 return false; 9633 } 9634 } 9635 return true; 9636 } 9637 9638 @Override 9639 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 9640 return new PackageParser.ProviderIntentInfo[size]; 9641 } 9642 9643 @Override 9644 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 9645 if (!sUserManager.exists(userId)) 9646 return true; 9647 PackageParser.Package p = filter.provider.owner; 9648 if (p != null) { 9649 PackageSetting ps = (PackageSetting) p.mExtras; 9650 if (ps != null) { 9651 // System apps are never considered stopped for purposes of 9652 // filtering, because there may be no way for the user to 9653 // actually re-launch them. 9654 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9655 && ps.getStopped(userId); 9656 } 9657 } 9658 return false; 9659 } 9660 9661 @Override 9662 protected boolean isPackageForFilter(String packageName, 9663 PackageParser.ProviderIntentInfo info) { 9664 return packageName.equals(info.provider.owner.packageName); 9665 } 9666 9667 @Override 9668 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 9669 int match, int userId) { 9670 if (!sUserManager.exists(userId)) 9671 return null; 9672 final PackageParser.ProviderIntentInfo info = filter; 9673 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 9674 return null; 9675 } 9676 final PackageParser.Provider provider = info.provider; 9677 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 9678 if (ps == null) { 9679 return null; 9680 } 9681 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 9682 ps.readUserState(userId), userId); 9683 if (pi == null) { 9684 return null; 9685 } 9686 final ResolveInfo res = new ResolveInfo(); 9687 res.providerInfo = pi; 9688 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 9689 res.filter = filter; 9690 } 9691 res.priority = info.getPriority(); 9692 res.preferredOrder = provider.owner.mPreferredOrder; 9693 res.match = match; 9694 res.isDefault = info.hasDefault; 9695 res.labelRes = info.labelRes; 9696 res.nonLocalizedLabel = info.nonLocalizedLabel; 9697 res.icon = info.icon; 9698 res.system = res.providerInfo.applicationInfo.isSystemApp(); 9699 return res; 9700 } 9701 9702 @Override 9703 protected void sortResults(List<ResolveInfo> results) { 9704 Collections.sort(results, mResolvePrioritySorter); 9705 } 9706 9707 @Override 9708 protected void dumpFilter(PrintWriter out, String prefix, 9709 PackageParser.ProviderIntentInfo filter) { 9710 out.print(prefix); 9711 out.print( 9712 Integer.toHexString(System.identityHashCode(filter.provider))); 9713 out.print(' '); 9714 filter.provider.printComponentShortName(out); 9715 out.print(" filter "); 9716 out.println(Integer.toHexString(System.identityHashCode(filter))); 9717 } 9718 9719 @Override 9720 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 9721 return filter.provider; 9722 } 9723 9724 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9725 PackageParser.Provider provider = (PackageParser.Provider)label; 9726 out.print(prefix); out.print( 9727 Integer.toHexString(System.identityHashCode(provider))); 9728 out.print(' '); 9729 provider.printComponentShortName(out); 9730 if (count > 1) { 9731 out.print(" ("); out.print(count); out.print(" filters)"); 9732 } 9733 out.println(); 9734 } 9735 9736 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 9737 = new ArrayMap<ComponentName, PackageParser.Provider>(); 9738 private int mFlags; 9739 } 9740 9741 private static final class EphemeralIntentResolver 9742 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 9743 @Override 9744 protected EphemeralResolveIntentInfo[] newArray(int size) { 9745 return new EphemeralResolveIntentInfo[size]; 9746 } 9747 9748 @Override 9749 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 9750 return true; 9751 } 9752 9753 @Override 9754 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 9755 int userId) { 9756 if (!sUserManager.exists(userId)) { 9757 return null; 9758 } 9759 return info.getEphemeralResolveInfo(); 9760 } 9761 } 9762 9763 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 9764 new Comparator<ResolveInfo>() { 9765 public int compare(ResolveInfo r1, ResolveInfo r2) { 9766 int v1 = r1.priority; 9767 int v2 = r2.priority; 9768 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 9769 if (v1 != v2) { 9770 return (v1 > v2) ? -1 : 1; 9771 } 9772 v1 = r1.preferredOrder; 9773 v2 = r2.preferredOrder; 9774 if (v1 != v2) { 9775 return (v1 > v2) ? -1 : 1; 9776 } 9777 if (r1.isDefault != r2.isDefault) { 9778 return r1.isDefault ? -1 : 1; 9779 } 9780 v1 = r1.match; 9781 v2 = r2.match; 9782 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 9783 if (v1 != v2) { 9784 return (v1 > v2) ? -1 : 1; 9785 } 9786 if (r1.system != r2.system) { 9787 return r1.system ? -1 : 1; 9788 } 9789 if (r1.activityInfo != null) { 9790 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 9791 } 9792 if (r1.serviceInfo != null) { 9793 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 9794 } 9795 if (r1.providerInfo != null) { 9796 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 9797 } 9798 return 0; 9799 } 9800 }; 9801 9802 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 9803 new Comparator<ProviderInfo>() { 9804 public int compare(ProviderInfo p1, ProviderInfo p2) { 9805 final int v1 = p1.initOrder; 9806 final int v2 = p2.initOrder; 9807 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 9808 } 9809 }; 9810 9811 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 9812 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 9813 final int[] userIds) { 9814 mHandler.post(new Runnable() { 9815 @Override 9816 public void run() { 9817 try { 9818 final IActivityManager am = ActivityManagerNative.getDefault(); 9819 if (am == null) return; 9820 final int[] resolvedUserIds; 9821 if (userIds == null) { 9822 resolvedUserIds = am.getRunningUserIds(); 9823 } else { 9824 resolvedUserIds = userIds; 9825 } 9826 for (int id : resolvedUserIds) { 9827 final Intent intent = new Intent(action, 9828 pkg != null ? Uri.fromParts("package", pkg, null) : null); 9829 if (extras != null) { 9830 intent.putExtras(extras); 9831 } 9832 if (targetPkg != null) { 9833 intent.setPackage(targetPkg); 9834 } 9835 // Modify the UID when posting to other users 9836 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 9837 if (uid > 0 && UserHandle.getUserId(uid) != id) { 9838 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 9839 intent.putExtra(Intent.EXTRA_UID, uid); 9840 } 9841 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 9842 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 9843 if (DEBUG_BROADCASTS) { 9844 RuntimeException here = new RuntimeException("here"); 9845 here.fillInStackTrace(); 9846 Slog.d(TAG, "Sending to user " + id + ": " 9847 + intent.toShortString(false, true, false, false) 9848 + " " + intent.getExtras(), here); 9849 } 9850 am.broadcastIntent(null, intent, null, finishedReceiver, 9851 0, null, null, null, android.app.AppOpsManager.OP_NONE, 9852 null, finishedReceiver != null, false, id); 9853 } 9854 } catch (RemoteException ex) { 9855 } 9856 } 9857 }); 9858 } 9859 9860 /** 9861 * Check if the external storage media is available. This is true if there 9862 * is a mounted external storage medium or if the external storage is 9863 * emulated. 9864 */ 9865 private boolean isExternalMediaAvailable() { 9866 return mMediaMounted || Environment.isExternalStorageEmulated(); 9867 } 9868 9869 @Override 9870 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 9871 // writer 9872 synchronized (mPackages) { 9873 if (!isExternalMediaAvailable()) { 9874 // If the external storage is no longer mounted at this point, 9875 // the caller may not have been able to delete all of this 9876 // packages files and can not delete any more. Bail. 9877 return null; 9878 } 9879 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 9880 if (lastPackage != null) { 9881 pkgs.remove(lastPackage); 9882 } 9883 if (pkgs.size() > 0) { 9884 return pkgs.get(0); 9885 } 9886 } 9887 return null; 9888 } 9889 9890 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 9891 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 9892 userId, andCode ? 1 : 0, packageName); 9893 if (mSystemReady) { 9894 msg.sendToTarget(); 9895 } else { 9896 if (mPostSystemReadyMessages == null) { 9897 mPostSystemReadyMessages = new ArrayList<>(); 9898 } 9899 mPostSystemReadyMessages.add(msg); 9900 } 9901 } 9902 9903 void startCleaningPackages() { 9904 // reader 9905 synchronized (mPackages) { 9906 if (!isExternalMediaAvailable()) { 9907 return; 9908 } 9909 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 9910 return; 9911 } 9912 } 9913 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 9914 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 9915 IActivityManager am = ActivityManagerNative.getDefault(); 9916 if (am != null) { 9917 try { 9918 am.startService(null, intent, null, mContext.getOpPackageName(), 9919 UserHandle.USER_SYSTEM); 9920 } catch (RemoteException e) { 9921 } 9922 } 9923 } 9924 9925 @Override 9926 public void installPackage(String originPath, IPackageInstallObserver2 observer, 9927 int installFlags, String installerPackageName, VerificationParams verificationParams, 9928 String packageAbiOverride) { 9929 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9930 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9931 } 9932 9933 @Override 9934 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9935 int installFlags, String installerPackageName, VerificationParams verificationParams, 9936 String packageAbiOverride, int userId) { 9937 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9938 9939 final int callingUid = Binder.getCallingUid(); 9940 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9941 9942 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9943 try { 9944 if (observer != null) { 9945 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9946 } 9947 } catch (RemoteException re) { 9948 } 9949 return; 9950 } 9951 9952 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9953 installFlags |= PackageManager.INSTALL_FROM_ADB; 9954 9955 } else { 9956 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9957 // about installerPackageName. 9958 9959 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9960 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9961 } 9962 9963 UserHandle user; 9964 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9965 user = UserHandle.ALL; 9966 } else { 9967 user = new UserHandle(userId); 9968 } 9969 9970 // Only system components can circumvent runtime permissions when installing. 9971 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9972 && mContext.checkCallingOrSelfPermission(Manifest.permission 9973 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9974 throw new SecurityException("You need the " 9975 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9976 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9977 } 9978 9979 verificationParams.setInstallerUid(callingUid); 9980 9981 final File originFile = new File(originPath); 9982 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9983 9984 final Message msg = mHandler.obtainMessage(INIT_COPY); 9985 final InstallParams params = new InstallParams(origin, null, observer, installFlags, 9986 installerPackageName, null, verificationParams, user, packageAbiOverride, null); 9987 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 9988 msg.obj = params; 9989 9990 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 9991 System.identityHashCode(msg.obj)); 9992 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 9993 System.identityHashCode(msg.obj)); 9994 9995 mHandler.sendMessage(msg); 9996 } 9997 9998 void installStage(String packageName, File stagedDir, String stagedCid, 9999 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10000 String installerPackageName, int installerUid, UserHandle user) { 10001 if (DEBUG_EPHEMERAL) { 10002 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10003 Slog.d(TAG, "Ephemeral install of " + packageName); 10004 } 10005 } 10006 final VerificationParams verifParams = new VerificationParams( 10007 null, sessionParams.originatingUri, sessionParams.referrerUri, 10008 sessionParams.originatingUid); 10009 verifParams.setInstallerUid(installerUid); 10010 10011 final OriginInfo origin; 10012 if (stagedDir != null) { 10013 origin = OriginInfo.fromStagedFile(stagedDir); 10014 } else { 10015 origin = OriginInfo.fromStagedContainer(stagedCid); 10016 } 10017 10018 final Message msg = mHandler.obtainMessage(INIT_COPY); 10019 final InstallParams params = new InstallParams(origin, null, observer, 10020 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10021 verifParams, user, sessionParams.abiOverride, 10022 sessionParams.grantedRuntimePermissions); 10023 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10024 msg.obj = params; 10025 10026 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10027 System.identityHashCode(msg.obj)); 10028 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10029 System.identityHashCode(msg.obj)); 10030 10031 mHandler.sendMessage(msg); 10032 } 10033 10034 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10035 Bundle extras = new Bundle(1); 10036 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10037 10038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10039 packageName, extras, 0, null, null, new int[] {userId}); 10040 try { 10041 IActivityManager am = ActivityManagerNative.getDefault(); 10042 final boolean isSystem = 10043 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10044 if (isSystem && am.isUserRunning(userId, 0)) { 10045 // The just-installed/enabled app is bundled on the system, so presumed 10046 // to be able to run automatically without needing an explicit launch. 10047 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10048 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10049 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10050 .setPackage(packageName); 10051 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10052 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10053 } 10054 } catch (RemoteException e) { 10055 // shouldn't happen 10056 Slog.w(TAG, "Unable to bootstrap installed package", e); 10057 } 10058 } 10059 10060 @Override 10061 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10062 int userId) { 10063 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10064 PackageSetting pkgSetting; 10065 final int uid = Binder.getCallingUid(); 10066 enforceCrossUserPermission(uid, userId, true, true, 10067 "setApplicationHiddenSetting for user " + userId); 10068 10069 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10070 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10071 return false; 10072 } 10073 10074 long callingId = Binder.clearCallingIdentity(); 10075 try { 10076 boolean sendAdded = false; 10077 boolean sendRemoved = false; 10078 // writer 10079 synchronized (mPackages) { 10080 pkgSetting = mSettings.mPackages.get(packageName); 10081 if (pkgSetting == null) { 10082 return false; 10083 } 10084 if (pkgSetting.getHidden(userId) != hidden) { 10085 pkgSetting.setHidden(hidden, userId); 10086 mSettings.writePackageRestrictionsLPr(userId); 10087 if (hidden) { 10088 sendRemoved = true; 10089 } else { 10090 sendAdded = true; 10091 } 10092 } 10093 } 10094 if (sendAdded) { 10095 sendPackageAddedForUser(packageName, pkgSetting, userId); 10096 return true; 10097 } 10098 if (sendRemoved) { 10099 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10100 "hiding pkg"); 10101 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10102 return true; 10103 } 10104 } finally { 10105 Binder.restoreCallingIdentity(callingId); 10106 } 10107 return false; 10108 } 10109 10110 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10111 int userId) { 10112 final PackageRemovedInfo info = new PackageRemovedInfo(); 10113 info.removedPackage = packageName; 10114 info.removedUsers = new int[] {userId}; 10115 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10116 info.sendBroadcast(false, false, false); 10117 } 10118 10119 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10120 if (pkgList.length > 0) { 10121 Bundle extras = new Bundle(1); 10122 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10123 10124 sendPackageBroadcast( 10125 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10126 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10127 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10128 new int[] {userId}); 10129 } 10130 } 10131 10132 /** 10133 * Returns true if application is not found or there was an error. Otherwise it returns 10134 * the hidden state of the package for the given user. 10135 */ 10136 @Override 10137 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10138 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10139 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10140 false, "getApplicationHidden for user " + userId); 10141 PackageSetting pkgSetting; 10142 long callingId = Binder.clearCallingIdentity(); 10143 try { 10144 // writer 10145 synchronized (mPackages) { 10146 pkgSetting = mSettings.mPackages.get(packageName); 10147 if (pkgSetting == null) { 10148 return true; 10149 } 10150 return pkgSetting.getHidden(userId); 10151 } 10152 } finally { 10153 Binder.restoreCallingIdentity(callingId); 10154 } 10155 } 10156 10157 /** 10158 * @hide 10159 */ 10160 @Override 10161 public int installExistingPackageAsUser(String packageName, int userId) { 10162 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10163 null); 10164 PackageSetting pkgSetting; 10165 final int uid = Binder.getCallingUid(); 10166 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10167 + userId); 10168 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10169 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10170 } 10171 10172 long callingId = Binder.clearCallingIdentity(); 10173 try { 10174 boolean installed = false; 10175 10176 // writer 10177 synchronized (mPackages) { 10178 pkgSetting = mSettings.mPackages.get(packageName); 10179 if (pkgSetting == null) { 10180 return PackageManager.INSTALL_FAILED_INVALID_URI; 10181 } 10182 if (!pkgSetting.getInstalled(userId)) { 10183 pkgSetting.setInstalled(true, userId); 10184 pkgSetting.setHidden(false, userId); 10185 mSettings.writePackageRestrictionsLPr(userId); 10186 if (pkgSetting.pkg != null) { 10187 prepareAppDataAfterInstall(pkgSetting.pkg); 10188 } 10189 installed = true; 10190 } 10191 } 10192 10193 if (installed) { 10194 sendPackageAddedForUser(packageName, pkgSetting, userId); 10195 } 10196 } finally { 10197 Binder.restoreCallingIdentity(callingId); 10198 } 10199 10200 return PackageManager.INSTALL_SUCCEEDED; 10201 } 10202 10203 boolean isUserRestricted(int userId, String restrictionKey) { 10204 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10205 if (restrictions.getBoolean(restrictionKey, false)) { 10206 Log.w(TAG, "User is restricted: " + restrictionKey); 10207 return true; 10208 } 10209 return false; 10210 } 10211 10212 @Override 10213 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10214 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10215 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10216 "setPackageSuspended for user " + userId); 10217 10218 // TODO: investigate and add more restrictions for suspending crucial packages. 10219 if (isPackageDeviceAdmin(packageName, userId)) { 10220 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10221 + "\": has active device admin"); 10222 return false; 10223 } 10224 10225 long callingId = Binder.clearCallingIdentity(); 10226 try { 10227 boolean changed = false; 10228 boolean success = false; 10229 int appId = -1; 10230 synchronized (mPackages) { 10231 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10232 if (pkgSetting != null) { 10233 if (pkgSetting.getSuspended(userId) != suspended) { 10234 pkgSetting.setSuspended(suspended, userId); 10235 mSettings.writePackageRestrictionsLPr(userId); 10236 appId = pkgSetting.appId; 10237 changed = true; 10238 } 10239 success = true; 10240 } 10241 } 10242 10243 if (changed) { 10244 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10245 if (suspended) { 10246 killApplication(packageName, UserHandle.getUid(userId, appId), 10247 "suspending package"); 10248 } 10249 } 10250 return success; 10251 } finally { 10252 Binder.restoreCallingIdentity(callingId); 10253 } 10254 } 10255 10256 @Override 10257 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10258 mContext.enforceCallingOrSelfPermission( 10259 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10260 "Only package verification agents can verify applications"); 10261 10262 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10263 final PackageVerificationResponse response = new PackageVerificationResponse( 10264 verificationCode, Binder.getCallingUid()); 10265 msg.arg1 = id; 10266 msg.obj = response; 10267 mHandler.sendMessage(msg); 10268 } 10269 10270 @Override 10271 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10272 long millisecondsToDelay) { 10273 mContext.enforceCallingOrSelfPermission( 10274 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10275 "Only package verification agents can extend verification timeouts"); 10276 10277 final PackageVerificationState state = mPendingVerification.get(id); 10278 final PackageVerificationResponse response = new PackageVerificationResponse( 10279 verificationCodeAtTimeout, Binder.getCallingUid()); 10280 10281 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10282 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10283 } 10284 if (millisecondsToDelay < 0) { 10285 millisecondsToDelay = 0; 10286 } 10287 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10288 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10289 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10290 } 10291 10292 if ((state != null) && !state.timeoutExtended()) { 10293 state.extendTimeout(); 10294 10295 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10296 msg.arg1 = id; 10297 msg.obj = response; 10298 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10299 } 10300 } 10301 10302 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10303 int verificationCode, UserHandle user) { 10304 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10305 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10306 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10307 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10308 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10309 10310 mContext.sendBroadcastAsUser(intent, user, 10311 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10312 } 10313 10314 private ComponentName matchComponentForVerifier(String packageName, 10315 List<ResolveInfo> receivers) { 10316 ActivityInfo targetReceiver = null; 10317 10318 final int NR = receivers.size(); 10319 for (int i = 0; i < NR; i++) { 10320 final ResolveInfo info = receivers.get(i); 10321 if (info.activityInfo == null) { 10322 continue; 10323 } 10324 10325 if (packageName.equals(info.activityInfo.packageName)) { 10326 targetReceiver = info.activityInfo; 10327 break; 10328 } 10329 } 10330 10331 if (targetReceiver == null) { 10332 return null; 10333 } 10334 10335 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10336 } 10337 10338 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10339 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10340 if (pkgInfo.verifiers.length == 0) { 10341 return null; 10342 } 10343 10344 final int N = pkgInfo.verifiers.length; 10345 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10346 for (int i = 0; i < N; i++) { 10347 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10348 10349 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10350 receivers); 10351 if (comp == null) { 10352 continue; 10353 } 10354 10355 final int verifierUid = getUidForVerifier(verifierInfo); 10356 if (verifierUid == -1) { 10357 continue; 10358 } 10359 10360 if (DEBUG_VERIFY) { 10361 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10362 + " with the correct signature"); 10363 } 10364 sufficientVerifiers.add(comp); 10365 verificationState.addSufficientVerifier(verifierUid); 10366 } 10367 10368 return sufficientVerifiers; 10369 } 10370 10371 private int getUidForVerifier(VerifierInfo verifierInfo) { 10372 synchronized (mPackages) { 10373 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10374 if (pkg == null) { 10375 return -1; 10376 } else if (pkg.mSignatures.length != 1) { 10377 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10378 + " has more than one signature; ignoring"); 10379 return -1; 10380 } 10381 10382 /* 10383 * If the public key of the package's signature does not match 10384 * our expected public key, then this is a different package and 10385 * we should skip. 10386 */ 10387 10388 final byte[] expectedPublicKey; 10389 try { 10390 final Signature verifierSig = pkg.mSignatures[0]; 10391 final PublicKey publicKey = verifierSig.getPublicKey(); 10392 expectedPublicKey = publicKey.getEncoded(); 10393 } catch (CertificateException e) { 10394 return -1; 10395 } 10396 10397 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10398 10399 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10400 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10401 + " does not have the expected public key; ignoring"); 10402 return -1; 10403 } 10404 10405 return pkg.applicationInfo.uid; 10406 } 10407 } 10408 10409 @Override 10410 public void finishPackageInstall(int token) { 10411 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10412 10413 if (DEBUG_INSTALL) { 10414 Slog.v(TAG, "BM finishing package install for " + token); 10415 } 10416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10417 10418 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10419 mHandler.sendMessage(msg); 10420 } 10421 10422 /** 10423 * Get the verification agent timeout. 10424 * 10425 * @return verification timeout in milliseconds 10426 */ 10427 private long getVerificationTimeout() { 10428 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10429 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10430 DEFAULT_VERIFICATION_TIMEOUT); 10431 } 10432 10433 /** 10434 * Get the default verification agent response code. 10435 * 10436 * @return default verification response code 10437 */ 10438 private int getDefaultVerificationResponse() { 10439 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10440 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10441 DEFAULT_VERIFICATION_RESPONSE); 10442 } 10443 10444 /** 10445 * Check whether or not package verification has been enabled. 10446 * 10447 * @return true if verification should be performed 10448 */ 10449 private boolean isVerificationEnabled(int userId, int installFlags) { 10450 if (!DEFAULT_VERIFY_ENABLE) { 10451 return false; 10452 } 10453 // Ephemeral apps don't get the full verification treatment 10454 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10455 if (DEBUG_EPHEMERAL) { 10456 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10457 } 10458 return false; 10459 } 10460 10461 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10462 10463 // Check if installing from ADB 10464 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10465 // Do not run verification in a test harness environment 10466 if (ActivityManager.isRunningInTestHarness()) { 10467 return false; 10468 } 10469 if (ensureVerifyAppsEnabled) { 10470 return true; 10471 } 10472 // Check if the developer does not want package verification for ADB installs 10473 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10474 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10475 return false; 10476 } 10477 } 10478 10479 if (ensureVerifyAppsEnabled) { 10480 return true; 10481 } 10482 10483 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10484 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10485 } 10486 10487 @Override 10488 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10489 throws RemoteException { 10490 mContext.enforceCallingOrSelfPermission( 10491 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10492 "Only intentfilter verification agents can verify applications"); 10493 10494 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10495 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10496 Binder.getCallingUid(), verificationCode, failedDomains); 10497 msg.arg1 = id; 10498 msg.obj = response; 10499 mHandler.sendMessage(msg); 10500 } 10501 10502 @Override 10503 public int getIntentVerificationStatus(String packageName, int userId) { 10504 synchronized (mPackages) { 10505 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10506 } 10507 } 10508 10509 @Override 10510 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10511 mContext.enforceCallingOrSelfPermission( 10512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10513 10514 boolean result = false; 10515 synchronized (mPackages) { 10516 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10517 } 10518 if (result) { 10519 scheduleWritePackageRestrictionsLocked(userId); 10520 } 10521 return result; 10522 } 10523 10524 @Override 10525 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10526 synchronized (mPackages) { 10527 return mSettings.getIntentFilterVerificationsLPr(packageName); 10528 } 10529 } 10530 10531 @Override 10532 public List<IntentFilter> getAllIntentFilters(String packageName) { 10533 if (TextUtils.isEmpty(packageName)) { 10534 return Collections.<IntentFilter>emptyList(); 10535 } 10536 synchronized (mPackages) { 10537 PackageParser.Package pkg = mPackages.get(packageName); 10538 if (pkg == null || pkg.activities == null) { 10539 return Collections.<IntentFilter>emptyList(); 10540 } 10541 final int count = pkg.activities.size(); 10542 ArrayList<IntentFilter> result = new ArrayList<>(); 10543 for (int n=0; n<count; n++) { 10544 PackageParser.Activity activity = pkg.activities.get(n); 10545 if (activity.intents != null && activity.intents.size() > 0) { 10546 result.addAll(activity.intents); 10547 } 10548 } 10549 return result; 10550 } 10551 } 10552 10553 @Override 10554 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10555 mContext.enforceCallingOrSelfPermission( 10556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10557 10558 synchronized (mPackages) { 10559 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10560 if (packageName != null) { 10561 result |= updateIntentVerificationStatus(packageName, 10562 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10563 userId); 10564 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10565 packageName, userId); 10566 } 10567 return result; 10568 } 10569 } 10570 10571 @Override 10572 public String getDefaultBrowserPackageName(int userId) { 10573 synchronized (mPackages) { 10574 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10575 } 10576 } 10577 10578 /** 10579 * Get the "allow unknown sources" setting. 10580 * 10581 * @return the current "allow unknown sources" setting 10582 */ 10583 private int getUnknownSourcesSettings() { 10584 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10585 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10586 -1); 10587 } 10588 10589 @Override 10590 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10591 final int uid = Binder.getCallingUid(); 10592 // writer 10593 synchronized (mPackages) { 10594 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10595 if (targetPackageSetting == null) { 10596 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10597 } 10598 10599 PackageSetting installerPackageSetting; 10600 if (installerPackageName != null) { 10601 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 10602 if (installerPackageSetting == null) { 10603 throw new IllegalArgumentException("Unknown installer package: " 10604 + installerPackageName); 10605 } 10606 } else { 10607 installerPackageSetting = null; 10608 } 10609 10610 Signature[] callerSignature; 10611 Object obj = mSettings.getUserIdLPr(uid); 10612 if (obj != null) { 10613 if (obj instanceof SharedUserSetting) { 10614 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 10615 } else if (obj instanceof PackageSetting) { 10616 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 10617 } else { 10618 throw new SecurityException("Bad object " + obj + " for uid " + uid); 10619 } 10620 } else { 10621 throw new SecurityException("Unknown calling UID: " + uid); 10622 } 10623 10624 // Verify: can't set installerPackageName to a package that is 10625 // not signed with the same cert as the caller. 10626 if (installerPackageSetting != null) { 10627 if (compareSignatures(callerSignature, 10628 installerPackageSetting.signatures.mSignatures) 10629 != PackageManager.SIGNATURE_MATCH) { 10630 throw new SecurityException( 10631 "Caller does not have same cert as new installer package " 10632 + installerPackageName); 10633 } 10634 } 10635 10636 // Verify: if target already has an installer package, it must 10637 // be signed with the same cert as the caller. 10638 if (targetPackageSetting.installerPackageName != null) { 10639 PackageSetting setting = mSettings.mPackages.get( 10640 targetPackageSetting.installerPackageName); 10641 // If the currently set package isn't valid, then it's always 10642 // okay to change it. 10643 if (setting != null) { 10644 if (compareSignatures(callerSignature, 10645 setting.signatures.mSignatures) 10646 != PackageManager.SIGNATURE_MATCH) { 10647 throw new SecurityException( 10648 "Caller does not have same cert as old installer package " 10649 + targetPackageSetting.installerPackageName); 10650 } 10651 } 10652 } 10653 10654 // Okay! 10655 targetPackageSetting.installerPackageName = installerPackageName; 10656 scheduleWriteSettingsLocked(); 10657 } 10658 } 10659 10660 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 10661 // Queue up an async operation since the package installation may take a little while. 10662 mHandler.post(new Runnable() { 10663 public void run() { 10664 mHandler.removeCallbacks(this); 10665 // Result object to be returned 10666 PackageInstalledInfo res = new PackageInstalledInfo(); 10667 res.returnCode = currentStatus; 10668 res.uid = -1; 10669 res.pkg = null; 10670 res.removedInfo = new PackageRemovedInfo(); 10671 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10672 args.doPreInstall(res.returnCode); 10673 synchronized (mInstallLock) { 10674 installPackageTracedLI(args, res); 10675 } 10676 args.doPostInstall(res.returnCode, res.uid); 10677 } 10678 10679 // A restore should be performed at this point if (a) the install 10680 // succeeded, (b) the operation is not an update, and (c) the new 10681 // package has not opted out of backup participation. 10682 final boolean update = res.removedInfo.removedPackage != null; 10683 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 10684 boolean doRestore = !update 10685 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 10686 10687 // Set up the post-install work request bookkeeping. This will be used 10688 // and cleaned up by the post-install event handling regardless of whether 10689 // there's a restore pass performed. Token values are >= 1. 10690 int token; 10691 if (mNextInstallToken < 0) mNextInstallToken = 1; 10692 token = mNextInstallToken++; 10693 10694 PostInstallData data = new PostInstallData(args, res); 10695 mRunningInstalls.put(token, data); 10696 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 10697 10698 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 10699 // Pass responsibility to the Backup Manager. It will perform a 10700 // restore if appropriate, then pass responsibility back to the 10701 // Package Manager to run the post-install observer callbacks 10702 // and broadcasts. 10703 IBackupManager bm = IBackupManager.Stub.asInterface( 10704 ServiceManager.getService(Context.BACKUP_SERVICE)); 10705 if (bm != null) { 10706 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 10707 + " to BM for possible restore"); 10708 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10709 try { 10710 // TODO: http://b/22388012 10711 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 10712 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 10713 } else { 10714 doRestore = false; 10715 } 10716 } catch (RemoteException e) { 10717 // can't happen; the backup manager is local 10718 } catch (Exception e) { 10719 Slog.e(TAG, "Exception trying to enqueue restore", e); 10720 doRestore = false; 10721 } 10722 } else { 10723 Slog.e(TAG, "Backup Manager not found!"); 10724 doRestore = false; 10725 } 10726 } 10727 10728 if (!doRestore) { 10729 // No restore possible, or the Backup Manager was mysteriously not 10730 // available -- just fire the post-install work request directly. 10731 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 10732 10733 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 10734 10735 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10736 mHandler.sendMessage(msg); 10737 } 10738 } 10739 }); 10740 } 10741 10742 private abstract class HandlerParams { 10743 private static final int MAX_RETRIES = 4; 10744 10745 /** 10746 * Number of times startCopy() has been attempted and had a non-fatal 10747 * error. 10748 */ 10749 private int mRetries = 0; 10750 10751 /** User handle for the user requesting the information or installation. */ 10752 private final UserHandle mUser; 10753 String traceMethod; 10754 int traceCookie; 10755 10756 HandlerParams(UserHandle user) { 10757 mUser = user; 10758 } 10759 10760 UserHandle getUser() { 10761 return mUser; 10762 } 10763 10764 HandlerParams setTraceMethod(String traceMethod) { 10765 this.traceMethod = traceMethod; 10766 return this; 10767 } 10768 10769 HandlerParams setTraceCookie(int traceCookie) { 10770 this.traceCookie = traceCookie; 10771 return this; 10772 } 10773 10774 final boolean startCopy() { 10775 boolean res; 10776 try { 10777 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 10778 10779 if (++mRetries > MAX_RETRIES) { 10780 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 10781 mHandler.sendEmptyMessage(MCS_GIVE_UP); 10782 handleServiceError(); 10783 return false; 10784 } else { 10785 handleStartCopy(); 10786 res = true; 10787 } 10788 } catch (RemoteException e) { 10789 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 10790 mHandler.sendEmptyMessage(MCS_RECONNECT); 10791 res = false; 10792 } 10793 handleReturnCode(); 10794 return res; 10795 } 10796 10797 final void serviceError() { 10798 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 10799 handleServiceError(); 10800 handleReturnCode(); 10801 } 10802 10803 abstract void handleStartCopy() throws RemoteException; 10804 abstract void handleServiceError(); 10805 abstract void handleReturnCode(); 10806 } 10807 10808 class MeasureParams extends HandlerParams { 10809 private final PackageStats mStats; 10810 private boolean mSuccess; 10811 10812 private final IPackageStatsObserver mObserver; 10813 10814 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 10815 super(new UserHandle(stats.userHandle)); 10816 mObserver = observer; 10817 mStats = stats; 10818 } 10819 10820 @Override 10821 public String toString() { 10822 return "MeasureParams{" 10823 + Integer.toHexString(System.identityHashCode(this)) 10824 + " " + mStats.packageName + "}"; 10825 } 10826 10827 @Override 10828 void handleStartCopy() throws RemoteException { 10829 synchronized (mInstallLock) { 10830 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 10831 } 10832 10833 if (mSuccess) { 10834 final boolean mounted; 10835 if (Environment.isExternalStorageEmulated()) { 10836 mounted = true; 10837 } else { 10838 final String status = Environment.getExternalStorageState(); 10839 mounted = (Environment.MEDIA_MOUNTED.equals(status) 10840 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 10841 } 10842 10843 if (mounted) { 10844 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 10845 10846 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 10847 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 10848 10849 mStats.externalDataSize = calculateDirectorySize(mContainerService, 10850 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 10851 10852 // Always subtract cache size, since it's a subdirectory 10853 mStats.externalDataSize -= mStats.externalCacheSize; 10854 10855 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 10856 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 10857 10858 mStats.externalObbSize = calculateDirectorySize(mContainerService, 10859 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 10860 } 10861 } 10862 } 10863 10864 @Override 10865 void handleReturnCode() { 10866 if (mObserver != null) { 10867 try { 10868 mObserver.onGetStatsCompleted(mStats, mSuccess); 10869 } catch (RemoteException e) { 10870 Slog.i(TAG, "Observer no longer exists."); 10871 } 10872 } 10873 } 10874 10875 @Override 10876 void handleServiceError() { 10877 Slog.e(TAG, "Could not measure application " + mStats.packageName 10878 + " external storage"); 10879 } 10880 } 10881 10882 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 10883 throws RemoteException { 10884 long result = 0; 10885 for (File path : paths) { 10886 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 10887 } 10888 return result; 10889 } 10890 10891 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 10892 for (File path : paths) { 10893 try { 10894 mcs.clearDirectory(path.getAbsolutePath()); 10895 } catch (RemoteException e) { 10896 } 10897 } 10898 } 10899 10900 static class OriginInfo { 10901 /** 10902 * Location where install is coming from, before it has been 10903 * copied/renamed into place. This could be a single monolithic APK 10904 * file, or a cluster directory. This location may be untrusted. 10905 */ 10906 final File file; 10907 final String cid; 10908 10909 /** 10910 * Flag indicating that {@link #file} or {@link #cid} has already been 10911 * staged, meaning downstream users don't need to defensively copy the 10912 * contents. 10913 */ 10914 final boolean staged; 10915 10916 /** 10917 * Flag indicating that {@link #file} or {@link #cid} is an already 10918 * installed app that is being moved. 10919 */ 10920 final boolean existing; 10921 10922 final String resolvedPath; 10923 final File resolvedFile; 10924 10925 static OriginInfo fromNothing() { 10926 return new OriginInfo(null, null, false, false); 10927 } 10928 10929 static OriginInfo fromUntrustedFile(File file) { 10930 return new OriginInfo(file, null, false, false); 10931 } 10932 10933 static OriginInfo fromExistingFile(File file) { 10934 return new OriginInfo(file, null, false, true); 10935 } 10936 10937 static OriginInfo fromStagedFile(File file) { 10938 return new OriginInfo(file, null, true, false); 10939 } 10940 10941 static OriginInfo fromStagedContainer(String cid) { 10942 return new OriginInfo(null, cid, true, false); 10943 } 10944 10945 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 10946 this.file = file; 10947 this.cid = cid; 10948 this.staged = staged; 10949 this.existing = existing; 10950 10951 if (cid != null) { 10952 resolvedPath = PackageHelper.getSdDir(cid); 10953 resolvedFile = new File(resolvedPath); 10954 } else if (file != null) { 10955 resolvedPath = file.getAbsolutePath(); 10956 resolvedFile = file; 10957 } else { 10958 resolvedPath = null; 10959 resolvedFile = null; 10960 } 10961 } 10962 } 10963 10964 static class MoveInfo { 10965 final int moveId; 10966 final String fromUuid; 10967 final String toUuid; 10968 final String packageName; 10969 final String dataAppName; 10970 final int appId; 10971 final String seinfo; 10972 final int targetSdkVersion; 10973 10974 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 10975 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 10976 this.moveId = moveId; 10977 this.fromUuid = fromUuid; 10978 this.toUuid = toUuid; 10979 this.packageName = packageName; 10980 this.dataAppName = dataAppName; 10981 this.appId = appId; 10982 this.seinfo = seinfo; 10983 this.targetSdkVersion = targetSdkVersion; 10984 } 10985 } 10986 10987 class InstallParams extends HandlerParams { 10988 final OriginInfo origin; 10989 final MoveInfo move; 10990 final IPackageInstallObserver2 observer; 10991 int installFlags; 10992 final String installerPackageName; 10993 final String volumeUuid; 10994 final VerificationParams verificationParams; 10995 private InstallArgs mArgs; 10996 private int mRet; 10997 final String packageAbiOverride; 10998 final String[] grantedRuntimePermissions; 10999 11000 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11001 int installFlags, String installerPackageName, String volumeUuid, 11002 VerificationParams verificationParams, UserHandle user, String packageAbiOverride, 11003 String[] grantedPermissions) { 11004 super(user); 11005 this.origin = origin; 11006 this.move = move; 11007 this.observer = observer; 11008 this.installFlags = installFlags; 11009 this.installerPackageName = installerPackageName; 11010 this.volumeUuid = volumeUuid; 11011 this.verificationParams = verificationParams; 11012 this.packageAbiOverride = packageAbiOverride; 11013 this.grantedRuntimePermissions = grantedPermissions; 11014 } 11015 11016 @Override 11017 public String toString() { 11018 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11019 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11020 } 11021 11022 private int installLocationPolicy(PackageInfoLite pkgLite) { 11023 String packageName = pkgLite.packageName; 11024 int installLocation = pkgLite.installLocation; 11025 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11026 // reader 11027 synchronized (mPackages) { 11028 PackageParser.Package pkg = mPackages.get(packageName); 11029 if (pkg != null) { 11030 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11031 // Check for downgrading. 11032 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11033 try { 11034 checkDowngrade(pkg, pkgLite); 11035 } catch (PackageManagerException e) { 11036 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11037 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11038 } 11039 } 11040 // Check for updated system application. 11041 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11042 if (onSd) { 11043 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11044 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11045 } 11046 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11047 } else { 11048 if (onSd) { 11049 // Install flag overrides everything. 11050 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11051 } 11052 // If current upgrade specifies particular preference 11053 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11054 // Application explicitly specified internal. 11055 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11056 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11057 // App explictly prefers external. Let policy decide 11058 } else { 11059 // Prefer previous location 11060 if (isExternal(pkg)) { 11061 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11062 } 11063 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11064 } 11065 } 11066 } else { 11067 // Invalid install. Return error code 11068 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11069 } 11070 } 11071 } 11072 // All the special cases have been taken care of. 11073 // Return result based on recommended install location. 11074 if (onSd) { 11075 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11076 } 11077 return pkgLite.recommendedInstallLocation; 11078 } 11079 11080 /* 11081 * Invoke remote method to get package information and install 11082 * location values. Override install location based on default 11083 * policy if needed and then create install arguments based 11084 * on the install location. 11085 */ 11086 public void handleStartCopy() throws RemoteException { 11087 int ret = PackageManager.INSTALL_SUCCEEDED; 11088 11089 // If we're already staged, we've firmly committed to an install location 11090 if (origin.staged) { 11091 if (origin.file != null) { 11092 installFlags |= PackageManager.INSTALL_INTERNAL; 11093 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11094 } else if (origin.cid != null) { 11095 installFlags |= PackageManager.INSTALL_EXTERNAL; 11096 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11097 } else { 11098 throw new IllegalStateException("Invalid stage location"); 11099 } 11100 } 11101 11102 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11103 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11104 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11105 PackageInfoLite pkgLite = null; 11106 11107 if (onInt && onSd) { 11108 // Check if both bits are set. 11109 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11110 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11111 } else if (onSd && ephemeral) { 11112 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11113 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11114 } else { 11115 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11116 packageAbiOverride); 11117 11118 if (DEBUG_EPHEMERAL && ephemeral) { 11119 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11120 } 11121 11122 /* 11123 * If we have too little free space, try to free cache 11124 * before giving up. 11125 */ 11126 if (!origin.staged && pkgLite.recommendedInstallLocation 11127 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11128 // TODO: focus freeing disk space on the target device 11129 final StorageManager storage = StorageManager.from(mContext); 11130 final long lowThreshold = storage.getStorageLowBytes( 11131 Environment.getDataDirectory()); 11132 11133 final long sizeBytes = mContainerService.calculateInstalledSize( 11134 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11135 11136 try { 11137 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11138 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11139 installFlags, packageAbiOverride); 11140 } catch (InstallerException e) { 11141 Slog.w(TAG, "Failed to free cache", e); 11142 } 11143 11144 /* 11145 * The cache free must have deleted the file we 11146 * downloaded to install. 11147 * 11148 * TODO: fix the "freeCache" call to not delete 11149 * the file we care about. 11150 */ 11151 if (pkgLite.recommendedInstallLocation 11152 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11153 pkgLite.recommendedInstallLocation 11154 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11155 } 11156 } 11157 } 11158 11159 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11160 int loc = pkgLite.recommendedInstallLocation; 11161 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11162 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11163 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11164 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11165 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11166 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11167 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11168 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11169 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11170 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11171 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11172 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11173 } else { 11174 // Override with defaults if needed. 11175 loc = installLocationPolicy(pkgLite); 11176 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11177 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11178 } else if (!onSd && !onInt) { 11179 // Override install location with flags 11180 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11181 // Set the flag to install on external media. 11182 installFlags |= PackageManager.INSTALL_EXTERNAL; 11183 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11184 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11185 if (DEBUG_EPHEMERAL) { 11186 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11187 } 11188 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11189 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11190 |PackageManager.INSTALL_INTERNAL); 11191 } else { 11192 // Make sure the flag for installing on external 11193 // media is unset 11194 installFlags |= PackageManager.INSTALL_INTERNAL; 11195 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11196 } 11197 } 11198 } 11199 } 11200 11201 final InstallArgs args = createInstallArgs(this); 11202 mArgs = args; 11203 11204 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11205 // TODO: http://b/22976637 11206 // Apps installed for "all" users use the device owner to verify the app 11207 UserHandle verifierUser = getUser(); 11208 if (verifierUser == UserHandle.ALL) { 11209 verifierUser = UserHandle.SYSTEM; 11210 } 11211 11212 /* 11213 * Determine if we have any installed package verifiers. If we 11214 * do, then we'll defer to them to verify the packages. 11215 */ 11216 final int requiredUid = mRequiredVerifierPackage == null ? -1 11217 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11218 verifierUser.getIdentifier()); 11219 if (!origin.existing && requiredUid != -1 11220 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11221 final Intent verification = new Intent( 11222 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11223 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11224 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11225 PACKAGE_MIME_TYPE); 11226 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11227 11228 // Query all live verifiers based on current user state 11229 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11230 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11231 11232 if (DEBUG_VERIFY) { 11233 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11234 + verification.toString() + " with " + pkgLite.verifiers.length 11235 + " optional verifiers"); 11236 } 11237 11238 final int verificationId = mPendingVerificationToken++; 11239 11240 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11241 11242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11243 installerPackageName); 11244 11245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11246 installFlags); 11247 11248 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11249 pkgLite.packageName); 11250 11251 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11252 pkgLite.versionCode); 11253 11254 if (verificationParams != null) { 11255 if (verificationParams.getVerificationURI() != null) { 11256 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 11257 verificationParams.getVerificationURI()); 11258 } 11259 if (verificationParams.getOriginatingURI() != null) { 11260 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11261 verificationParams.getOriginatingURI()); 11262 } 11263 if (verificationParams.getReferrer() != null) { 11264 verification.putExtra(Intent.EXTRA_REFERRER, 11265 verificationParams.getReferrer()); 11266 } 11267 if (verificationParams.getOriginatingUid() >= 0) { 11268 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11269 verificationParams.getOriginatingUid()); 11270 } 11271 if (verificationParams.getInstallerUid() >= 0) { 11272 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11273 verificationParams.getInstallerUid()); 11274 } 11275 } 11276 11277 final PackageVerificationState verificationState = new PackageVerificationState( 11278 requiredUid, args); 11279 11280 mPendingVerification.append(verificationId, verificationState); 11281 11282 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11283 receivers, verificationState); 11284 11285 /* 11286 * If any sufficient verifiers were listed in the package 11287 * manifest, attempt to ask them. 11288 */ 11289 if (sufficientVerifiers != null) { 11290 final int N = sufficientVerifiers.size(); 11291 if (N == 0) { 11292 Slog.i(TAG, "Additional verifiers required, but none installed."); 11293 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11294 } else { 11295 for (int i = 0; i < N; i++) { 11296 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11297 11298 final Intent sufficientIntent = new Intent(verification); 11299 sufficientIntent.setComponent(verifierComponent); 11300 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11301 } 11302 } 11303 } 11304 11305 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11306 mRequiredVerifierPackage, receivers); 11307 if (ret == PackageManager.INSTALL_SUCCEEDED 11308 && mRequiredVerifierPackage != null) { 11309 Trace.asyncTraceBegin( 11310 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11311 /* 11312 * Send the intent to the required verification agent, 11313 * but only start the verification timeout after the 11314 * target BroadcastReceivers have run. 11315 */ 11316 verification.setComponent(requiredVerifierComponent); 11317 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11318 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11319 new BroadcastReceiver() { 11320 @Override 11321 public void onReceive(Context context, Intent intent) { 11322 final Message msg = mHandler 11323 .obtainMessage(CHECK_PENDING_VERIFICATION); 11324 msg.arg1 = verificationId; 11325 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11326 } 11327 }, null, 0, null, null); 11328 11329 /* 11330 * We don't want the copy to proceed until verification 11331 * succeeds, so null out this field. 11332 */ 11333 mArgs = null; 11334 } 11335 } else { 11336 /* 11337 * No package verification is enabled, so immediately start 11338 * the remote call to initiate copy using temporary file. 11339 */ 11340 ret = args.copyApk(mContainerService, true); 11341 } 11342 } 11343 11344 mRet = ret; 11345 } 11346 11347 @Override 11348 void handleReturnCode() { 11349 // If mArgs is null, then MCS couldn't be reached. When it 11350 // reconnects, it will try again to install. At that point, this 11351 // will succeed. 11352 if (mArgs != null) { 11353 processPendingInstall(mArgs, mRet); 11354 } 11355 } 11356 11357 @Override 11358 void handleServiceError() { 11359 mArgs = createInstallArgs(this); 11360 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11361 } 11362 11363 public boolean isForwardLocked() { 11364 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11365 } 11366 } 11367 11368 /** 11369 * Used during creation of InstallArgs 11370 * 11371 * @param installFlags package installation flags 11372 * @return true if should be installed on external storage 11373 */ 11374 private static boolean installOnExternalAsec(int installFlags) { 11375 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11376 return false; 11377 } 11378 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11379 return true; 11380 } 11381 return false; 11382 } 11383 11384 /** 11385 * Used during creation of InstallArgs 11386 * 11387 * @param installFlags package installation flags 11388 * @return true if should be installed as forward locked 11389 */ 11390 private static boolean installForwardLocked(int installFlags) { 11391 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11392 } 11393 11394 private InstallArgs createInstallArgs(InstallParams params) { 11395 if (params.move != null) { 11396 return new MoveInstallArgs(params); 11397 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11398 return new AsecInstallArgs(params); 11399 } else { 11400 return new FileInstallArgs(params); 11401 } 11402 } 11403 11404 /** 11405 * Create args that describe an existing installed package. Typically used 11406 * when cleaning up old installs, or used as a move source. 11407 */ 11408 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11409 String resourcePath, String[] instructionSets) { 11410 final boolean isInAsec; 11411 if (installOnExternalAsec(installFlags)) { 11412 /* Apps on SD card are always in ASEC containers. */ 11413 isInAsec = true; 11414 } else if (installForwardLocked(installFlags) 11415 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11416 /* 11417 * Forward-locked apps are only in ASEC containers if they're the 11418 * new style 11419 */ 11420 isInAsec = true; 11421 } else { 11422 isInAsec = false; 11423 } 11424 11425 if (isInAsec) { 11426 return new AsecInstallArgs(codePath, instructionSets, 11427 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11428 } else { 11429 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11430 } 11431 } 11432 11433 static abstract class InstallArgs { 11434 /** @see InstallParams#origin */ 11435 final OriginInfo origin; 11436 /** @see InstallParams#move */ 11437 final MoveInfo move; 11438 11439 final IPackageInstallObserver2 observer; 11440 // Always refers to PackageManager flags only 11441 final int installFlags; 11442 final String installerPackageName; 11443 final String volumeUuid; 11444 final UserHandle user; 11445 final String abiOverride; 11446 final String[] installGrantPermissions; 11447 /** If non-null, drop an async trace when the install completes */ 11448 final String traceMethod; 11449 final int traceCookie; 11450 11451 // The list of instruction sets supported by this app. This is currently 11452 // only used during the rmdex() phase to clean up resources. We can get rid of this 11453 // if we move dex files under the common app path. 11454 /* nullable */ String[] instructionSets; 11455 11456 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11457 int installFlags, String installerPackageName, String volumeUuid, 11458 UserHandle user, String[] instructionSets, 11459 String abiOverride, String[] installGrantPermissions, 11460 String traceMethod, int traceCookie) { 11461 this.origin = origin; 11462 this.move = move; 11463 this.installFlags = installFlags; 11464 this.observer = observer; 11465 this.installerPackageName = installerPackageName; 11466 this.volumeUuid = volumeUuid; 11467 this.user = user; 11468 this.instructionSets = instructionSets; 11469 this.abiOverride = abiOverride; 11470 this.installGrantPermissions = installGrantPermissions; 11471 this.traceMethod = traceMethod; 11472 this.traceCookie = traceCookie; 11473 } 11474 11475 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11476 abstract int doPreInstall(int status); 11477 11478 /** 11479 * Rename package into final resting place. All paths on the given 11480 * scanned package should be updated to reflect the rename. 11481 */ 11482 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11483 abstract int doPostInstall(int status, int uid); 11484 11485 /** @see PackageSettingBase#codePathString */ 11486 abstract String getCodePath(); 11487 /** @see PackageSettingBase#resourcePathString */ 11488 abstract String getResourcePath(); 11489 11490 // Need installer lock especially for dex file removal. 11491 abstract void cleanUpResourcesLI(); 11492 abstract boolean doPostDeleteLI(boolean delete); 11493 11494 /** 11495 * Called before the source arguments are copied. This is used mostly 11496 * for MoveParams when it needs to read the source file to put it in the 11497 * destination. 11498 */ 11499 int doPreCopy() { 11500 return PackageManager.INSTALL_SUCCEEDED; 11501 } 11502 11503 /** 11504 * Called after the source arguments are copied. This is used mostly for 11505 * MoveParams when it needs to read the source file to put it in the 11506 * destination. 11507 * 11508 * @return 11509 */ 11510 int doPostCopy(int uid) { 11511 return PackageManager.INSTALL_SUCCEEDED; 11512 } 11513 11514 protected boolean isFwdLocked() { 11515 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11516 } 11517 11518 protected boolean isExternalAsec() { 11519 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11520 } 11521 11522 protected boolean isEphemeral() { 11523 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11524 } 11525 11526 UserHandle getUser() { 11527 return user; 11528 } 11529 } 11530 11531 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11532 if (!allCodePaths.isEmpty()) { 11533 if (instructionSets == null) { 11534 throw new IllegalStateException("instructionSet == null"); 11535 } 11536 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11537 for (String codePath : allCodePaths) { 11538 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11539 try { 11540 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11541 } catch (InstallerException ignored) { 11542 } 11543 } 11544 } 11545 } 11546 } 11547 11548 /** 11549 * Logic to handle installation of non-ASEC applications, including copying 11550 * and renaming logic. 11551 */ 11552 class FileInstallArgs extends InstallArgs { 11553 private File codeFile; 11554 private File resourceFile; 11555 11556 // Example topology: 11557 // /data/app/com.example/base.apk 11558 // /data/app/com.example/split_foo.apk 11559 // /data/app/com.example/lib/arm/libfoo.so 11560 // /data/app/com.example/lib/arm64/libfoo.so 11561 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11562 11563 /** New install */ 11564 FileInstallArgs(InstallParams params) { 11565 super(params.origin, params.move, params.observer, params.installFlags, 11566 params.installerPackageName, params.volumeUuid, 11567 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11568 params.grantedRuntimePermissions, 11569 params.traceMethod, params.traceCookie); 11570 if (isFwdLocked()) { 11571 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11572 } 11573 } 11574 11575 /** Existing install */ 11576 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11577 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11578 null, null, null, 0); 11579 this.codeFile = (codePath != null) ? new File(codePath) : null; 11580 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 11581 } 11582 11583 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 11585 try { 11586 return doCopyApk(imcs, temp); 11587 } finally { 11588 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11589 } 11590 } 11591 11592 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11593 if (origin.staged) { 11594 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 11595 codeFile = origin.file; 11596 resourceFile = origin.file; 11597 return PackageManager.INSTALL_SUCCEEDED; 11598 } 11599 11600 try { 11601 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11602 final File tempDir = 11603 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 11604 codeFile = tempDir; 11605 resourceFile = tempDir; 11606 } catch (IOException e) { 11607 Slog.w(TAG, "Failed to create copy file: " + e); 11608 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11609 } 11610 11611 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 11612 @Override 11613 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 11614 if (!FileUtils.isValidExtFilename(name)) { 11615 throw new IllegalArgumentException("Invalid filename: " + name); 11616 } 11617 try { 11618 final File file = new File(codeFile, name); 11619 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 11620 O_RDWR | O_CREAT, 0644); 11621 Os.chmod(file.getAbsolutePath(), 0644); 11622 return new ParcelFileDescriptor(fd); 11623 } catch (ErrnoException e) { 11624 throw new RemoteException("Failed to open: " + e.getMessage()); 11625 } 11626 } 11627 }; 11628 11629 int ret = PackageManager.INSTALL_SUCCEEDED; 11630 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 11631 if (ret != PackageManager.INSTALL_SUCCEEDED) { 11632 Slog.e(TAG, "Failed to copy package"); 11633 return ret; 11634 } 11635 11636 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 11637 NativeLibraryHelper.Handle handle = null; 11638 try { 11639 handle = NativeLibraryHelper.Handle.create(codeFile); 11640 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 11641 abiOverride); 11642 } catch (IOException e) { 11643 Slog.e(TAG, "Copying native libraries failed", e); 11644 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11645 } finally { 11646 IoUtils.closeQuietly(handle); 11647 } 11648 11649 return ret; 11650 } 11651 11652 int doPreInstall(int status) { 11653 if (status != PackageManager.INSTALL_SUCCEEDED) { 11654 cleanUp(); 11655 } 11656 return status; 11657 } 11658 11659 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11660 if (status != PackageManager.INSTALL_SUCCEEDED) { 11661 cleanUp(); 11662 return false; 11663 } 11664 11665 final File targetDir = codeFile.getParentFile(); 11666 final File beforeCodeFile = codeFile; 11667 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 11668 11669 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 11670 try { 11671 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 11672 } catch (ErrnoException e) { 11673 Slog.w(TAG, "Failed to rename", e); 11674 return false; 11675 } 11676 11677 if (!SELinux.restoreconRecursive(afterCodeFile)) { 11678 Slog.w(TAG, "Failed to restorecon"); 11679 return false; 11680 } 11681 11682 // Reflect the rename internally 11683 codeFile = afterCodeFile; 11684 resourceFile = afterCodeFile; 11685 11686 // Reflect the rename in scanned details 11687 pkg.codePath = afterCodeFile.getAbsolutePath(); 11688 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11689 pkg.baseCodePath); 11690 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11691 pkg.splitCodePaths); 11692 11693 // Reflect the rename in app info 11694 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11695 pkg.applicationInfo.setCodePath(pkg.codePath); 11696 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11697 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11698 pkg.applicationInfo.setResourcePath(pkg.codePath); 11699 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11700 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11701 11702 return true; 11703 } 11704 11705 int doPostInstall(int status, int uid) { 11706 if (status != PackageManager.INSTALL_SUCCEEDED) { 11707 cleanUp(); 11708 } 11709 return status; 11710 } 11711 11712 @Override 11713 String getCodePath() { 11714 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11715 } 11716 11717 @Override 11718 String getResourcePath() { 11719 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11720 } 11721 11722 private boolean cleanUp() { 11723 if (codeFile == null || !codeFile.exists()) { 11724 return false; 11725 } 11726 11727 removeCodePathLI(codeFile); 11728 11729 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11730 resourceFile.delete(); 11731 } 11732 11733 return true; 11734 } 11735 11736 void cleanUpResourcesLI() { 11737 // Try enumerating all code paths before deleting 11738 List<String> allCodePaths = Collections.EMPTY_LIST; 11739 if (codeFile != null && codeFile.exists()) { 11740 try { 11741 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 11742 allCodePaths = pkg.getAllCodePaths(); 11743 } catch (PackageParserException e) { 11744 // Ignored; we tried our best 11745 } 11746 } 11747 11748 cleanUp(); 11749 removeDexFiles(allCodePaths, instructionSets); 11750 } 11751 11752 boolean doPostDeleteLI(boolean delete) { 11753 // XXX err, shouldn't we respect the delete flag? 11754 cleanUpResourcesLI(); 11755 return true; 11756 } 11757 } 11758 11759 private boolean isAsecExternal(String cid) { 11760 final String asecPath = PackageHelper.getSdFilesystem(cid); 11761 return !asecPath.startsWith(mAsecInternalPath); 11762 } 11763 11764 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 11765 PackageManagerException { 11766 if (copyRet < 0) { 11767 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 11768 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 11769 throw new PackageManagerException(copyRet, message); 11770 } 11771 } 11772 } 11773 11774 /** 11775 * Extract the MountService "container ID" from the full code path of an 11776 * .apk. 11777 */ 11778 static String cidFromCodePath(String fullCodePath) { 11779 int eidx = fullCodePath.lastIndexOf("/"); 11780 String subStr1 = fullCodePath.substring(0, eidx); 11781 int sidx = subStr1.lastIndexOf("/"); 11782 return subStr1.substring(sidx+1, eidx); 11783 } 11784 11785 /** 11786 * Logic to handle installation of ASEC applications, including copying and 11787 * renaming logic. 11788 */ 11789 class AsecInstallArgs extends InstallArgs { 11790 static final String RES_FILE_NAME = "pkg.apk"; 11791 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 11792 11793 String cid; 11794 String packagePath; 11795 String resourcePath; 11796 11797 /** New install */ 11798 AsecInstallArgs(InstallParams params) { 11799 super(params.origin, params.move, params.observer, params.installFlags, 11800 params.installerPackageName, params.volumeUuid, 11801 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11802 params.grantedRuntimePermissions, 11803 params.traceMethod, params.traceCookie); 11804 } 11805 11806 /** Existing install */ 11807 AsecInstallArgs(String fullCodePath, String[] instructionSets, 11808 boolean isExternal, boolean isForwardLocked) { 11809 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 11810 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11811 instructionSets, null, null, null, 0); 11812 // Hackily pretend we're still looking at a full code path 11813 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 11814 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 11815 } 11816 11817 // Extract cid from fullCodePath 11818 int eidx = fullCodePath.lastIndexOf("/"); 11819 String subStr1 = fullCodePath.substring(0, eidx); 11820 int sidx = subStr1.lastIndexOf("/"); 11821 cid = subStr1.substring(sidx+1, eidx); 11822 setMountPath(subStr1); 11823 } 11824 11825 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 11826 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 11827 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 11828 instructionSets, null, null, null, 0); 11829 this.cid = cid; 11830 setMountPath(PackageHelper.getSdDir(cid)); 11831 } 11832 11833 void createCopyFile() { 11834 cid = mInstallerService.allocateExternalStageCidLegacy(); 11835 } 11836 11837 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 11838 if (origin.staged && origin.cid != null) { 11839 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 11840 cid = origin.cid; 11841 setMountPath(PackageHelper.getSdDir(cid)); 11842 return PackageManager.INSTALL_SUCCEEDED; 11843 } 11844 11845 if (temp) { 11846 createCopyFile(); 11847 } else { 11848 /* 11849 * Pre-emptively destroy the container since it's destroyed if 11850 * copying fails due to it existing anyway. 11851 */ 11852 PackageHelper.destroySdDir(cid); 11853 } 11854 11855 final String newMountPath = imcs.copyPackageToContainer( 11856 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 11857 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 11858 11859 if (newMountPath != null) { 11860 setMountPath(newMountPath); 11861 return PackageManager.INSTALL_SUCCEEDED; 11862 } else { 11863 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11864 } 11865 } 11866 11867 @Override 11868 String getCodePath() { 11869 return packagePath; 11870 } 11871 11872 @Override 11873 String getResourcePath() { 11874 return resourcePath; 11875 } 11876 11877 int doPreInstall(int status) { 11878 if (status != PackageManager.INSTALL_SUCCEEDED) { 11879 // Destroy container 11880 PackageHelper.destroySdDir(cid); 11881 } else { 11882 boolean mounted = PackageHelper.isContainerMounted(cid); 11883 if (!mounted) { 11884 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 11885 Process.SYSTEM_UID); 11886 if (newMountPath != null) { 11887 setMountPath(newMountPath); 11888 } else { 11889 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11890 } 11891 } 11892 } 11893 return status; 11894 } 11895 11896 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11897 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 11898 String newMountPath = null; 11899 if (PackageHelper.isContainerMounted(cid)) { 11900 // Unmount the container 11901 if (!PackageHelper.unMountSdDir(cid)) { 11902 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 11903 return false; 11904 } 11905 } 11906 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11907 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 11908 " which might be stale. Will try to clean up."); 11909 // Clean up the stale container and proceed to recreate. 11910 if (!PackageHelper.destroySdDir(newCacheId)) { 11911 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 11912 return false; 11913 } 11914 // Successfully cleaned up stale container. Try to rename again. 11915 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 11916 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 11917 + " inspite of cleaning it up."); 11918 return false; 11919 } 11920 } 11921 if (!PackageHelper.isContainerMounted(newCacheId)) { 11922 Slog.w(TAG, "Mounting container " + newCacheId); 11923 newMountPath = PackageHelper.mountSdDir(newCacheId, 11924 getEncryptKey(), Process.SYSTEM_UID); 11925 } else { 11926 newMountPath = PackageHelper.getSdDir(newCacheId); 11927 } 11928 if (newMountPath == null) { 11929 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 11930 return false; 11931 } 11932 Log.i(TAG, "Succesfully renamed " + cid + 11933 " to " + newCacheId + 11934 " at new path: " + newMountPath); 11935 cid = newCacheId; 11936 11937 final File beforeCodeFile = new File(packagePath); 11938 setMountPath(newMountPath); 11939 final File afterCodeFile = new File(packagePath); 11940 11941 // Reflect the rename in scanned details 11942 pkg.codePath = afterCodeFile.getAbsolutePath(); 11943 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11944 pkg.baseCodePath); 11945 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 11946 pkg.splitCodePaths); 11947 11948 // Reflect the rename in app info 11949 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11950 pkg.applicationInfo.setCodePath(pkg.codePath); 11951 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11952 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11953 pkg.applicationInfo.setResourcePath(pkg.codePath); 11954 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11955 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11956 11957 return true; 11958 } 11959 11960 private void setMountPath(String mountPath) { 11961 final File mountFile = new File(mountPath); 11962 11963 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 11964 if (monolithicFile.exists()) { 11965 packagePath = monolithicFile.getAbsolutePath(); 11966 if (isFwdLocked()) { 11967 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 11968 } else { 11969 resourcePath = packagePath; 11970 } 11971 } else { 11972 packagePath = mountFile.getAbsolutePath(); 11973 resourcePath = packagePath; 11974 } 11975 } 11976 11977 int doPostInstall(int status, int uid) { 11978 if (status != PackageManager.INSTALL_SUCCEEDED) { 11979 cleanUp(); 11980 } else { 11981 final int groupOwner; 11982 final String protectedFile; 11983 if (isFwdLocked()) { 11984 groupOwner = UserHandle.getSharedAppGid(uid); 11985 protectedFile = RES_FILE_NAME; 11986 } else { 11987 groupOwner = -1; 11988 protectedFile = null; 11989 } 11990 11991 if (uid < Process.FIRST_APPLICATION_UID 11992 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 11993 Slog.e(TAG, "Failed to finalize " + cid); 11994 PackageHelper.destroySdDir(cid); 11995 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11996 } 11997 11998 boolean mounted = PackageHelper.isContainerMounted(cid); 11999 if (!mounted) { 12000 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12001 } 12002 } 12003 return status; 12004 } 12005 12006 private void cleanUp() { 12007 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12008 12009 // Destroy secure container 12010 PackageHelper.destroySdDir(cid); 12011 } 12012 12013 private List<String> getAllCodePaths() { 12014 final File codeFile = new File(getCodePath()); 12015 if (codeFile != null && codeFile.exists()) { 12016 try { 12017 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12018 return pkg.getAllCodePaths(); 12019 } catch (PackageParserException e) { 12020 // Ignored; we tried our best 12021 } 12022 } 12023 return Collections.EMPTY_LIST; 12024 } 12025 12026 void cleanUpResourcesLI() { 12027 // Enumerate all code paths before deleting 12028 cleanUpResourcesLI(getAllCodePaths()); 12029 } 12030 12031 private void cleanUpResourcesLI(List<String> allCodePaths) { 12032 cleanUp(); 12033 removeDexFiles(allCodePaths, instructionSets); 12034 } 12035 12036 String getPackageName() { 12037 return getAsecPackageName(cid); 12038 } 12039 12040 boolean doPostDeleteLI(boolean delete) { 12041 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12042 final List<String> allCodePaths = getAllCodePaths(); 12043 boolean mounted = PackageHelper.isContainerMounted(cid); 12044 if (mounted) { 12045 // Unmount first 12046 if (PackageHelper.unMountSdDir(cid)) { 12047 mounted = false; 12048 } 12049 } 12050 if (!mounted && delete) { 12051 cleanUpResourcesLI(allCodePaths); 12052 } 12053 return !mounted; 12054 } 12055 12056 @Override 12057 int doPreCopy() { 12058 if (isFwdLocked()) { 12059 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12060 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12061 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12062 } 12063 } 12064 12065 return PackageManager.INSTALL_SUCCEEDED; 12066 } 12067 12068 @Override 12069 int doPostCopy(int uid) { 12070 if (isFwdLocked()) { 12071 if (uid < Process.FIRST_APPLICATION_UID 12072 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12073 RES_FILE_NAME)) { 12074 Slog.e(TAG, "Failed to finalize " + cid); 12075 PackageHelper.destroySdDir(cid); 12076 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12077 } 12078 } 12079 12080 return PackageManager.INSTALL_SUCCEEDED; 12081 } 12082 } 12083 12084 /** 12085 * Logic to handle movement of existing installed applications. 12086 */ 12087 class MoveInstallArgs extends InstallArgs { 12088 private File codeFile; 12089 private File resourceFile; 12090 12091 /** New install */ 12092 MoveInstallArgs(InstallParams params) { 12093 super(params.origin, params.move, params.observer, params.installFlags, 12094 params.installerPackageName, params.volumeUuid, 12095 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12096 params.grantedRuntimePermissions, 12097 params.traceMethod, params.traceCookie); 12098 } 12099 12100 int copyApk(IMediaContainerService imcs, boolean temp) { 12101 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12102 + move.fromUuid + " to " + move.toUuid); 12103 synchronized (mInstaller) { 12104 try { 12105 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12106 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12107 } catch (InstallerException e) { 12108 Slog.w(TAG, "Failed to move app", e); 12109 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12110 } 12111 } 12112 12113 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12114 resourceFile = codeFile; 12115 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12116 12117 return PackageManager.INSTALL_SUCCEEDED; 12118 } 12119 12120 int doPreInstall(int status) { 12121 if (status != PackageManager.INSTALL_SUCCEEDED) { 12122 cleanUp(move.toUuid); 12123 } 12124 return status; 12125 } 12126 12127 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12128 if (status != PackageManager.INSTALL_SUCCEEDED) { 12129 cleanUp(move.toUuid); 12130 return false; 12131 } 12132 12133 // Reflect the move in app info 12134 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 12135 pkg.applicationInfo.setCodePath(pkg.codePath); 12136 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 12137 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 12138 pkg.applicationInfo.setResourcePath(pkg.codePath); 12139 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 12140 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 12141 12142 return true; 12143 } 12144 12145 int doPostInstall(int status, int uid) { 12146 if (status == PackageManager.INSTALL_SUCCEEDED) { 12147 cleanUp(move.fromUuid); 12148 } else { 12149 cleanUp(move.toUuid); 12150 } 12151 return status; 12152 } 12153 12154 @Override 12155 String getCodePath() { 12156 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12157 } 12158 12159 @Override 12160 String getResourcePath() { 12161 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12162 } 12163 12164 private boolean cleanUp(String volumeUuid) { 12165 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12166 move.dataAppName); 12167 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12168 synchronized (mInstallLock) { 12169 // Clean up both app data and code 12170 removeDataDirsLI(volumeUuid, move.packageName); 12171 removeCodePathLI(codeFile); 12172 } 12173 return true; 12174 } 12175 12176 void cleanUpResourcesLI() { 12177 throw new UnsupportedOperationException(); 12178 } 12179 12180 boolean doPostDeleteLI(boolean delete) { 12181 throw new UnsupportedOperationException(); 12182 } 12183 } 12184 12185 static String getAsecPackageName(String packageCid) { 12186 int idx = packageCid.lastIndexOf("-"); 12187 if (idx == -1) { 12188 return packageCid; 12189 } 12190 return packageCid.substring(0, idx); 12191 } 12192 12193 // Utility method used to create code paths based on package name and available index. 12194 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12195 String idxStr = ""; 12196 int idx = 1; 12197 // Fall back to default value of idx=1 if prefix is not 12198 // part of oldCodePath 12199 if (oldCodePath != null) { 12200 String subStr = oldCodePath; 12201 // Drop the suffix right away 12202 if (suffix != null && subStr.endsWith(suffix)) { 12203 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12204 } 12205 // If oldCodePath already contains prefix find out the 12206 // ending index to either increment or decrement. 12207 int sidx = subStr.lastIndexOf(prefix); 12208 if (sidx != -1) { 12209 subStr = subStr.substring(sidx + prefix.length()); 12210 if (subStr != null) { 12211 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12212 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12213 } 12214 try { 12215 idx = Integer.parseInt(subStr); 12216 if (idx <= 1) { 12217 idx++; 12218 } else { 12219 idx--; 12220 } 12221 } catch(NumberFormatException e) { 12222 } 12223 } 12224 } 12225 } 12226 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12227 return prefix + idxStr; 12228 } 12229 12230 private File getNextCodePath(File targetDir, String packageName) { 12231 int suffix = 1; 12232 File result; 12233 do { 12234 result = new File(targetDir, packageName + "-" + suffix); 12235 suffix++; 12236 } while (result.exists()); 12237 return result; 12238 } 12239 12240 // Utility method that returns the relative package path with respect 12241 // to the installation directory. Like say for /data/data/com.test-1.apk 12242 // string com.test-1 is returned. 12243 static String deriveCodePathName(String codePath) { 12244 if (codePath == null) { 12245 return null; 12246 } 12247 final File codeFile = new File(codePath); 12248 final String name = codeFile.getName(); 12249 if (codeFile.isDirectory()) { 12250 return name; 12251 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12252 final int lastDot = name.lastIndexOf('.'); 12253 return name.substring(0, lastDot); 12254 } else { 12255 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12256 return null; 12257 } 12258 } 12259 12260 static class PackageInstalledInfo { 12261 String name; 12262 int uid; 12263 // The set of users that originally had this package installed. 12264 int[] origUsers; 12265 // The set of users that now have this package installed. 12266 int[] newUsers; 12267 PackageParser.Package pkg; 12268 int returnCode; 12269 String returnMsg; 12270 PackageRemovedInfo removedInfo; 12271 12272 public void setError(int code, String msg) { 12273 returnCode = code; 12274 returnMsg = msg; 12275 Slog.w(TAG, msg); 12276 } 12277 12278 public void setError(String msg, PackageParserException e) { 12279 returnCode = e.error; 12280 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12281 Slog.w(TAG, msg, e); 12282 } 12283 12284 public void setError(String msg, PackageManagerException e) { 12285 returnCode = e.error; 12286 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12287 Slog.w(TAG, msg, e); 12288 } 12289 12290 // In some error cases we want to convey more info back to the observer 12291 String origPackage; 12292 String origPermission; 12293 } 12294 12295 /* 12296 * Install a non-existing package. 12297 */ 12298 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12299 UserHandle user, String installerPackageName, String volumeUuid, 12300 PackageInstalledInfo res) { 12301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12302 12303 // Remember this for later, in case we need to rollback this install 12304 String pkgName = pkg.packageName; 12305 12306 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12307 // TODO: b/23350563 12308 final boolean dataDirExists = Environment 12309 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12310 12311 synchronized(mPackages) { 12312 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12313 // A package with the same name is already installed, though 12314 // it has been renamed to an older name. The package we 12315 // are trying to install should be installed as an update to 12316 // the existing one, but that has not been requested, so bail. 12317 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12318 + " without first uninstalling package running as " 12319 + mSettings.mRenamedPackages.get(pkgName)); 12320 return; 12321 } 12322 if (mPackages.containsKey(pkgName)) { 12323 // Don't allow installation over an existing package with the same name. 12324 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12325 + " without first uninstalling."); 12326 return; 12327 } 12328 } 12329 12330 try { 12331 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12332 System.currentTimeMillis(), user); 12333 12334 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 12335 prepareAppDataAfterInstall(newPackage); 12336 12337 // delete the partially installed application. the data directory will have to be 12338 // restored if it was already existing 12339 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12340 // remove package from internal structures. Note that we want deletePackageX to 12341 // delete the package data and cache directories that it created in 12342 // scanPackageLocked, unless those directories existed before we even tried to 12343 // install. 12344 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12345 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12346 res.removedInfo, true); 12347 } 12348 12349 } catch (PackageManagerException e) { 12350 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12351 } 12352 12353 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12354 } 12355 12356 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12357 // Can't rotate keys during boot or if sharedUser. 12358 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12359 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12360 return false; 12361 } 12362 // app is using upgradeKeySets; make sure all are valid 12363 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12364 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12365 for (int i = 0; i < upgradeKeySets.length; i++) { 12366 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12367 Slog.wtf(TAG, "Package " 12368 + (oldPs.name != null ? oldPs.name : "<null>") 12369 + " contains upgrade-key-set reference to unknown key-set: " 12370 + upgradeKeySets[i] 12371 + " reverting to signatures check."); 12372 return false; 12373 } 12374 } 12375 return true; 12376 } 12377 12378 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12379 // Upgrade keysets are being used. Determine if new package has a superset of the 12380 // required keys. 12381 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12382 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12383 for (int i = 0; i < upgradeKeySets.length; i++) { 12384 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12385 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12386 return true; 12387 } 12388 } 12389 return false; 12390 } 12391 12392 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12393 UserHandle user, String installerPackageName, String volumeUuid, 12394 PackageInstalledInfo res) { 12395 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12396 12397 final PackageParser.Package oldPackage; 12398 final String pkgName = pkg.packageName; 12399 final int[] allUsers; 12400 final boolean[] perUserInstalled; 12401 12402 // First find the old package info and check signatures 12403 synchronized(mPackages) { 12404 oldPackage = mPackages.get(pkgName); 12405 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12406 if (isEphemeral && !oldIsEphemeral) { 12407 // can't downgrade from full to ephemeral 12408 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12409 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12410 return; 12411 } 12412 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12413 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12414 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12415 if(!checkUpgradeKeySetLP(ps, pkg)) { 12416 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12417 "New package not signed by keys specified by upgrade-keysets: " 12418 + pkgName); 12419 return; 12420 } 12421 } else { 12422 // default to original signature matching 12423 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12424 != PackageManager.SIGNATURE_MATCH) { 12425 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12426 "New package has a different signature: " + pkgName); 12427 return; 12428 } 12429 } 12430 12431 // In case of rollback, remember per-user/profile install state 12432 allUsers = sUserManager.getUserIds(); 12433 perUserInstalled = new boolean[allUsers.length]; 12434 for (int i = 0; i < allUsers.length; i++) { 12435 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12436 } 12437 } 12438 12439 boolean sysPkg = (isSystemApp(oldPackage)); 12440 if (sysPkg) { 12441 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12442 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12443 } else { 12444 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12445 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 12446 } 12447 } 12448 12449 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12450 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12451 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12452 String volumeUuid, PackageInstalledInfo res) { 12453 String pkgName = deletedPackage.packageName; 12454 boolean deletedPkg = true; 12455 boolean updatedSettings = false; 12456 12457 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12458 + deletedPackage); 12459 long origUpdateTime; 12460 if (pkg.mExtras != null) { 12461 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 12462 } else { 12463 origUpdateTime = 0; 12464 } 12465 12466 // First delete the existing package while retaining the data directory 12467 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12468 res.removedInfo, true)) { 12469 // If the existing package wasn't successfully deleted 12470 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12471 deletedPkg = false; 12472 } else { 12473 // Successfully deleted the old package; proceed with replace. 12474 12475 // If deleted package lived in a container, give users a chance to 12476 // relinquish resources before killing. 12477 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12478 if (DEBUG_INSTALL) { 12479 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12480 } 12481 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12482 final ArrayList<String> pkgList = new ArrayList<String>(1); 12483 pkgList.add(deletedPackage.applicationInfo.packageName); 12484 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12485 } 12486 12487 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 12488 try { 12489 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12490 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12491 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12492 perUserInstalled, res, user); 12493 prepareAppDataAfterInstall(newPackage); 12494 updatedSettings = true; 12495 } catch (PackageManagerException e) { 12496 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12497 } 12498 } 12499 12500 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12501 // remove package from internal structures. Note that we want deletePackageX to 12502 // delete the package data and cache directories that it created in 12503 // scanPackageLocked, unless those directories existed before we even tried to 12504 // install. 12505 if(updatedSettings) { 12506 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12507 deletePackageLI( 12508 pkgName, null, true, allUsers, perUserInstalled, 12509 PackageManager.DELETE_KEEP_DATA, 12510 res.removedInfo, true); 12511 } 12512 // Since we failed to install the new package we need to restore the old 12513 // package that we deleted. 12514 if (deletedPkg) { 12515 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12516 File restoreFile = new File(deletedPackage.codePath); 12517 // Parse old package 12518 boolean oldExternal = isExternal(deletedPackage); 12519 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12520 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12521 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12522 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12523 try { 12524 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12525 null); 12526 } catch (PackageManagerException e) { 12527 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12528 + e.getMessage()); 12529 return; 12530 } 12531 // Restore of old package succeeded. Update permissions. 12532 // writer 12533 synchronized (mPackages) { 12534 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 12535 UPDATE_PERMISSIONS_ALL); 12536 // can downgrade to reader 12537 mSettings.writeLPr(); 12538 } 12539 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12540 } 12541 } 12542 } 12543 12544 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12545 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12546 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12547 String volumeUuid, PackageInstalledInfo res) { 12548 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12549 + ", old=" + deletedPackage); 12550 boolean disabledSystem = false; 12551 boolean updatedSettings = false; 12552 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12553 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12554 != 0) { 12555 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12556 } 12557 String packageName = deletedPackage.packageName; 12558 if (packageName == null) { 12559 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12560 "Attempt to delete null packageName."); 12561 return; 12562 } 12563 PackageParser.Package oldPkg; 12564 PackageSetting oldPkgSetting; 12565 // reader 12566 synchronized (mPackages) { 12567 oldPkg = mPackages.get(packageName); 12568 oldPkgSetting = mSettings.mPackages.get(packageName); 12569 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 12570 (oldPkgSetting == null)) { 12571 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 12572 "Couldn't find package " + packageName + " information"); 12573 return; 12574 } 12575 } 12576 12577 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 12578 12579 res.removedInfo.uid = oldPkg.applicationInfo.uid; 12580 res.removedInfo.removedPackage = packageName; 12581 // Remove existing system package 12582 removePackageLI(oldPkgSetting, true); 12583 // writer 12584 synchronized (mPackages) { 12585 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 12586 if (!disabledSystem && deletedPackage != null) { 12587 // We didn't need to disable the .apk as a current system package, 12588 // which means we are replacing another update that is already 12589 // installed. We need to make sure to delete the older one's .apk. 12590 res.removedInfo.args = createInstallArgsForExisting(0, 12591 deletedPackage.applicationInfo.getCodePath(), 12592 deletedPackage.applicationInfo.getResourcePath(), 12593 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12594 } else { 12595 res.removedInfo.args = null; 12596 } 12597 } 12598 12599 // Successfully disabled the old package. Now proceed with re-installation 12600 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 12601 12602 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12603 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 12604 12605 PackageParser.Package newPackage = null; 12606 try { 12607 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 12608 if (newPackage.mExtras != null) { 12609 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 12610 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 12611 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 12612 12613 // is the update attempting to change shared user? that isn't going to work... 12614 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 12615 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 12616 "Forbidding shared user change from " + oldPkgSetting.sharedUser 12617 + " to " + newPkgSetting.sharedUser); 12618 updatedSettings = true; 12619 } 12620 } 12621 12622 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12623 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 12624 perUserInstalled, res, user); 12625 prepareAppDataAfterInstall(newPackage); 12626 updatedSettings = true; 12627 } 12628 12629 } catch (PackageManagerException e) { 12630 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12631 } 12632 12633 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12634 // Re installation failed. Restore old information 12635 // Remove new pkg information 12636 if (newPackage != null) { 12637 removeInstalledPackageLI(newPackage, true); 12638 } 12639 // Add back the old system package 12640 try { 12641 scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 12642 } catch (PackageManagerException e) { 12643 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 12644 } 12645 // Restore the old system information in Settings 12646 synchronized (mPackages) { 12647 if (disabledSystem) { 12648 mSettings.enableSystemPackageLPw(packageName); 12649 } 12650 if (updatedSettings) { 12651 mSettings.setInstallerPackageName(packageName, 12652 oldPkgSetting.installerPackageName); 12653 } 12654 mSettings.writeLPr(); 12655 } 12656 } 12657 } 12658 12659 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 12660 // Collect all used permissions in the UID 12661 ArraySet<String> usedPermissions = new ArraySet<>(); 12662 final int packageCount = su.packages.size(); 12663 for (int i = 0; i < packageCount; i++) { 12664 PackageSetting ps = su.packages.valueAt(i); 12665 if (ps.pkg == null) { 12666 continue; 12667 } 12668 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 12669 for (int j = 0; j < requestedPermCount; j++) { 12670 String permission = ps.pkg.requestedPermissions.get(j); 12671 BasePermission bp = mSettings.mPermissions.get(permission); 12672 if (bp != null) { 12673 usedPermissions.add(permission); 12674 } 12675 } 12676 } 12677 12678 PermissionsState permissionsState = su.getPermissionsState(); 12679 // Prune install permissions 12680 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 12681 final int installPermCount = installPermStates.size(); 12682 for (int i = installPermCount - 1; i >= 0; i--) { 12683 PermissionState permissionState = installPermStates.get(i); 12684 if (!usedPermissions.contains(permissionState.getName())) { 12685 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12686 if (bp != null) { 12687 permissionsState.revokeInstallPermission(bp); 12688 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 12689 PackageManager.MASK_PERMISSION_FLAGS, 0); 12690 } 12691 } 12692 } 12693 12694 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 12695 12696 // Prune runtime permissions 12697 for (int userId : allUserIds) { 12698 List<PermissionState> runtimePermStates = permissionsState 12699 .getRuntimePermissionStates(userId); 12700 final int runtimePermCount = runtimePermStates.size(); 12701 for (int i = runtimePermCount - 1; i >= 0; i--) { 12702 PermissionState permissionState = runtimePermStates.get(i); 12703 if (!usedPermissions.contains(permissionState.getName())) { 12704 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 12705 if (bp != null) { 12706 permissionsState.revokeRuntimePermission(bp, userId); 12707 permissionsState.updatePermissionFlags(bp, userId, 12708 PackageManager.MASK_PERMISSION_FLAGS, 0); 12709 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 12710 runtimePermissionChangedUserIds, userId); 12711 } 12712 } 12713 } 12714 } 12715 12716 return runtimePermissionChangedUserIds; 12717 } 12718 12719 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 12720 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 12721 UserHandle user) { 12722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12723 12724 String pkgName = newPackage.packageName; 12725 synchronized (mPackages) { 12726 //write settings. the installStatus will be incomplete at this stage. 12727 //note that the new package setting would have already been 12728 //added to mPackages. It hasn't been persisted yet. 12729 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 12730 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12731 mSettings.writeLPr(); 12732 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12733 } 12734 12735 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 12736 synchronized (mPackages) { 12737 updatePermissionsLPw(newPackage.packageName, newPackage, 12738 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 12739 ? UPDATE_PERMISSIONS_ALL : 0)); 12740 // For system-bundled packages, we assume that installing an upgraded version 12741 // of the package implies that the user actually wants to run that new code, 12742 // so we enable the package. 12743 PackageSetting ps = mSettings.mPackages.get(pkgName); 12744 if (ps != null) { 12745 if (isSystemApp(newPackage)) { 12746 // NB: implicit assumption that system package upgrades apply to all users 12747 if (DEBUG_INSTALL) { 12748 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 12749 } 12750 if (res.origUsers != null) { 12751 for (int userHandle : res.origUsers) { 12752 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 12753 userHandle, installerPackageName); 12754 } 12755 } 12756 // Also convey the prior install/uninstall state 12757 if (allUsers != null && perUserInstalled != null) { 12758 for (int i = 0; i < allUsers.length; i++) { 12759 if (DEBUG_INSTALL) { 12760 Slog.d(TAG, " user " + allUsers[i] 12761 + " => " + perUserInstalled[i]); 12762 } 12763 ps.setInstalled(perUserInstalled[i], allUsers[i]); 12764 } 12765 // these install state changes will be persisted in the 12766 // upcoming call to mSettings.writeLPr(). 12767 } 12768 } 12769 // It's implied that when a user requests installation, they want the app to be 12770 // installed and enabled. 12771 int userId = user.getIdentifier(); 12772 if (userId != UserHandle.USER_ALL) { 12773 ps.setInstalled(true, userId); 12774 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 12775 } 12776 } 12777 res.name = pkgName; 12778 res.uid = newPackage.applicationInfo.uid; 12779 res.pkg = newPackage; 12780 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 12781 mSettings.setInstallerPackageName(pkgName, installerPackageName); 12782 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12783 //to update install status 12784 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 12785 mSettings.writeLPr(); 12786 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12787 } 12788 12789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12790 } 12791 12792 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 12793 try { 12794 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 12795 installPackageLI(args, res); 12796 } finally { 12797 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12798 } 12799 } 12800 12801 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 12802 final int installFlags = args.installFlags; 12803 final String installerPackageName = args.installerPackageName; 12804 final String volumeUuid = args.volumeUuid; 12805 final File tmpPackageFile = new File(args.getCodePath()); 12806 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 12807 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 12808 || (args.volumeUuid != null)); 12809 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 12810 boolean replace = false; 12811 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 12812 if (args.move != null) { 12813 // moving a complete application; perfom an initial scan on the new install location 12814 scanFlags |= SCAN_INITIAL; 12815 } 12816 // Result object to be returned 12817 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 12818 12819 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 12820 12821 // Sanity check 12822 if (ephemeral && (forwardLocked || onExternal)) { 12823 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 12824 + " external=" + onExternal); 12825 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12826 return; 12827 } 12828 12829 // Retrieve PackageSettings and parse package 12830 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 12831 | PackageParser.PARSE_ENFORCE_CODE 12832 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 12833 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 12834 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 12835 PackageParser pp = new PackageParser(); 12836 pp.setSeparateProcesses(mSeparateProcesses); 12837 pp.setDisplayMetrics(mMetrics); 12838 12839 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 12840 final PackageParser.Package pkg; 12841 try { 12842 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 12843 } catch (PackageParserException e) { 12844 res.setError("Failed parse during installPackageLI", e); 12845 return; 12846 } finally { 12847 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12848 } 12849 12850 // If package doesn't declare API override, mark that we have an install 12851 // time CPU ABI override. 12852 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 12853 pkg.cpuAbiOverride = args.abiOverride; 12854 } 12855 12856 String pkgName = res.name = pkg.packageName; 12857 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 12858 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 12859 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 12860 return; 12861 } 12862 } 12863 12864 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 12865 try { 12866 pp.collectCertificates(pkg, parseFlags); 12867 } catch (PackageParserException e) { 12868 res.setError("Failed collect during installPackageLI", e); 12869 return; 12870 } finally { 12871 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12872 } 12873 12874 // Get rid of all references to package scan path via parser. 12875 pp = null; 12876 String oldCodePath = null; 12877 boolean systemApp = false; 12878 synchronized (mPackages) { 12879 // Check if installing already existing package 12880 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12881 String oldName = mSettings.mRenamedPackages.get(pkgName); 12882 if (pkg.mOriginalPackages != null 12883 && pkg.mOriginalPackages.contains(oldName) 12884 && mPackages.containsKey(oldName)) { 12885 // This package is derived from an original package, 12886 // and this device has been updating from that original 12887 // name. We must continue using the original name, so 12888 // rename the new package here. 12889 pkg.setPackageName(oldName); 12890 pkgName = pkg.packageName; 12891 replace = true; 12892 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 12893 + oldName + " pkgName=" + pkgName); 12894 } else if (mPackages.containsKey(pkgName)) { 12895 // This package, under its official name, already exists 12896 // on the device; we should replace it. 12897 replace = true; 12898 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 12899 } 12900 12901 // Prevent apps opting out from runtime permissions 12902 if (replace) { 12903 PackageParser.Package oldPackage = mPackages.get(pkgName); 12904 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 12905 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 12906 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 12907 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 12908 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 12909 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 12910 + " doesn't support runtime permissions but the old" 12911 + " target SDK " + oldTargetSdk + " does."); 12912 return; 12913 } 12914 } 12915 } 12916 12917 PackageSetting ps = mSettings.mPackages.get(pkgName); 12918 if (ps != null) { 12919 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 12920 12921 // Quick sanity check that we're signed correctly if updating; 12922 // we'll check this again later when scanning, but we want to 12923 // bail early here before tripping over redefined permissions. 12924 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12925 if (!checkUpgradeKeySetLP(ps, pkg)) { 12926 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 12927 + pkg.packageName + " upgrade keys do not match the " 12928 + "previously installed version"); 12929 return; 12930 } 12931 } else { 12932 try { 12933 verifySignaturesLP(ps, pkg); 12934 } catch (PackageManagerException e) { 12935 res.setError(e.error, e.getMessage()); 12936 return; 12937 } 12938 } 12939 12940 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 12941 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 12942 systemApp = (ps.pkg.applicationInfo.flags & 12943 ApplicationInfo.FLAG_SYSTEM) != 0; 12944 } 12945 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 12946 } 12947 12948 // Check whether the newly-scanned package wants to define an already-defined perm 12949 int N = pkg.permissions.size(); 12950 for (int i = N-1; i >= 0; i--) { 12951 PackageParser.Permission perm = pkg.permissions.get(i); 12952 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 12953 if (bp != null) { 12954 // If the defining package is signed with our cert, it's okay. This 12955 // also includes the "updating the same package" case, of course. 12956 // "updating same package" could also involve key-rotation. 12957 final boolean sigsOk; 12958 if (bp.sourcePackage.equals(pkg.packageName) 12959 && (bp.packageSetting instanceof PackageSetting) 12960 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 12961 scanFlags))) { 12962 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 12963 } else { 12964 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 12965 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 12966 } 12967 if (!sigsOk) { 12968 // If the owning package is the system itself, we log but allow 12969 // install to proceed; we fail the install on all other permission 12970 // redefinitions. 12971 if (!bp.sourcePackage.equals("android")) { 12972 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 12973 + pkg.packageName + " attempting to redeclare permission " 12974 + perm.info.name + " already owned by " + bp.sourcePackage); 12975 res.origPermission = perm.info.name; 12976 res.origPackage = bp.sourcePackage; 12977 return; 12978 } else { 12979 Slog.w(TAG, "Package " + pkg.packageName 12980 + " attempting to redeclare system permission " 12981 + perm.info.name + "; ignoring new declaration"); 12982 pkg.permissions.remove(i); 12983 } 12984 } 12985 } 12986 } 12987 12988 } 12989 12990 if (systemApp) { 12991 if (onExternal) { 12992 // Abort update; system app can't be replaced with app on sdcard 12993 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 12994 "Cannot install updates to system apps on sdcard"); 12995 return; 12996 } else if (ephemeral) { 12997 // Abort update; system app can't be replaced with an ephemeral app 12998 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 12999 "Cannot update a system app with an ephemeral app"); 13000 return; 13001 } 13002 } 13003 13004 if (args.move != null) { 13005 // We did an in-place move, so dex is ready to roll 13006 scanFlags |= SCAN_NO_DEX; 13007 scanFlags |= SCAN_MOVE; 13008 13009 synchronized (mPackages) { 13010 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13011 if (ps == null) { 13012 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13013 "Missing settings for moved package " + pkgName); 13014 } 13015 13016 // We moved the entire application as-is, so bring over the 13017 // previously derived ABI information. 13018 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13019 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13020 } 13021 13022 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13023 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13024 scanFlags |= SCAN_NO_DEX; 13025 13026 try { 13027 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13028 args.abiOverride : pkg.cpuAbiOverride); 13029 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13030 true /* extract libs */); 13031 } catch (PackageManagerException pme) { 13032 Slog.e(TAG, "Error deriving application ABI", pme); 13033 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13034 return; 13035 } 13036 13037 // Extract package to save the VM unzipping the APK in memory during 13038 // launch. Only do this if profile-guided compilation is enabled because 13039 // otherwise BackgroundDexOptService will not dexopt the package later. 13040 if (mUseJitProfiles) { 13041 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13042 // Do not run PackageDexOptimizer through the local performDexOpt 13043 // method because `pkg` is not in `mPackages` yet. 13044 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13045 false /* inclDependencies */, false /* useProfiles */, 13046 true /* extractOnly */, false /* force */); 13047 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13048 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13049 String msg = "Extracking package failed for " + pkgName; 13050 res.setError(INSTALL_FAILED_DEXOPT, msg); 13051 return; 13052 } 13053 } 13054 } 13055 13056 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13057 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13058 return; 13059 } 13060 13061 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13062 13063 if (replace) { 13064 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13065 installerPackageName, volumeUuid, res); 13066 } else { 13067 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13068 args.user, installerPackageName, volumeUuid, res); 13069 } 13070 synchronized (mPackages) { 13071 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13072 if (ps != null) { 13073 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13074 } 13075 } 13076 } 13077 13078 private void startIntentFilterVerifications(int userId, boolean replacing, 13079 PackageParser.Package pkg) { 13080 if (mIntentFilterVerifierComponent == null) { 13081 Slog.w(TAG, "No IntentFilter verification will not be done as " 13082 + "there is no IntentFilterVerifier available!"); 13083 return; 13084 } 13085 13086 final int verifierUid = getPackageUid( 13087 mIntentFilterVerifierComponent.getPackageName(), 13088 MATCH_DEBUG_TRIAGED_MISSING, 13089 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13090 13091 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13092 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13093 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13094 mHandler.sendMessage(msg); 13095 } 13096 13097 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13098 PackageParser.Package pkg) { 13099 int size = pkg.activities.size(); 13100 if (size == 0) { 13101 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13102 "No activity, so no need to verify any IntentFilter!"); 13103 return; 13104 } 13105 13106 final boolean hasDomainURLs = hasDomainURLs(pkg); 13107 if (!hasDomainURLs) { 13108 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13109 "No domain URLs, so no need to verify any IntentFilter!"); 13110 return; 13111 } 13112 13113 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13114 + " if any IntentFilter from the " + size 13115 + " Activities needs verification ..."); 13116 13117 int count = 0; 13118 final String packageName = pkg.packageName; 13119 13120 synchronized (mPackages) { 13121 // If this is a new install and we see that we've already run verification for this 13122 // package, we have nothing to do: it means the state was restored from backup. 13123 if (!replacing) { 13124 IntentFilterVerificationInfo ivi = 13125 mSettings.getIntentFilterVerificationLPr(packageName); 13126 if (ivi != null) { 13127 if (DEBUG_DOMAIN_VERIFICATION) { 13128 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13129 + ivi.getStatusString()); 13130 } 13131 return; 13132 } 13133 } 13134 13135 // If any filters need to be verified, then all need to be. 13136 boolean needToVerify = false; 13137 for (PackageParser.Activity a : pkg.activities) { 13138 for (ActivityIntentInfo filter : a.intents) { 13139 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13140 if (DEBUG_DOMAIN_VERIFICATION) { 13141 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13142 } 13143 needToVerify = true; 13144 break; 13145 } 13146 } 13147 } 13148 13149 if (needToVerify) { 13150 final int verificationId = mIntentFilterVerificationToken++; 13151 for (PackageParser.Activity a : pkg.activities) { 13152 for (ActivityIntentInfo filter : a.intents) { 13153 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13154 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13155 "Verification needed for IntentFilter:" + filter.toString()); 13156 mIntentFilterVerifier.addOneIntentFilterVerification( 13157 verifierUid, userId, verificationId, filter, packageName); 13158 count++; 13159 } 13160 } 13161 } 13162 } 13163 } 13164 13165 if (count > 0) { 13166 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13167 + " IntentFilter verification" + (count > 1 ? "s" : "") 13168 + " for userId:" + userId); 13169 mIntentFilterVerifier.startVerifications(userId); 13170 } else { 13171 if (DEBUG_DOMAIN_VERIFICATION) { 13172 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13173 } 13174 } 13175 } 13176 13177 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13178 final ComponentName cn = filter.activity.getComponentName(); 13179 final String packageName = cn.getPackageName(); 13180 13181 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13182 packageName); 13183 if (ivi == null) { 13184 return true; 13185 } 13186 int status = ivi.getStatus(); 13187 switch (status) { 13188 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13189 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13190 return true; 13191 13192 default: 13193 // Nothing to do 13194 return false; 13195 } 13196 } 13197 13198 private static boolean isMultiArch(ApplicationInfo info) { 13199 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13200 } 13201 13202 private static boolean isExternal(PackageParser.Package pkg) { 13203 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13204 } 13205 13206 private static boolean isExternal(PackageSetting ps) { 13207 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13208 } 13209 13210 private static boolean isEphemeral(PackageParser.Package pkg) { 13211 return pkg.applicationInfo.isEphemeralApp(); 13212 } 13213 13214 private static boolean isEphemeral(PackageSetting ps) { 13215 return ps.pkg != null && isEphemeral(ps.pkg); 13216 } 13217 13218 private static boolean isSystemApp(PackageParser.Package pkg) { 13219 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13220 } 13221 13222 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13223 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13224 } 13225 13226 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13227 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13228 } 13229 13230 private static boolean isSystemApp(PackageSetting ps) { 13231 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13232 } 13233 13234 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13235 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13236 } 13237 13238 private int packageFlagsToInstallFlags(PackageSetting ps) { 13239 int installFlags = 0; 13240 if (isEphemeral(ps)) { 13241 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13242 } 13243 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13244 // This existing package was an external ASEC install when we have 13245 // the external flag without a UUID 13246 installFlags |= PackageManager.INSTALL_EXTERNAL; 13247 } 13248 if (ps.isForwardLocked()) { 13249 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13250 } 13251 return installFlags; 13252 } 13253 13254 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13255 if (isExternal(pkg)) { 13256 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13257 return StorageManager.UUID_PRIMARY_PHYSICAL; 13258 } else { 13259 return pkg.volumeUuid; 13260 } 13261 } else { 13262 return StorageManager.UUID_PRIVATE_INTERNAL; 13263 } 13264 } 13265 13266 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13267 if (isExternal(pkg)) { 13268 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13269 return mSettings.getExternalVersion(); 13270 } else { 13271 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13272 } 13273 } else { 13274 return mSettings.getInternalVersion(); 13275 } 13276 } 13277 13278 private void deleteTempPackageFiles() { 13279 final FilenameFilter filter = new FilenameFilter() { 13280 public boolean accept(File dir, String name) { 13281 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13282 } 13283 }; 13284 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13285 file.delete(); 13286 } 13287 } 13288 13289 @Override 13290 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13291 int flags) { 13292 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13293 flags); 13294 } 13295 13296 @Override 13297 public void deletePackage(final String packageName, 13298 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13299 mContext.enforceCallingOrSelfPermission( 13300 android.Manifest.permission.DELETE_PACKAGES, null); 13301 Preconditions.checkNotNull(packageName); 13302 Preconditions.checkNotNull(observer); 13303 final int uid = Binder.getCallingUid(); 13304 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13305 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13306 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13307 mContext.enforceCallingOrSelfPermission( 13308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13309 "deletePackage for user " + userId); 13310 } 13311 13312 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13313 try { 13314 observer.onPackageDeleted(packageName, 13315 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13316 } catch (RemoteException re) { 13317 } 13318 return; 13319 } 13320 13321 for (int currentUserId : users) { 13322 if (getBlockUninstallForUser(packageName, currentUserId)) { 13323 try { 13324 observer.onPackageDeleted(packageName, 13325 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13326 } catch (RemoteException re) { 13327 } 13328 return; 13329 } 13330 } 13331 13332 if (DEBUG_REMOVE) { 13333 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13334 } 13335 // Queue up an async operation since the package deletion may take a little while. 13336 mHandler.post(new Runnable() { 13337 public void run() { 13338 mHandler.removeCallbacks(this); 13339 final int returnCode = deletePackageX(packageName, userId, flags); 13340 try { 13341 observer.onPackageDeleted(packageName, returnCode, null); 13342 } catch (RemoteException e) { 13343 Log.i(TAG, "Observer no longer exists."); 13344 } //end catch 13345 } //end run 13346 }); 13347 } 13348 13349 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13350 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13351 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13352 try { 13353 if (dpm != null) { 13354 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13355 /* callingUserOnly =*/ false); 13356 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13357 : deviceOwnerComponentName.getPackageName(); 13358 // Does the package contains the device owner? 13359 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13360 // this check is probably not needed, since DO should be registered as a device 13361 // admin on some user too. (Original bug for this: b/17657954) 13362 if (packageName.equals(deviceOwnerPackageName)) { 13363 return true; 13364 } 13365 // Does it contain a device admin for any user? 13366 int[] users; 13367 if (userId == UserHandle.USER_ALL) { 13368 users = sUserManager.getUserIds(); 13369 } else { 13370 users = new int[]{userId}; 13371 } 13372 for (int i = 0; i < users.length; ++i) { 13373 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13374 return true; 13375 } 13376 } 13377 } 13378 } catch (RemoteException e) { 13379 } 13380 return false; 13381 } 13382 13383 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13384 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13385 } 13386 13387 /** 13388 * This method is an internal method that could be get invoked either 13389 * to delete an installed package or to clean up a failed installation. 13390 * After deleting an installed package, a broadcast is sent to notify any 13391 * listeners that the package has been installed. For cleaning up a failed 13392 * installation, the broadcast is not necessary since the package's 13393 * installation wouldn't have sent the initial broadcast either 13394 * The key steps in deleting a package are 13395 * deleting the package information in internal structures like mPackages, 13396 * deleting the packages base directories through installd 13397 * updating mSettings to reflect current status 13398 * persisting settings for later use 13399 * sending a broadcast if necessary 13400 */ 13401 private int deletePackageX(String packageName, int userId, int flags) { 13402 final PackageRemovedInfo info = new PackageRemovedInfo(); 13403 final boolean res; 13404 13405 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13406 ? UserHandle.ALL : new UserHandle(userId); 13407 13408 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13409 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13410 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13411 } 13412 13413 boolean removedForAllUsers = false; 13414 boolean systemUpdate = false; 13415 13416 PackageParser.Package uninstalledPkg; 13417 13418 // for the uninstall-updates case and restricted profiles, remember the per- 13419 // userhandle installed state 13420 int[] allUsers; 13421 boolean[] perUserInstalled; 13422 synchronized (mPackages) { 13423 uninstalledPkg = mPackages.get(packageName); 13424 PackageSetting ps = mSettings.mPackages.get(packageName); 13425 allUsers = sUserManager.getUserIds(); 13426 perUserInstalled = new boolean[allUsers.length]; 13427 for (int i = 0; i < allUsers.length; i++) { 13428 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13429 } 13430 } 13431 13432 synchronized (mInstallLock) { 13433 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13434 res = deletePackageLI(packageName, removeForUser, 13435 true, allUsers, perUserInstalled, 13436 flags | REMOVE_CHATTY, info, true); 13437 systemUpdate = info.isRemovedPackageSystemUpdate; 13438 synchronized (mPackages) { 13439 if (res) { 13440 if (!systemUpdate && mPackages.get(packageName) == null) { 13441 removedForAllUsers = true; 13442 } 13443 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13444 } 13445 } 13446 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13447 + " removedForAllUsers=" + removedForAllUsers); 13448 } 13449 13450 if (res) { 13451 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13452 13453 // If the removed package was a system update, the old system package 13454 // was re-enabled; we need to broadcast this information 13455 if (systemUpdate) { 13456 Bundle extras = new Bundle(1); 13457 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 13458 ? info.removedAppId : info.uid); 13459 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13460 13461 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 13462 extras, 0, null, null, null); 13463 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 13464 extras, 0, null, null, null); 13465 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 13466 null, 0, packageName, null, null); 13467 } 13468 } 13469 // Force a gc here. 13470 Runtime.getRuntime().gc(); 13471 // Delete the resources here after sending the broadcast to let 13472 // other processes clean up before deleting resources. 13473 if (info.args != null) { 13474 synchronized (mInstallLock) { 13475 info.args.doPostDeleteLI(true); 13476 } 13477 } 13478 13479 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 13480 } 13481 13482 class PackageRemovedInfo { 13483 String removedPackage; 13484 int uid = -1; 13485 int removedAppId = -1; 13486 int[] removedUsers = null; 13487 boolean isRemovedPackageSystemUpdate = false; 13488 // Clean up resources deleted packages. 13489 InstallArgs args = null; 13490 13491 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 13492 Bundle extras = new Bundle(1); 13493 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 13494 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 13495 if (replacing) { 13496 extras.putBoolean(Intent.EXTRA_REPLACING, true); 13497 } 13498 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 13499 if (removedPackage != null) { 13500 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 13501 extras, 0, null, null, removedUsers); 13502 if (fullRemove && !replacing) { 13503 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 13504 extras, 0, null, null, removedUsers); 13505 } 13506 } 13507 if (removedAppId >= 0) { 13508 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 13509 removedUsers); 13510 } 13511 } 13512 } 13513 13514 /* 13515 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 13516 * flag is not set, the data directory is removed as well. 13517 * make sure this flag is set for partially installed apps. If not its meaningless to 13518 * delete a partially installed application. 13519 */ 13520 private void removePackageDataLI(PackageSetting ps, 13521 int[] allUserHandles, boolean[] perUserInstalled, 13522 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 13523 String packageName = ps.name; 13524 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 13525 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 13526 // Retrieve object to delete permissions for shared user later on 13527 final PackageSetting deletedPs; 13528 // reader 13529 synchronized (mPackages) { 13530 deletedPs = mSettings.mPackages.get(packageName); 13531 if (outInfo != null) { 13532 outInfo.removedPackage = packageName; 13533 outInfo.removedUsers = deletedPs != null 13534 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 13535 : null; 13536 } 13537 } 13538 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13539 removeDataDirsLI(ps.volumeUuid, packageName); 13540 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 13541 } 13542 // writer 13543 synchronized (mPackages) { 13544 if (deletedPs != null) { 13545 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 13546 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 13547 clearDefaultBrowserIfNeeded(packageName); 13548 if (outInfo != null) { 13549 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 13550 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 13551 } 13552 updatePermissionsLPw(deletedPs.name, null, 0); 13553 if (deletedPs.sharedUser != null) { 13554 // Remove permissions associated with package. Since runtime 13555 // permissions are per user we have to kill the removed package 13556 // or packages running under the shared user of the removed 13557 // package if revoking the permissions requested only by the removed 13558 // package is successful and this causes a change in gids. 13559 for (int userId : UserManagerService.getInstance().getUserIds()) { 13560 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 13561 userId); 13562 if (userIdToKill == UserHandle.USER_ALL 13563 || userIdToKill >= UserHandle.USER_SYSTEM) { 13564 // If gids changed for this user, kill all affected packages. 13565 mHandler.post(new Runnable() { 13566 @Override 13567 public void run() { 13568 // This has to happen with no lock held. 13569 killApplication(deletedPs.name, deletedPs.appId, 13570 KILL_APP_REASON_GIDS_CHANGED); 13571 } 13572 }); 13573 break; 13574 } 13575 } 13576 } 13577 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 13578 } 13579 // make sure to preserve per-user disabled state if this removal was just 13580 // a downgrade of a system app to the factory package 13581 if (allUserHandles != null && perUserInstalled != null) { 13582 if (DEBUG_REMOVE) { 13583 Slog.d(TAG, "Propagating install state across downgrade"); 13584 } 13585 for (int i = 0; i < allUserHandles.length; i++) { 13586 if (DEBUG_REMOVE) { 13587 Slog.d(TAG, " user " + allUserHandles[i] 13588 + " => " + perUserInstalled[i]); 13589 } 13590 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13591 } 13592 } 13593 } 13594 // can downgrade to reader 13595 if (writeSettings) { 13596 // Save settings now 13597 mSettings.writeLPr(); 13598 } 13599 } 13600 if (outInfo != null) { 13601 // A user ID was deleted here. Go through all users and remove it 13602 // from KeyStore. 13603 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 13604 } 13605 } 13606 13607 static boolean locationIsPrivileged(File path) { 13608 try { 13609 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 13610 .getCanonicalPath(); 13611 return path.getCanonicalPath().startsWith(privilegedAppDir); 13612 } catch (IOException e) { 13613 Slog.e(TAG, "Unable to access code path " + path); 13614 } 13615 return false; 13616 } 13617 13618 /* 13619 * Tries to delete system package. 13620 */ 13621 private boolean deleteSystemPackageLI(PackageSetting newPs, 13622 int[] allUserHandles, boolean[] perUserInstalled, 13623 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 13624 final boolean applyUserRestrictions 13625 = (allUserHandles != null) && (perUserInstalled != null); 13626 PackageSetting disabledPs = null; 13627 // Confirm if the system package has been updated 13628 // An updated system app can be deleted. This will also have to restore 13629 // the system pkg from system partition 13630 // reader 13631 synchronized (mPackages) { 13632 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 13633 } 13634 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 13635 + " disabledPs=" + disabledPs); 13636 if (disabledPs == null) { 13637 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 13638 return false; 13639 } else if (DEBUG_REMOVE) { 13640 Slog.d(TAG, "Deleting system pkg from data partition"); 13641 } 13642 if (DEBUG_REMOVE) { 13643 if (applyUserRestrictions) { 13644 Slog.d(TAG, "Remembering install states:"); 13645 for (int i = 0; i < allUserHandles.length; i++) { 13646 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 13647 } 13648 } 13649 } 13650 // Delete the updated package 13651 outInfo.isRemovedPackageSystemUpdate = true; 13652 if (disabledPs.versionCode < newPs.versionCode) { 13653 // Delete data for downgrades 13654 flags &= ~PackageManager.DELETE_KEEP_DATA; 13655 } else { 13656 // Preserve data by setting flag 13657 flags |= PackageManager.DELETE_KEEP_DATA; 13658 } 13659 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 13660 allUserHandles, perUserInstalled, outInfo, writeSettings); 13661 if (!ret) { 13662 return false; 13663 } 13664 // writer 13665 synchronized (mPackages) { 13666 // Reinstate the old system package 13667 mSettings.enableSystemPackageLPw(newPs.name); 13668 // Remove any native libraries from the upgraded package. 13669 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 13670 } 13671 // Install the system package 13672 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 13673 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 13674 if (locationIsPrivileged(disabledPs.codePath)) { 13675 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13676 } 13677 13678 final PackageParser.Package newPkg; 13679 try { 13680 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 13681 } catch (PackageManagerException e) { 13682 Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage()); 13683 return false; 13684 } 13685 13686 prepareAppDataAfterInstall(newPkg); 13687 13688 // writer 13689 synchronized (mPackages) { 13690 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 13691 13692 // Propagate the permissions state as we do not want to drop on the floor 13693 // runtime permissions. The update permissions method below will take 13694 // care of removing obsolete permissions and grant install permissions. 13695 ps.getPermissionsState().copyFrom(newPs.getPermissionsState()); 13696 updatePermissionsLPw(newPkg.packageName, newPkg, 13697 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 13698 13699 if (applyUserRestrictions) { 13700 if (DEBUG_REMOVE) { 13701 Slog.d(TAG, "Propagating install state across reinstall"); 13702 } 13703 for (int i = 0; i < allUserHandles.length; i++) { 13704 if (DEBUG_REMOVE) { 13705 Slog.d(TAG, " user " + allUserHandles[i] 13706 + " => " + perUserInstalled[i]); 13707 } 13708 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 13709 13710 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 13711 } 13712 // Regardless of writeSettings we need to ensure that this restriction 13713 // state propagation is persisted 13714 mSettings.writeAllUsersPackageRestrictionsLPr(); 13715 } 13716 // can downgrade to reader here 13717 if (writeSettings) { 13718 mSettings.writeLPr(); 13719 } 13720 } 13721 return true; 13722 } 13723 13724 private boolean deleteInstalledPackageLI(PackageSetting ps, 13725 boolean deleteCodeAndResources, int flags, 13726 int[] allUserHandles, boolean[] perUserInstalled, 13727 PackageRemovedInfo outInfo, boolean writeSettings) { 13728 if (outInfo != null) { 13729 outInfo.uid = ps.appId; 13730 } 13731 13732 // Delete package data from internal structures and also remove data if flag is set 13733 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 13734 13735 // Delete application code and resources 13736 if (deleteCodeAndResources && (outInfo != null)) { 13737 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 13738 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 13739 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 13740 } 13741 return true; 13742 } 13743 13744 @Override 13745 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 13746 int userId) { 13747 mContext.enforceCallingOrSelfPermission( 13748 android.Manifest.permission.DELETE_PACKAGES, null); 13749 synchronized (mPackages) { 13750 PackageSetting ps = mSettings.mPackages.get(packageName); 13751 if (ps == null) { 13752 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 13753 return false; 13754 } 13755 if (!ps.getInstalled(userId)) { 13756 // Can't block uninstall for an app that is not installed or enabled. 13757 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 13758 return false; 13759 } 13760 ps.setBlockUninstall(blockUninstall, userId); 13761 mSettings.writePackageRestrictionsLPr(userId); 13762 } 13763 return true; 13764 } 13765 13766 @Override 13767 public boolean getBlockUninstallForUser(String packageName, int userId) { 13768 synchronized (mPackages) { 13769 PackageSetting ps = mSettings.mPackages.get(packageName); 13770 if (ps == null) { 13771 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 13772 return false; 13773 } 13774 return ps.getBlockUninstall(userId); 13775 } 13776 } 13777 13778 @Override 13779 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 13780 int callingUid = Binder.getCallingUid(); 13781 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 13782 throw new SecurityException( 13783 "setRequiredForSystemUser can only be run by the system or root"); 13784 } 13785 synchronized (mPackages) { 13786 PackageSetting ps = mSettings.mPackages.get(packageName); 13787 if (ps == null) { 13788 Log.w(TAG, "Package doesn't exist: " + packageName); 13789 return false; 13790 } 13791 if (systemUserApp) { 13792 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13793 } else { 13794 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 13795 } 13796 mSettings.writeLPr(); 13797 } 13798 return true; 13799 } 13800 13801 /* 13802 * This method handles package deletion in general 13803 */ 13804 private boolean deletePackageLI(String packageName, UserHandle user, 13805 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 13806 int flags, PackageRemovedInfo outInfo, 13807 boolean writeSettings) { 13808 if (packageName == null) { 13809 Slog.w(TAG, "Attempt to delete null packageName."); 13810 return false; 13811 } 13812 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 13813 PackageSetting ps; 13814 boolean dataOnly = false; 13815 int removeUser = -1; 13816 int appId = -1; 13817 synchronized (mPackages) { 13818 ps = mSettings.mPackages.get(packageName); 13819 if (ps == null) { 13820 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 13821 return false; 13822 } 13823 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 13824 && user.getIdentifier() != UserHandle.USER_ALL) { 13825 // The caller is asking that the package only be deleted for a single 13826 // user. To do this, we just mark its uninstalled state and delete 13827 // its data. If this is a system app, we only allow this to happen if 13828 // they have set the special DELETE_SYSTEM_APP which requests different 13829 // semantics than normal for uninstalling system apps. 13830 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 13831 final int userId = user.getIdentifier(); 13832 ps.setUserState(userId, 13833 COMPONENT_ENABLED_STATE_DEFAULT, 13834 false, //installed 13835 true, //stopped 13836 true, //notLaunched 13837 false, //hidden 13838 false, //suspended 13839 null, null, null, 13840 false, // blockUninstall 13841 ps.readUserState(userId).domainVerificationStatus, 0); 13842 if (!isSystemApp(ps)) { 13843 // Do not uninstall the APK if an app should be cached 13844 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 13845 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 13846 // Other user still have this package installed, so all 13847 // we need to do is clear this user's data and save that 13848 // it is uninstalled. 13849 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 13850 removeUser = user.getIdentifier(); 13851 appId = ps.appId; 13852 scheduleWritePackageRestrictionsLocked(removeUser); 13853 } else { 13854 // We need to set it back to 'installed' so the uninstall 13855 // broadcasts will be sent correctly. 13856 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 13857 ps.setInstalled(true, user.getIdentifier()); 13858 } 13859 } else { 13860 // This is a system app, so we assume that the 13861 // other users still have this package installed, so all 13862 // we need to do is clear this user's data and save that 13863 // it is uninstalled. 13864 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 13865 removeUser = user.getIdentifier(); 13866 appId = ps.appId; 13867 scheduleWritePackageRestrictionsLocked(removeUser); 13868 } 13869 } 13870 } 13871 13872 if (removeUser >= 0) { 13873 // From above, we determined that we are deleting this only 13874 // for a single user. Continue the work here. 13875 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 13876 if (outInfo != null) { 13877 outInfo.removedPackage = packageName; 13878 outInfo.removedAppId = appId; 13879 outInfo.removedUsers = new int[] {removeUser}; 13880 } 13881 // TODO: triage flags as part of 26466827 13882 final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 13883 try { 13884 mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags); 13885 } catch (InstallerException e) { 13886 Slog.w(TAG, "Failed to delete app data", e); 13887 } 13888 removeKeystoreDataIfNeeded(removeUser, appId); 13889 schedulePackageCleaning(packageName, removeUser, false); 13890 synchronized (mPackages) { 13891 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 13892 scheduleWritePackageRestrictionsLocked(removeUser); 13893 } 13894 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser); 13895 } 13896 return true; 13897 } 13898 13899 if (dataOnly) { 13900 // Delete application data first 13901 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 13902 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 13903 return true; 13904 } 13905 13906 boolean ret = false; 13907 if (isSystemApp(ps)) { 13908 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 13909 // When an updated system application is deleted we delete the existing resources as well and 13910 // fall back to existing code in system partition 13911 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 13912 flags, outInfo, writeSettings); 13913 } else { 13914 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 13915 // Kill application pre-emptively especially for apps on sd. 13916 killApplication(packageName, ps.appId, "uninstall pkg"); 13917 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 13918 allUserHandles, perUserInstalled, 13919 outInfo, writeSettings); 13920 } 13921 13922 return ret; 13923 } 13924 13925 private final static class ClearStorageConnection implements ServiceConnection { 13926 IMediaContainerService mContainerService; 13927 13928 @Override 13929 public void onServiceConnected(ComponentName name, IBinder service) { 13930 synchronized (this) { 13931 mContainerService = IMediaContainerService.Stub.asInterface(service); 13932 notifyAll(); 13933 } 13934 } 13935 13936 @Override 13937 public void onServiceDisconnected(ComponentName name) { 13938 } 13939 } 13940 13941 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 13942 final boolean mounted; 13943 if (Environment.isExternalStorageEmulated()) { 13944 mounted = true; 13945 } else { 13946 final String status = Environment.getExternalStorageState(); 13947 13948 mounted = status.equals(Environment.MEDIA_MOUNTED) 13949 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 13950 } 13951 13952 if (!mounted) { 13953 return; 13954 } 13955 13956 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 13957 int[] users; 13958 if (userId == UserHandle.USER_ALL) { 13959 users = sUserManager.getUserIds(); 13960 } else { 13961 users = new int[] { userId }; 13962 } 13963 final ClearStorageConnection conn = new ClearStorageConnection(); 13964 if (mContext.bindServiceAsUser( 13965 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 13966 try { 13967 for (int curUser : users) { 13968 long timeout = SystemClock.uptimeMillis() + 5000; 13969 synchronized (conn) { 13970 long now = SystemClock.uptimeMillis(); 13971 while (conn.mContainerService == null && now < timeout) { 13972 try { 13973 conn.wait(timeout - now); 13974 } catch (InterruptedException e) { 13975 } 13976 } 13977 } 13978 if (conn.mContainerService == null) { 13979 return; 13980 } 13981 13982 final UserEnvironment userEnv = new UserEnvironment(curUser); 13983 clearDirectory(conn.mContainerService, 13984 userEnv.buildExternalStorageAppCacheDirs(packageName)); 13985 if (allData) { 13986 clearDirectory(conn.mContainerService, 13987 userEnv.buildExternalStorageAppDataDirs(packageName)); 13988 clearDirectory(conn.mContainerService, 13989 userEnv.buildExternalStorageAppMediaDirs(packageName)); 13990 } 13991 } 13992 } finally { 13993 mContext.unbindService(conn); 13994 } 13995 } 13996 } 13997 13998 @Override 13999 public void clearApplicationUserData(final String packageName, 14000 final IPackageDataObserver observer, final int userId) { 14001 mContext.enforceCallingOrSelfPermission( 14002 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14003 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14004 // Queue up an async operation since the package deletion may take a little while. 14005 mHandler.post(new Runnable() { 14006 public void run() { 14007 mHandler.removeCallbacks(this); 14008 final boolean succeeded; 14009 synchronized (mInstallLock) { 14010 succeeded = clearApplicationUserDataLI(packageName, userId); 14011 } 14012 clearExternalStorageDataSync(packageName, userId, true); 14013 if (succeeded) { 14014 // invoke DeviceStorageMonitor's update method to clear any notifications 14015 DeviceStorageMonitorInternal 14016 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14017 if (dsm != null) { 14018 dsm.checkMemory(); 14019 } 14020 } 14021 if(observer != null) { 14022 try { 14023 observer.onRemoveCompleted(packageName, succeeded); 14024 } catch (RemoteException e) { 14025 Log.i(TAG, "Observer no longer exists."); 14026 } 14027 } //end if observer 14028 } //end run 14029 }); 14030 } 14031 14032 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14033 if (packageName == null) { 14034 Slog.w(TAG, "Attempt to delete null packageName."); 14035 return false; 14036 } 14037 14038 // Try finding details about the requested package 14039 PackageParser.Package pkg; 14040 synchronized (mPackages) { 14041 pkg = mPackages.get(packageName); 14042 if (pkg == null) { 14043 final PackageSetting ps = mSettings.mPackages.get(packageName); 14044 if (ps != null) { 14045 pkg = ps.pkg; 14046 } 14047 } 14048 14049 if (pkg == null) { 14050 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14051 return false; 14052 } 14053 14054 PackageSetting ps = (PackageSetting) pkg.mExtras; 14055 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14056 } 14057 14058 // Always delete data directories for package, even if we found no other 14059 // record of app. This helps users recover from UID mismatches without 14060 // resorting to a full data wipe. 14061 // TODO: triage flags as part of 26466827 14062 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14063 try { 14064 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14065 } catch (InstallerException e) { 14066 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14067 return false; 14068 } 14069 14070 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14071 removeKeystoreDataIfNeeded(userId, appId); 14072 14073 // Create a native library symlink only if we have native libraries 14074 // and if the native libraries are 32 bit libraries. We do not provide 14075 // this symlink for 64 bit libraries. 14076 if (pkg.applicationInfo.primaryCpuAbi != null && 14077 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14078 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14079 try { 14080 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14081 nativeLibPath, userId); 14082 } catch (InstallerException e) { 14083 Slog.w(TAG, "Failed linking native library dir", e); 14084 return false; 14085 } 14086 } 14087 14088 return true; 14089 } 14090 14091 /** 14092 * Reverts user permission state changes (permissions and flags) in 14093 * all packages for a given user. 14094 * 14095 * @param userId The device user for which to do a reset. 14096 */ 14097 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14098 final int packageCount = mPackages.size(); 14099 for (int i = 0; i < packageCount; i++) { 14100 PackageParser.Package pkg = mPackages.valueAt(i); 14101 PackageSetting ps = (PackageSetting) pkg.mExtras; 14102 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14103 } 14104 } 14105 14106 /** 14107 * Reverts user permission state changes (permissions and flags). 14108 * 14109 * @param ps The package for which to reset. 14110 * @param userId The device user for which to do a reset. 14111 */ 14112 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14113 final PackageSetting ps, final int userId) { 14114 if (ps.pkg == null) { 14115 return; 14116 } 14117 14118 // These are flags that can change base on user actions. 14119 final int userSettableMask = FLAG_PERMISSION_USER_SET 14120 | FLAG_PERMISSION_USER_FIXED 14121 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14122 | FLAG_PERMISSION_REVIEW_REQUIRED; 14123 14124 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14125 | FLAG_PERMISSION_POLICY_FIXED; 14126 14127 boolean writeInstallPermissions = false; 14128 boolean writeRuntimePermissions = false; 14129 14130 final int permissionCount = ps.pkg.requestedPermissions.size(); 14131 for (int i = 0; i < permissionCount; i++) { 14132 String permission = ps.pkg.requestedPermissions.get(i); 14133 14134 BasePermission bp = mSettings.mPermissions.get(permission); 14135 if (bp == null) { 14136 continue; 14137 } 14138 14139 // If shared user we just reset the state to which only this app contributed. 14140 if (ps.sharedUser != null) { 14141 boolean used = false; 14142 final int packageCount = ps.sharedUser.packages.size(); 14143 for (int j = 0; j < packageCount; j++) { 14144 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14145 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14146 && pkg.pkg.requestedPermissions.contains(permission)) { 14147 used = true; 14148 break; 14149 } 14150 } 14151 if (used) { 14152 continue; 14153 } 14154 } 14155 14156 PermissionsState permissionsState = ps.getPermissionsState(); 14157 14158 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14159 14160 // Always clear the user settable flags. 14161 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14162 bp.name) != null; 14163 // If permission review is enabled and this is a legacy app, mark the 14164 // permission as requiring a review as this is the initial state. 14165 int flags = 0; 14166 if (Build.PERMISSIONS_REVIEW_REQUIRED 14167 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14168 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14169 } 14170 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14171 if (hasInstallState) { 14172 writeInstallPermissions = true; 14173 } else { 14174 writeRuntimePermissions = true; 14175 } 14176 } 14177 14178 // Below is only runtime permission handling. 14179 if (!bp.isRuntime()) { 14180 continue; 14181 } 14182 14183 // Never clobber system or policy. 14184 if ((oldFlags & policyOrSystemFlags) != 0) { 14185 continue; 14186 } 14187 14188 // If this permission was granted by default, make sure it is. 14189 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14190 if (permissionsState.grantRuntimePermission(bp, userId) 14191 != PERMISSION_OPERATION_FAILURE) { 14192 writeRuntimePermissions = true; 14193 } 14194 // If permission review is enabled the permissions for a legacy apps 14195 // are represented as constantly granted runtime ones, so don't revoke. 14196 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14197 // Otherwise, reset the permission. 14198 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14199 switch (revokeResult) { 14200 case PERMISSION_OPERATION_SUCCESS: { 14201 writeRuntimePermissions = true; 14202 } break; 14203 14204 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14205 writeRuntimePermissions = true; 14206 final int appId = ps.appId; 14207 mHandler.post(new Runnable() { 14208 @Override 14209 public void run() { 14210 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14211 } 14212 }); 14213 } break; 14214 } 14215 } 14216 } 14217 14218 // Synchronously write as we are taking permissions away. 14219 if (writeRuntimePermissions) { 14220 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14221 } 14222 14223 // Synchronously write as we are taking permissions away. 14224 if (writeInstallPermissions) { 14225 mSettings.writeLPr(); 14226 } 14227 } 14228 14229 /** 14230 * Remove entries from the keystore daemon. Will only remove it if the 14231 * {@code appId} is valid. 14232 */ 14233 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14234 if (appId < 0) { 14235 return; 14236 } 14237 14238 final KeyStore keyStore = KeyStore.getInstance(); 14239 if (keyStore != null) { 14240 if (userId == UserHandle.USER_ALL) { 14241 for (final int individual : sUserManager.getUserIds()) { 14242 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14243 } 14244 } else { 14245 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14246 } 14247 } else { 14248 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14249 } 14250 } 14251 14252 @Override 14253 public void deleteApplicationCacheFiles(final String packageName, 14254 final IPackageDataObserver observer) { 14255 mContext.enforceCallingOrSelfPermission( 14256 android.Manifest.permission.DELETE_CACHE_FILES, null); 14257 // Queue up an async operation since the package deletion may take a little while. 14258 final int userId = UserHandle.getCallingUserId(); 14259 mHandler.post(new Runnable() { 14260 public void run() { 14261 mHandler.removeCallbacks(this); 14262 final boolean succeded; 14263 synchronized (mInstallLock) { 14264 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14265 } 14266 clearExternalStorageDataSync(packageName, userId, false); 14267 if (observer != null) { 14268 try { 14269 observer.onRemoveCompleted(packageName, succeded); 14270 } catch (RemoteException e) { 14271 Log.i(TAG, "Observer no longer exists."); 14272 } 14273 } //end if observer 14274 } //end run 14275 }); 14276 } 14277 14278 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14279 if (packageName == null) { 14280 Slog.w(TAG, "Attempt to delete null packageName."); 14281 return false; 14282 } 14283 PackageParser.Package p; 14284 synchronized (mPackages) { 14285 p = mPackages.get(packageName); 14286 } 14287 if (p == null) { 14288 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14289 return false; 14290 } 14291 final ApplicationInfo applicationInfo = p.applicationInfo; 14292 if (applicationInfo == null) { 14293 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14294 return false; 14295 } 14296 // TODO: triage flags as part of 26466827 14297 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14298 try { 14299 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14300 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14301 } catch (InstallerException e) { 14302 Slog.w(TAG, "Couldn't remove cache files for package " 14303 + packageName + " u" + userId, e); 14304 return false; 14305 } 14306 return true; 14307 } 14308 14309 @Override 14310 public void getPackageSizeInfo(final String packageName, int userHandle, 14311 final IPackageStatsObserver observer) { 14312 mContext.enforceCallingOrSelfPermission( 14313 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14314 if (packageName == null) { 14315 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14316 } 14317 14318 PackageStats stats = new PackageStats(packageName, userHandle); 14319 14320 /* 14321 * Queue up an async operation since the package measurement may take a 14322 * little while. 14323 */ 14324 Message msg = mHandler.obtainMessage(INIT_COPY); 14325 msg.obj = new MeasureParams(stats, observer); 14326 mHandler.sendMessage(msg); 14327 } 14328 14329 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14330 PackageStats pStats) { 14331 if (packageName == null) { 14332 Slog.w(TAG, "Attempt to get size of null packageName."); 14333 return false; 14334 } 14335 PackageParser.Package p; 14336 boolean dataOnly = false; 14337 String libDirRoot = null; 14338 String asecPath = null; 14339 PackageSetting ps = null; 14340 synchronized (mPackages) { 14341 p = mPackages.get(packageName); 14342 ps = mSettings.mPackages.get(packageName); 14343 if(p == null) { 14344 dataOnly = true; 14345 if((ps == null) || (ps.pkg == null)) { 14346 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14347 return false; 14348 } 14349 p = ps.pkg; 14350 } 14351 if (ps != null) { 14352 libDirRoot = ps.legacyNativeLibraryPathString; 14353 } 14354 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14355 final long token = Binder.clearCallingIdentity(); 14356 try { 14357 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14358 if (secureContainerId != null) { 14359 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14360 } 14361 } finally { 14362 Binder.restoreCallingIdentity(token); 14363 } 14364 } 14365 } 14366 String publicSrcDir = null; 14367 if(!dataOnly) { 14368 final ApplicationInfo applicationInfo = p.applicationInfo; 14369 if (applicationInfo == null) { 14370 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14371 return false; 14372 } 14373 if (p.isForwardLocked()) { 14374 publicSrcDir = applicationInfo.getBaseResourcePath(); 14375 } 14376 } 14377 // TODO: extend to measure size of split APKs 14378 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 14379 // not just the first level. 14380 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 14381 // just the primary. 14382 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 14383 14384 String apkPath; 14385 File packageDir = new File(p.codePath); 14386 14387 if (packageDir.isDirectory() && p.canHaveOatDir()) { 14388 apkPath = packageDir.getAbsolutePath(); 14389 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 14390 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 14391 libDirRoot = null; 14392 } 14393 } else { 14394 apkPath = p.baseCodePath; 14395 } 14396 14397 // TODO: triage flags as part of 26466827 14398 final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE; 14399 try { 14400 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 14401 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 14402 } catch (InstallerException e) { 14403 return false; 14404 } 14405 14406 // Fix-up for forward-locked applications in ASEC containers. 14407 if (!isExternal(p)) { 14408 pStats.codeSize += pStats.externalCodeSize; 14409 pStats.externalCodeSize = 0L; 14410 } 14411 14412 return true; 14413 } 14414 14415 14416 @Override 14417 public void addPackageToPreferred(String packageName) { 14418 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 14419 } 14420 14421 @Override 14422 public void removePackageFromPreferred(String packageName) { 14423 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 14424 } 14425 14426 @Override 14427 public List<PackageInfo> getPreferredPackages(int flags) { 14428 return new ArrayList<PackageInfo>(); 14429 } 14430 14431 private int getUidTargetSdkVersionLockedLPr(int uid) { 14432 Object obj = mSettings.getUserIdLPr(uid); 14433 if (obj instanceof SharedUserSetting) { 14434 final SharedUserSetting sus = (SharedUserSetting) obj; 14435 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 14436 final Iterator<PackageSetting> it = sus.packages.iterator(); 14437 while (it.hasNext()) { 14438 final PackageSetting ps = it.next(); 14439 if (ps.pkg != null) { 14440 int v = ps.pkg.applicationInfo.targetSdkVersion; 14441 if (v < vers) vers = v; 14442 } 14443 } 14444 return vers; 14445 } else if (obj instanceof PackageSetting) { 14446 final PackageSetting ps = (PackageSetting) obj; 14447 if (ps.pkg != null) { 14448 return ps.pkg.applicationInfo.targetSdkVersion; 14449 } 14450 } 14451 return Build.VERSION_CODES.CUR_DEVELOPMENT; 14452 } 14453 14454 @Override 14455 public void addPreferredActivity(IntentFilter filter, int match, 14456 ComponentName[] set, ComponentName activity, int userId) { 14457 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14458 "Adding preferred"); 14459 } 14460 14461 private void addPreferredActivityInternal(IntentFilter filter, int match, 14462 ComponentName[] set, ComponentName activity, boolean always, int userId, 14463 String opname) { 14464 // writer 14465 int callingUid = Binder.getCallingUid(); 14466 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 14467 if (filter.countActions() == 0) { 14468 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14469 return; 14470 } 14471 synchronized (mPackages) { 14472 if (mContext.checkCallingOrSelfPermission( 14473 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14474 != PackageManager.PERMISSION_GRANTED) { 14475 if (getUidTargetSdkVersionLockedLPr(callingUid) 14476 < Build.VERSION_CODES.FROYO) { 14477 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 14478 + callingUid); 14479 return; 14480 } 14481 mContext.enforceCallingOrSelfPermission( 14482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14483 } 14484 14485 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 14486 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 14487 + userId + ":"); 14488 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14489 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 14490 scheduleWritePackageRestrictionsLocked(userId); 14491 } 14492 } 14493 14494 @Override 14495 public void replacePreferredActivity(IntentFilter filter, int match, 14496 ComponentName[] set, ComponentName activity, int userId) { 14497 if (filter.countActions() != 1) { 14498 throw new IllegalArgumentException( 14499 "replacePreferredActivity expects filter to have only 1 action."); 14500 } 14501 if (filter.countDataAuthorities() != 0 14502 || filter.countDataPaths() != 0 14503 || filter.countDataSchemes() > 1 14504 || filter.countDataTypes() != 0) { 14505 throw new IllegalArgumentException( 14506 "replacePreferredActivity expects filter to have no data authorities, " + 14507 "paths, or types; and at most one scheme."); 14508 } 14509 14510 final int callingUid = Binder.getCallingUid(); 14511 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 14512 synchronized (mPackages) { 14513 if (mContext.checkCallingOrSelfPermission( 14514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14515 != PackageManager.PERMISSION_GRANTED) { 14516 if (getUidTargetSdkVersionLockedLPr(callingUid) 14517 < Build.VERSION_CODES.FROYO) { 14518 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 14519 + Binder.getCallingUid()); 14520 return; 14521 } 14522 mContext.enforceCallingOrSelfPermission( 14523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14524 } 14525 14526 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14527 if (pir != null) { 14528 // Get all of the existing entries that exactly match this filter. 14529 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 14530 if (existing != null && existing.size() == 1) { 14531 PreferredActivity cur = existing.get(0); 14532 if (DEBUG_PREFERRED) { 14533 Slog.i(TAG, "Checking replace of preferred:"); 14534 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14535 if (!cur.mPref.mAlways) { 14536 Slog.i(TAG, " -- CUR; not mAlways!"); 14537 } else { 14538 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 14539 Slog.i(TAG, " -- CUR: mSet=" 14540 + Arrays.toString(cur.mPref.mSetComponents)); 14541 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 14542 Slog.i(TAG, " -- NEW: mMatch=" 14543 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 14544 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 14545 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 14546 } 14547 } 14548 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 14549 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 14550 && cur.mPref.sameSet(set)) { 14551 // Setting the preferred activity to what it happens to be already 14552 if (DEBUG_PREFERRED) { 14553 Slog.i(TAG, "Replacing with same preferred activity " 14554 + cur.mPref.mShortComponent + " for user " 14555 + userId + ":"); 14556 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14557 } 14558 return; 14559 } 14560 } 14561 14562 if (existing != null) { 14563 if (DEBUG_PREFERRED) { 14564 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 14565 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14566 } 14567 for (int i = 0; i < existing.size(); i++) { 14568 PreferredActivity pa = existing.get(i); 14569 if (DEBUG_PREFERRED) { 14570 Slog.i(TAG, "Removing existing preferred activity " 14571 + pa.mPref.mComponent + ":"); 14572 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 14573 } 14574 pir.removeFilter(pa); 14575 } 14576 } 14577 } 14578 addPreferredActivityInternal(filter, match, set, activity, true, userId, 14579 "Replacing preferred"); 14580 } 14581 } 14582 14583 @Override 14584 public void clearPackagePreferredActivities(String packageName) { 14585 final int uid = Binder.getCallingUid(); 14586 // writer 14587 synchronized (mPackages) { 14588 PackageParser.Package pkg = mPackages.get(packageName); 14589 if (pkg == null || pkg.applicationInfo.uid != uid) { 14590 if (mContext.checkCallingOrSelfPermission( 14591 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 14592 != PackageManager.PERMISSION_GRANTED) { 14593 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 14594 < Build.VERSION_CODES.FROYO) { 14595 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 14596 + Binder.getCallingUid()); 14597 return; 14598 } 14599 mContext.enforceCallingOrSelfPermission( 14600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14601 } 14602 } 14603 14604 int user = UserHandle.getCallingUserId(); 14605 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 14606 scheduleWritePackageRestrictionsLocked(user); 14607 } 14608 } 14609 } 14610 14611 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14612 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 14613 ArrayList<PreferredActivity> removed = null; 14614 boolean changed = false; 14615 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14616 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 14617 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14618 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 14619 continue; 14620 } 14621 Iterator<PreferredActivity> it = pir.filterIterator(); 14622 while (it.hasNext()) { 14623 PreferredActivity pa = it.next(); 14624 // Mark entry for removal only if it matches the package name 14625 // and the entry is of type "always". 14626 if (packageName == null || 14627 (pa.mPref.mComponent.getPackageName().equals(packageName) 14628 && pa.mPref.mAlways)) { 14629 if (removed == null) { 14630 removed = new ArrayList<PreferredActivity>(); 14631 } 14632 removed.add(pa); 14633 } 14634 } 14635 if (removed != null) { 14636 for (int j=0; j<removed.size(); j++) { 14637 PreferredActivity pa = removed.get(j); 14638 pir.removeFilter(pa); 14639 } 14640 changed = true; 14641 } 14642 } 14643 return changed; 14644 } 14645 14646 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14647 private void clearIntentFilterVerificationsLPw(int userId) { 14648 final int packageCount = mPackages.size(); 14649 for (int i = 0; i < packageCount; i++) { 14650 PackageParser.Package pkg = mPackages.valueAt(i); 14651 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 14652 } 14653 } 14654 14655 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 14656 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 14657 if (userId == UserHandle.USER_ALL) { 14658 if (mSettings.removeIntentFilterVerificationLPw(packageName, 14659 sUserManager.getUserIds())) { 14660 for (int oneUserId : sUserManager.getUserIds()) { 14661 scheduleWritePackageRestrictionsLocked(oneUserId); 14662 } 14663 } 14664 } else { 14665 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 14666 scheduleWritePackageRestrictionsLocked(userId); 14667 } 14668 } 14669 } 14670 14671 void clearDefaultBrowserIfNeeded(String packageName) { 14672 for (int oneUserId : sUserManager.getUserIds()) { 14673 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 14674 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 14675 if (packageName.equals(defaultBrowserPackageName)) { 14676 setDefaultBrowserPackageName(null, oneUserId); 14677 } 14678 } 14679 } 14680 14681 @Override 14682 public void resetApplicationPreferences(int userId) { 14683 mContext.enforceCallingOrSelfPermission( 14684 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14685 // writer 14686 synchronized (mPackages) { 14687 final long identity = Binder.clearCallingIdentity(); 14688 try { 14689 clearPackagePreferredActivitiesLPw(null, userId); 14690 mSettings.applyDefaultPreferredAppsLPw(this, userId); 14691 // TODO: We have to reset the default SMS and Phone. This requires 14692 // significant refactoring to keep all default apps in the package 14693 // manager (cleaner but more work) or have the services provide 14694 // callbacks to the package manager to request a default app reset. 14695 applyFactoryDefaultBrowserLPw(userId); 14696 clearIntentFilterVerificationsLPw(userId); 14697 primeDomainVerificationsLPw(userId); 14698 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 14699 scheduleWritePackageRestrictionsLocked(userId); 14700 } finally { 14701 Binder.restoreCallingIdentity(identity); 14702 } 14703 } 14704 } 14705 14706 @Override 14707 public int getPreferredActivities(List<IntentFilter> outFilters, 14708 List<ComponentName> outActivities, String packageName) { 14709 14710 int num = 0; 14711 final int userId = UserHandle.getCallingUserId(); 14712 // reader 14713 synchronized (mPackages) { 14714 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 14715 if (pir != null) { 14716 final Iterator<PreferredActivity> it = pir.filterIterator(); 14717 while (it.hasNext()) { 14718 final PreferredActivity pa = it.next(); 14719 if (packageName == null 14720 || (pa.mPref.mComponent.getPackageName().equals(packageName) 14721 && pa.mPref.mAlways)) { 14722 if (outFilters != null) { 14723 outFilters.add(new IntentFilter(pa)); 14724 } 14725 if (outActivities != null) { 14726 outActivities.add(pa.mPref.mComponent); 14727 } 14728 } 14729 } 14730 } 14731 } 14732 14733 return num; 14734 } 14735 14736 @Override 14737 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 14738 int userId) { 14739 int callingUid = Binder.getCallingUid(); 14740 if (callingUid != Process.SYSTEM_UID) { 14741 throw new SecurityException( 14742 "addPersistentPreferredActivity can only be run by the system"); 14743 } 14744 if (filter.countActions() == 0) { 14745 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 14746 return; 14747 } 14748 synchronized (mPackages) { 14749 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 14750 ":"); 14751 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 14752 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 14753 new PersistentPreferredActivity(filter, activity)); 14754 scheduleWritePackageRestrictionsLocked(userId); 14755 } 14756 } 14757 14758 @Override 14759 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 14760 int callingUid = Binder.getCallingUid(); 14761 if (callingUid != Process.SYSTEM_UID) { 14762 throw new SecurityException( 14763 "clearPackagePersistentPreferredActivities can only be run by the system"); 14764 } 14765 ArrayList<PersistentPreferredActivity> removed = null; 14766 boolean changed = false; 14767 synchronized (mPackages) { 14768 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 14769 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 14770 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 14771 .valueAt(i); 14772 if (userId != thisUserId) { 14773 continue; 14774 } 14775 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 14776 while (it.hasNext()) { 14777 PersistentPreferredActivity ppa = it.next(); 14778 // Mark entry for removal only if it matches the package name. 14779 if (ppa.mComponent.getPackageName().equals(packageName)) { 14780 if (removed == null) { 14781 removed = new ArrayList<PersistentPreferredActivity>(); 14782 } 14783 removed.add(ppa); 14784 } 14785 } 14786 if (removed != null) { 14787 for (int j=0; j<removed.size(); j++) { 14788 PersistentPreferredActivity ppa = removed.get(j); 14789 ppir.removeFilter(ppa); 14790 } 14791 changed = true; 14792 } 14793 } 14794 14795 if (changed) { 14796 scheduleWritePackageRestrictionsLocked(userId); 14797 } 14798 } 14799 } 14800 14801 /** 14802 * Common machinery for picking apart a restored XML blob and passing 14803 * it to a caller-supplied functor to be applied to the running system. 14804 */ 14805 private void restoreFromXml(XmlPullParser parser, int userId, 14806 String expectedStartTag, BlobXmlRestorer functor) 14807 throws IOException, XmlPullParserException { 14808 int type; 14809 while ((type = parser.next()) != XmlPullParser.START_TAG 14810 && type != XmlPullParser.END_DOCUMENT) { 14811 } 14812 if (type != XmlPullParser.START_TAG) { 14813 // oops didn't find a start tag?! 14814 if (DEBUG_BACKUP) { 14815 Slog.e(TAG, "Didn't find start tag during restore"); 14816 } 14817 return; 14818 } 14819Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 14820 // this is supposed to be TAG_PREFERRED_BACKUP 14821 if (!expectedStartTag.equals(parser.getName())) { 14822 if (DEBUG_BACKUP) { 14823 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 14824 } 14825 return; 14826 } 14827 14828 // skip interfering stuff, then we're aligned with the backing implementation 14829 while ((type = parser.next()) == XmlPullParser.TEXT) { } 14830Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 14831 functor.apply(parser, userId); 14832 } 14833 14834 private interface BlobXmlRestorer { 14835 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 14836 } 14837 14838 /** 14839 * Non-Binder method, support for the backup/restore mechanism: write the 14840 * full set of preferred activities in its canonical XML format. Returns the 14841 * XML output as a byte array, or null if there is none. 14842 */ 14843 @Override 14844 public byte[] getPreferredActivityBackup(int userId) { 14845 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14846 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 14847 } 14848 14849 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14850 try { 14851 final XmlSerializer serializer = new FastXmlSerializer(); 14852 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14853 serializer.startDocument(null, true); 14854 serializer.startTag(null, TAG_PREFERRED_BACKUP); 14855 14856 synchronized (mPackages) { 14857 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 14858 } 14859 14860 serializer.endTag(null, TAG_PREFERRED_BACKUP); 14861 serializer.endDocument(); 14862 serializer.flush(); 14863 } catch (Exception e) { 14864 if (DEBUG_BACKUP) { 14865 Slog.e(TAG, "Unable to write preferred activities for backup", e); 14866 } 14867 return null; 14868 } 14869 14870 return dataStream.toByteArray(); 14871 } 14872 14873 @Override 14874 public void restorePreferredActivities(byte[] backup, int userId) { 14875 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14876 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14877 } 14878 14879 try { 14880 final XmlPullParser parser = Xml.newPullParser(); 14881 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14882 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 14883 new BlobXmlRestorer() { 14884 @Override 14885 public void apply(XmlPullParser parser, int userId) 14886 throws XmlPullParserException, IOException { 14887 synchronized (mPackages) { 14888 mSettings.readPreferredActivitiesLPw(parser, userId); 14889 } 14890 } 14891 } ); 14892 } catch (Exception e) { 14893 if (DEBUG_BACKUP) { 14894 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 14895 } 14896 } 14897 } 14898 14899 /** 14900 * Non-Binder method, support for the backup/restore mechanism: write the 14901 * default browser (etc) settings in its canonical XML format. Returns the default 14902 * browser XML representation as a byte array, or null if there is none. 14903 */ 14904 @Override 14905 public byte[] getDefaultAppsBackup(int userId) { 14906 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14907 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 14908 } 14909 14910 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14911 try { 14912 final XmlSerializer serializer = new FastXmlSerializer(); 14913 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14914 serializer.startDocument(null, true); 14915 serializer.startTag(null, TAG_DEFAULT_APPS); 14916 14917 synchronized (mPackages) { 14918 mSettings.writeDefaultAppsLPr(serializer, userId); 14919 } 14920 14921 serializer.endTag(null, TAG_DEFAULT_APPS); 14922 serializer.endDocument(); 14923 serializer.flush(); 14924 } catch (Exception e) { 14925 if (DEBUG_BACKUP) { 14926 Slog.e(TAG, "Unable to write default apps for backup", e); 14927 } 14928 return null; 14929 } 14930 14931 return dataStream.toByteArray(); 14932 } 14933 14934 @Override 14935 public void restoreDefaultApps(byte[] backup, int userId) { 14936 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14937 throw new SecurityException("Only the system may call restoreDefaultApps()"); 14938 } 14939 14940 try { 14941 final XmlPullParser parser = Xml.newPullParser(); 14942 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14943 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 14944 new BlobXmlRestorer() { 14945 @Override 14946 public void apply(XmlPullParser parser, int userId) 14947 throws XmlPullParserException, IOException { 14948 synchronized (mPackages) { 14949 mSettings.readDefaultAppsLPw(parser, userId); 14950 } 14951 } 14952 } ); 14953 } catch (Exception e) { 14954 if (DEBUG_BACKUP) { 14955 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 14956 } 14957 } 14958 } 14959 14960 @Override 14961 public byte[] getIntentFilterVerificationBackup(int userId) { 14962 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14963 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 14964 } 14965 14966 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 14967 try { 14968 final XmlSerializer serializer = new FastXmlSerializer(); 14969 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 14970 serializer.startDocument(null, true); 14971 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 14972 14973 synchronized (mPackages) { 14974 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 14975 } 14976 14977 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 14978 serializer.endDocument(); 14979 serializer.flush(); 14980 } catch (Exception e) { 14981 if (DEBUG_BACKUP) { 14982 Slog.e(TAG, "Unable to write default apps for backup", e); 14983 } 14984 return null; 14985 } 14986 14987 return dataStream.toByteArray(); 14988 } 14989 14990 @Override 14991 public void restoreIntentFilterVerification(byte[] backup, int userId) { 14992 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 14993 throw new SecurityException("Only the system may call restorePreferredActivities()"); 14994 } 14995 14996 try { 14997 final XmlPullParser parser = Xml.newPullParser(); 14998 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 14999 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15000 new BlobXmlRestorer() { 15001 @Override 15002 public void apply(XmlPullParser parser, int userId) 15003 throws XmlPullParserException, IOException { 15004 synchronized (mPackages) { 15005 mSettings.readAllDomainVerificationsLPr(parser, userId); 15006 mSettings.writeLPr(); 15007 } 15008 } 15009 } ); 15010 } catch (Exception e) { 15011 if (DEBUG_BACKUP) { 15012 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15013 } 15014 } 15015 } 15016 15017 @Override 15018 public byte[] getPermissionGrantBackup(int userId) { 15019 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15020 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15021 } 15022 15023 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15024 try { 15025 final XmlSerializer serializer = new FastXmlSerializer(); 15026 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15027 serializer.startDocument(null, true); 15028 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15029 15030 synchronized (mPackages) { 15031 serializeRuntimePermissionGrantsLPr(serializer, userId); 15032 } 15033 15034 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15035 serializer.endDocument(); 15036 serializer.flush(); 15037 } catch (Exception e) { 15038 if (DEBUG_BACKUP) { 15039 Slog.e(TAG, "Unable to write default apps for backup", e); 15040 } 15041 return null; 15042 } 15043 15044 return dataStream.toByteArray(); 15045 } 15046 15047 @Override 15048 public void restorePermissionGrants(byte[] backup, int userId) { 15049 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15050 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15051 } 15052 15053 try { 15054 final XmlPullParser parser = Xml.newPullParser(); 15055 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15056 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15057 new BlobXmlRestorer() { 15058 @Override 15059 public void apply(XmlPullParser parser, int userId) 15060 throws XmlPullParserException, IOException { 15061 synchronized (mPackages) { 15062 processRestoredPermissionGrantsLPr(parser, userId); 15063 } 15064 } 15065 } ); 15066 } catch (Exception e) { 15067 if (DEBUG_BACKUP) { 15068 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15069 } 15070 } 15071 } 15072 15073 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15074 throws IOException { 15075 serializer.startTag(null, TAG_ALL_GRANTS); 15076 15077 final int N = mSettings.mPackages.size(); 15078 for (int i = 0; i < N; i++) { 15079 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15080 boolean pkgGrantsKnown = false; 15081 15082 PermissionsState packagePerms = ps.getPermissionsState(); 15083 15084 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15085 final int grantFlags = state.getFlags(); 15086 // only look at grants that are not system/policy fixed 15087 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15088 final boolean isGranted = state.isGranted(); 15089 // And only back up the user-twiddled state bits 15090 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15091 final String packageName = mSettings.mPackages.keyAt(i); 15092 if (!pkgGrantsKnown) { 15093 serializer.startTag(null, TAG_GRANT); 15094 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15095 pkgGrantsKnown = true; 15096 } 15097 15098 final boolean userSet = 15099 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15100 final boolean userFixed = 15101 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15102 final boolean revoke = 15103 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15104 15105 serializer.startTag(null, TAG_PERMISSION); 15106 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15107 if (isGranted) { 15108 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15109 } 15110 if (userSet) { 15111 serializer.attribute(null, ATTR_USER_SET, "true"); 15112 } 15113 if (userFixed) { 15114 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15115 } 15116 if (revoke) { 15117 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15118 } 15119 serializer.endTag(null, TAG_PERMISSION); 15120 } 15121 } 15122 } 15123 15124 if (pkgGrantsKnown) { 15125 serializer.endTag(null, TAG_GRANT); 15126 } 15127 } 15128 15129 serializer.endTag(null, TAG_ALL_GRANTS); 15130 } 15131 15132 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15133 throws XmlPullParserException, IOException { 15134 String pkgName = null; 15135 int outerDepth = parser.getDepth(); 15136 int type; 15137 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15138 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15139 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15140 continue; 15141 } 15142 15143 final String tagName = parser.getName(); 15144 if (tagName.equals(TAG_GRANT)) { 15145 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15146 if (DEBUG_BACKUP) { 15147 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15148 } 15149 } else if (tagName.equals(TAG_PERMISSION)) { 15150 15151 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15152 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15153 15154 int newFlagSet = 0; 15155 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15156 newFlagSet |= FLAG_PERMISSION_USER_SET; 15157 } 15158 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15159 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15160 } 15161 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15162 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15163 } 15164 if (DEBUG_BACKUP) { 15165 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15166 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15167 } 15168 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15169 if (ps != null) { 15170 // Already installed so we apply the grant immediately 15171 if (DEBUG_BACKUP) { 15172 Slog.v(TAG, " + already installed; applying"); 15173 } 15174 PermissionsState perms = ps.getPermissionsState(); 15175 BasePermission bp = mSettings.mPermissions.get(permName); 15176 if (bp != null) { 15177 if (isGranted) { 15178 perms.grantRuntimePermission(bp, userId); 15179 } 15180 if (newFlagSet != 0) { 15181 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15182 } 15183 } 15184 } else { 15185 // Need to wait for post-restore install to apply the grant 15186 if (DEBUG_BACKUP) { 15187 Slog.v(TAG, " - not yet installed; saving for later"); 15188 } 15189 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15190 isGranted, newFlagSet, userId); 15191 } 15192 } else { 15193 PackageManagerService.reportSettingsProblem(Log.WARN, 15194 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15195 XmlUtils.skipCurrentTag(parser); 15196 } 15197 } 15198 15199 scheduleWriteSettingsLocked(); 15200 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15201 } 15202 15203 @Override 15204 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15205 int sourceUserId, int targetUserId, int flags) { 15206 mContext.enforceCallingOrSelfPermission( 15207 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15208 int callingUid = Binder.getCallingUid(); 15209 enforceOwnerRights(ownerPackage, callingUid); 15210 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15211 if (intentFilter.countActions() == 0) { 15212 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15213 return; 15214 } 15215 synchronized (mPackages) { 15216 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15217 ownerPackage, targetUserId, flags); 15218 CrossProfileIntentResolver resolver = 15219 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15220 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15221 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15222 if (existing != null) { 15223 int size = existing.size(); 15224 for (int i = 0; i < size; i++) { 15225 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15226 return; 15227 } 15228 } 15229 } 15230 resolver.addFilter(newFilter); 15231 scheduleWritePackageRestrictionsLocked(sourceUserId); 15232 } 15233 } 15234 15235 @Override 15236 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15237 mContext.enforceCallingOrSelfPermission( 15238 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15239 int callingUid = Binder.getCallingUid(); 15240 enforceOwnerRights(ownerPackage, callingUid); 15241 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15242 synchronized (mPackages) { 15243 CrossProfileIntentResolver resolver = 15244 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15245 ArraySet<CrossProfileIntentFilter> set = 15246 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15247 for (CrossProfileIntentFilter filter : set) { 15248 if (filter.getOwnerPackage().equals(ownerPackage)) { 15249 resolver.removeFilter(filter); 15250 } 15251 } 15252 scheduleWritePackageRestrictionsLocked(sourceUserId); 15253 } 15254 } 15255 15256 // Enforcing that callingUid is owning pkg on userId 15257 private void enforceOwnerRights(String pkg, int callingUid) { 15258 // The system owns everything. 15259 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15260 return; 15261 } 15262 int callingUserId = UserHandle.getUserId(callingUid); 15263 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15264 if (pi == null) { 15265 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15266 + callingUserId); 15267 } 15268 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15269 throw new SecurityException("Calling uid " + callingUid 15270 + " does not own package " + pkg); 15271 } 15272 } 15273 15274 @Override 15275 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15276 Intent intent = new Intent(Intent.ACTION_MAIN); 15277 intent.addCategory(Intent.CATEGORY_HOME); 15278 15279 final int callingUserId = UserHandle.getCallingUserId(); 15280 List<ResolveInfo> list = queryIntentActivities(intent, null, 15281 PackageManager.GET_META_DATA, callingUserId); 15282 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15283 true, false, false, callingUserId); 15284 15285 allHomeCandidates.clear(); 15286 if (list != null) { 15287 for (ResolveInfo ri : list) { 15288 allHomeCandidates.add(ri); 15289 } 15290 } 15291 return (preferred == null || preferred.activityInfo == null) 15292 ? null 15293 : new ComponentName(preferred.activityInfo.packageName, 15294 preferred.activityInfo.name); 15295 } 15296 15297 @Override 15298 public void setApplicationEnabledSetting(String appPackageName, 15299 int newState, int flags, int userId, String callingPackage) { 15300 if (!sUserManager.exists(userId)) return; 15301 if (callingPackage == null) { 15302 callingPackage = Integer.toString(Binder.getCallingUid()); 15303 } 15304 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15305 } 15306 15307 @Override 15308 public void setComponentEnabledSetting(ComponentName componentName, 15309 int newState, int flags, int userId) { 15310 if (!sUserManager.exists(userId)) return; 15311 setEnabledSetting(componentName.getPackageName(), 15312 componentName.getClassName(), newState, flags, userId, null); 15313 } 15314 15315 private void setEnabledSetting(final String packageName, String className, int newState, 15316 final int flags, int userId, String callingPackage) { 15317 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15318 || newState == COMPONENT_ENABLED_STATE_ENABLED 15319 || newState == COMPONENT_ENABLED_STATE_DISABLED 15320 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15321 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15322 throw new IllegalArgumentException("Invalid new component state: " 15323 + newState); 15324 } 15325 PackageSetting pkgSetting; 15326 final int uid = Binder.getCallingUid(); 15327 final int permission = mContext.checkCallingOrSelfPermission( 15328 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15329 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15330 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15331 boolean sendNow = false; 15332 boolean isApp = (className == null); 15333 String componentName = isApp ? packageName : className; 15334 int packageUid = -1; 15335 ArrayList<String> components; 15336 15337 // writer 15338 synchronized (mPackages) { 15339 pkgSetting = mSettings.mPackages.get(packageName); 15340 if (pkgSetting == null) { 15341 if (className == null) { 15342 throw new IllegalArgumentException("Unknown package: " + packageName); 15343 } 15344 throw new IllegalArgumentException( 15345 "Unknown component: " + packageName + "/" + className); 15346 } 15347 // Allow root and verify that userId is not being specified by a different user 15348 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15349 throw new SecurityException( 15350 "Permission Denial: attempt to change component state from pid=" 15351 + Binder.getCallingPid() 15352 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15353 } 15354 if (className == null) { 15355 // We're dealing with an application/package level state change 15356 if (pkgSetting.getEnabled(userId) == newState) { 15357 // Nothing to do 15358 return; 15359 } 15360 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15361 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15362 // Don't care about who enables an app. 15363 callingPackage = null; 15364 } 15365 pkgSetting.setEnabled(newState, userId, callingPackage); 15366 // pkgSetting.pkg.mSetEnabled = newState; 15367 } else { 15368 // We're dealing with a component level state change 15369 // First, verify that this is a valid class name. 15370 PackageParser.Package pkg = pkgSetting.pkg; 15371 if (pkg == null || !pkg.hasComponentClassName(className)) { 15372 if (pkg != null && 15373 pkg.applicationInfo.targetSdkVersion >= 15374 Build.VERSION_CODES.JELLY_BEAN) { 15375 throw new IllegalArgumentException("Component class " + className 15376 + " does not exist in " + packageName); 15377 } else { 15378 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 15379 + className + " does not exist in " + packageName); 15380 } 15381 } 15382 switch (newState) { 15383 case COMPONENT_ENABLED_STATE_ENABLED: 15384 if (!pkgSetting.enableComponentLPw(className, userId)) { 15385 return; 15386 } 15387 break; 15388 case COMPONENT_ENABLED_STATE_DISABLED: 15389 if (!pkgSetting.disableComponentLPw(className, userId)) { 15390 return; 15391 } 15392 break; 15393 case COMPONENT_ENABLED_STATE_DEFAULT: 15394 if (!pkgSetting.restoreComponentLPw(className, userId)) { 15395 return; 15396 } 15397 break; 15398 default: 15399 Slog.e(TAG, "Invalid new component state: " + newState); 15400 return; 15401 } 15402 } 15403 scheduleWritePackageRestrictionsLocked(userId); 15404 components = mPendingBroadcasts.get(userId, packageName); 15405 final boolean newPackage = components == null; 15406 if (newPackage) { 15407 components = new ArrayList<String>(); 15408 } 15409 if (!components.contains(componentName)) { 15410 components.add(componentName); 15411 } 15412 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 15413 sendNow = true; 15414 // Purge entry from pending broadcast list if another one exists already 15415 // since we are sending one right away. 15416 mPendingBroadcasts.remove(userId, packageName); 15417 } else { 15418 if (newPackage) { 15419 mPendingBroadcasts.put(userId, packageName, components); 15420 } 15421 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 15422 // Schedule a message 15423 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 15424 } 15425 } 15426 } 15427 15428 long callingId = Binder.clearCallingIdentity(); 15429 try { 15430 if (sendNow) { 15431 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 15432 sendPackageChangedBroadcast(packageName, 15433 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 15434 } 15435 } finally { 15436 Binder.restoreCallingIdentity(callingId); 15437 } 15438 } 15439 15440 private void sendPackageChangedBroadcast(String packageName, 15441 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 15442 if (DEBUG_INSTALL) 15443 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 15444 + componentNames); 15445 Bundle extras = new Bundle(4); 15446 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 15447 String nameList[] = new String[componentNames.size()]; 15448 componentNames.toArray(nameList); 15449 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 15450 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 15451 extras.putInt(Intent.EXTRA_UID, packageUid); 15452 // If this is not reporting a change of the overall package, then only send it 15453 // to registered receivers. We don't want to launch a swath of apps for every 15454 // little component state change. 15455 final int flags = !componentNames.contains(packageName) 15456 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 15457 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 15458 new int[] {UserHandle.getUserId(packageUid)}); 15459 } 15460 15461 @Override 15462 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 15463 if (!sUserManager.exists(userId)) return; 15464 final int uid = Binder.getCallingUid(); 15465 final int permission = mContext.checkCallingOrSelfPermission( 15466 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15467 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15468 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 15469 // writer 15470 synchronized (mPackages) { 15471 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 15472 allowedByPermission, uid, userId)) { 15473 scheduleWritePackageRestrictionsLocked(userId); 15474 } 15475 } 15476 } 15477 15478 @Override 15479 public String getInstallerPackageName(String packageName) { 15480 // reader 15481 synchronized (mPackages) { 15482 return mSettings.getInstallerPackageNameLPr(packageName); 15483 } 15484 } 15485 15486 @Override 15487 public int getApplicationEnabledSetting(String packageName, int userId) { 15488 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15489 int uid = Binder.getCallingUid(); 15490 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 15491 // reader 15492 synchronized (mPackages) { 15493 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 15494 } 15495 } 15496 15497 @Override 15498 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 15499 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 15500 int uid = Binder.getCallingUid(); 15501 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 15502 // reader 15503 synchronized (mPackages) { 15504 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 15505 } 15506 } 15507 15508 @Override 15509 public void enterSafeMode() { 15510 enforceSystemOrRoot("Only the system can request entering safe mode"); 15511 15512 if (!mSystemReady) { 15513 mSafeMode = true; 15514 } 15515 } 15516 15517 @Override 15518 public void systemReady() { 15519 mSystemReady = true; 15520 15521 // Read the compatibilty setting when the system is ready. 15522 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 15523 mContext.getContentResolver(), 15524 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 15525 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 15526 if (DEBUG_SETTINGS) { 15527 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 15528 } 15529 15530 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 15531 15532 synchronized (mPackages) { 15533 // Verify that all of the preferred activity components actually 15534 // exist. It is possible for applications to be updated and at 15535 // that point remove a previously declared activity component that 15536 // had been set as a preferred activity. We try to clean this up 15537 // the next time we encounter that preferred activity, but it is 15538 // possible for the user flow to never be able to return to that 15539 // situation so here we do a sanity check to make sure we haven't 15540 // left any junk around. 15541 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 15542 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15543 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15544 removed.clear(); 15545 for (PreferredActivity pa : pir.filterSet()) { 15546 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 15547 removed.add(pa); 15548 } 15549 } 15550 if (removed.size() > 0) { 15551 for (int r=0; r<removed.size(); r++) { 15552 PreferredActivity pa = removed.get(r); 15553 Slog.w(TAG, "Removing dangling preferred activity: " 15554 + pa.mPref.mComponent); 15555 pir.removeFilter(pa); 15556 } 15557 mSettings.writePackageRestrictionsLPr( 15558 mSettings.mPreferredActivities.keyAt(i)); 15559 } 15560 } 15561 15562 for (int userId : UserManagerService.getInstance().getUserIds()) { 15563 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 15564 grantPermissionsUserIds = ArrayUtils.appendInt( 15565 grantPermissionsUserIds, userId); 15566 } 15567 } 15568 } 15569 sUserManager.systemReady(); 15570 15571 // If we upgraded grant all default permissions before kicking off. 15572 for (int userId : grantPermissionsUserIds) { 15573 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 15574 } 15575 15576 // Kick off any messages waiting for system ready 15577 if (mPostSystemReadyMessages != null) { 15578 for (Message msg : mPostSystemReadyMessages) { 15579 msg.sendToTarget(); 15580 } 15581 mPostSystemReadyMessages = null; 15582 } 15583 15584 // Watch for external volumes that come and go over time 15585 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15586 storage.registerListener(mStorageListener); 15587 15588 mInstallerService.systemReady(); 15589 mPackageDexOptimizer.systemReady(); 15590 15591 MountServiceInternal mountServiceInternal = LocalServices.getService( 15592 MountServiceInternal.class); 15593 mountServiceInternal.addExternalStoragePolicy( 15594 new MountServiceInternal.ExternalStorageMountPolicy() { 15595 @Override 15596 public int getMountMode(int uid, String packageName) { 15597 if (Process.isIsolated(uid)) { 15598 return Zygote.MOUNT_EXTERNAL_NONE; 15599 } 15600 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 15601 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15602 } 15603 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15604 return Zygote.MOUNT_EXTERNAL_DEFAULT; 15605 } 15606 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 15607 return Zygote.MOUNT_EXTERNAL_READ; 15608 } 15609 return Zygote.MOUNT_EXTERNAL_WRITE; 15610 } 15611 15612 @Override 15613 public boolean hasExternalStorage(int uid, String packageName) { 15614 return true; 15615 } 15616 }); 15617 } 15618 15619 @Override 15620 public boolean isSafeMode() { 15621 return mSafeMode; 15622 } 15623 15624 @Override 15625 public boolean hasSystemUidErrors() { 15626 return mHasSystemUidErrors; 15627 } 15628 15629 static String arrayToString(int[] array) { 15630 StringBuffer buf = new StringBuffer(128); 15631 buf.append('['); 15632 if (array != null) { 15633 for (int i=0; i<array.length; i++) { 15634 if (i > 0) buf.append(", "); 15635 buf.append(array[i]); 15636 } 15637 } 15638 buf.append(']'); 15639 return buf.toString(); 15640 } 15641 15642 static class DumpState { 15643 public static final int DUMP_LIBS = 1 << 0; 15644 public static final int DUMP_FEATURES = 1 << 1; 15645 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 15646 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 15647 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 15648 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 15649 public static final int DUMP_PERMISSIONS = 1 << 6; 15650 public static final int DUMP_PACKAGES = 1 << 7; 15651 public static final int DUMP_SHARED_USERS = 1 << 8; 15652 public static final int DUMP_MESSAGES = 1 << 9; 15653 public static final int DUMP_PROVIDERS = 1 << 10; 15654 public static final int DUMP_VERIFIERS = 1 << 11; 15655 public static final int DUMP_PREFERRED = 1 << 12; 15656 public static final int DUMP_PREFERRED_XML = 1 << 13; 15657 public static final int DUMP_KEYSETS = 1 << 14; 15658 public static final int DUMP_VERSION = 1 << 15; 15659 public static final int DUMP_INSTALLS = 1 << 16; 15660 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 15661 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 15662 15663 public static final int OPTION_SHOW_FILTERS = 1 << 0; 15664 15665 private int mTypes; 15666 15667 private int mOptions; 15668 15669 private boolean mTitlePrinted; 15670 15671 private SharedUserSetting mSharedUser; 15672 15673 public boolean isDumping(int type) { 15674 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 15675 return true; 15676 } 15677 15678 return (mTypes & type) != 0; 15679 } 15680 15681 public void setDump(int type) { 15682 mTypes |= type; 15683 } 15684 15685 public boolean isOptionEnabled(int option) { 15686 return (mOptions & option) != 0; 15687 } 15688 15689 public void setOptionEnabled(int option) { 15690 mOptions |= option; 15691 } 15692 15693 public boolean onTitlePrinted() { 15694 final boolean printed = mTitlePrinted; 15695 mTitlePrinted = true; 15696 return printed; 15697 } 15698 15699 public boolean getTitlePrinted() { 15700 return mTitlePrinted; 15701 } 15702 15703 public void setTitlePrinted(boolean enabled) { 15704 mTitlePrinted = enabled; 15705 } 15706 15707 public SharedUserSetting getSharedUser() { 15708 return mSharedUser; 15709 } 15710 15711 public void setSharedUser(SharedUserSetting user) { 15712 mSharedUser = user; 15713 } 15714 } 15715 15716 @Override 15717 public void onShellCommand(FileDescriptor in, FileDescriptor out, 15718 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 15719 (new PackageManagerShellCommand(this)).exec( 15720 this, in, out, err, args, resultReceiver); 15721 } 15722 15723 @Override 15724 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 15725 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 15726 != PackageManager.PERMISSION_GRANTED) { 15727 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 15728 + Binder.getCallingPid() 15729 + ", uid=" + Binder.getCallingUid() 15730 + " without permission " 15731 + android.Manifest.permission.DUMP); 15732 return; 15733 } 15734 15735 DumpState dumpState = new DumpState(); 15736 boolean fullPreferred = false; 15737 boolean checkin = false; 15738 15739 String packageName = null; 15740 ArraySet<String> permissionNames = null; 15741 15742 int opti = 0; 15743 while (opti < args.length) { 15744 String opt = args[opti]; 15745 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 15746 break; 15747 } 15748 opti++; 15749 15750 if ("-a".equals(opt)) { 15751 // Right now we only know how to print all. 15752 } else if ("-h".equals(opt)) { 15753 pw.println("Package manager dump options:"); 15754 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 15755 pw.println(" --checkin: dump for a checkin"); 15756 pw.println(" -f: print details of intent filters"); 15757 pw.println(" -h: print this help"); 15758 pw.println(" cmd may be one of:"); 15759 pw.println(" l[ibraries]: list known shared libraries"); 15760 pw.println(" f[eatures]: list device features"); 15761 pw.println(" k[eysets]: print known keysets"); 15762 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 15763 pw.println(" perm[issions]: dump permissions"); 15764 pw.println(" permission [name ...]: dump declaration and use of given permission"); 15765 pw.println(" pref[erred]: print preferred package settings"); 15766 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 15767 pw.println(" prov[iders]: dump content providers"); 15768 pw.println(" p[ackages]: dump installed packages"); 15769 pw.println(" s[hared-users]: dump shared user IDs"); 15770 pw.println(" m[essages]: print collected runtime messages"); 15771 pw.println(" v[erifiers]: print package verifier info"); 15772 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 15773 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 15774 pw.println(" version: print database version info"); 15775 pw.println(" write: write current settings now"); 15776 pw.println(" installs: details about install sessions"); 15777 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 15778 pw.println(" <package.name>: info about given package"); 15779 return; 15780 } else if ("--checkin".equals(opt)) { 15781 checkin = true; 15782 } else if ("-f".equals(opt)) { 15783 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15784 } else { 15785 pw.println("Unknown argument: " + opt + "; use -h for help"); 15786 } 15787 } 15788 15789 // Is the caller requesting to dump a particular piece of data? 15790 if (opti < args.length) { 15791 String cmd = args[opti]; 15792 opti++; 15793 // Is this a package name? 15794 if ("android".equals(cmd) || cmd.contains(".")) { 15795 packageName = cmd; 15796 // When dumping a single package, we always dump all of its 15797 // filter information since the amount of data will be reasonable. 15798 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 15799 } else if ("check-permission".equals(cmd)) { 15800 if (opti >= args.length) { 15801 pw.println("Error: check-permission missing permission argument"); 15802 return; 15803 } 15804 String perm = args[opti]; 15805 opti++; 15806 if (opti >= args.length) { 15807 pw.println("Error: check-permission missing package argument"); 15808 return; 15809 } 15810 String pkg = args[opti]; 15811 opti++; 15812 int user = UserHandle.getUserId(Binder.getCallingUid()); 15813 if (opti < args.length) { 15814 try { 15815 user = Integer.parseInt(args[opti]); 15816 } catch (NumberFormatException e) { 15817 pw.println("Error: check-permission user argument is not a number: " 15818 + args[opti]); 15819 return; 15820 } 15821 } 15822 pw.println(checkPermission(perm, pkg, user)); 15823 return; 15824 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 15825 dumpState.setDump(DumpState.DUMP_LIBS); 15826 } else if ("f".equals(cmd) || "features".equals(cmd)) { 15827 dumpState.setDump(DumpState.DUMP_FEATURES); 15828 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 15829 if (opti >= args.length) { 15830 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 15831 | DumpState.DUMP_SERVICE_RESOLVERS 15832 | DumpState.DUMP_RECEIVER_RESOLVERS 15833 | DumpState.DUMP_CONTENT_RESOLVERS); 15834 } else { 15835 while (opti < args.length) { 15836 String name = args[opti]; 15837 if ("a".equals(name) || "activity".equals(name)) { 15838 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 15839 } else if ("s".equals(name) || "service".equals(name)) { 15840 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 15841 } else if ("r".equals(name) || "receiver".equals(name)) { 15842 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 15843 } else if ("c".equals(name) || "content".equals(name)) { 15844 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 15845 } else { 15846 pw.println("Error: unknown resolver table type: " + name); 15847 return; 15848 } 15849 opti++; 15850 } 15851 } 15852 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 15853 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 15854 } else if ("permission".equals(cmd)) { 15855 if (opti >= args.length) { 15856 pw.println("Error: permission requires permission name"); 15857 return; 15858 } 15859 permissionNames = new ArraySet<>(); 15860 while (opti < args.length) { 15861 permissionNames.add(args[opti]); 15862 opti++; 15863 } 15864 dumpState.setDump(DumpState.DUMP_PERMISSIONS 15865 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 15866 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 15867 dumpState.setDump(DumpState.DUMP_PREFERRED); 15868 } else if ("preferred-xml".equals(cmd)) { 15869 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 15870 if (opti < args.length && "--full".equals(args[opti])) { 15871 fullPreferred = true; 15872 opti++; 15873 } 15874 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 15875 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 15876 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 15877 dumpState.setDump(DumpState.DUMP_PACKAGES); 15878 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 15879 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 15880 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 15881 dumpState.setDump(DumpState.DUMP_PROVIDERS); 15882 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 15883 dumpState.setDump(DumpState.DUMP_MESSAGES); 15884 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 15885 dumpState.setDump(DumpState.DUMP_VERIFIERS); 15886 } else if ("i".equals(cmd) || "ifv".equals(cmd) 15887 || "intent-filter-verifiers".equals(cmd)) { 15888 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 15889 } else if ("version".equals(cmd)) { 15890 dumpState.setDump(DumpState.DUMP_VERSION); 15891 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 15892 dumpState.setDump(DumpState.DUMP_KEYSETS); 15893 } else if ("installs".equals(cmd)) { 15894 dumpState.setDump(DumpState.DUMP_INSTALLS); 15895 } else if ("write".equals(cmd)) { 15896 synchronized (mPackages) { 15897 mSettings.writeLPr(); 15898 pw.println("Settings written."); 15899 return; 15900 } 15901 } 15902 } 15903 15904 if (checkin) { 15905 pw.println("vers,1"); 15906 } 15907 15908 // reader 15909 synchronized (mPackages) { 15910 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 15911 if (!checkin) { 15912 if (dumpState.onTitlePrinted()) 15913 pw.println(); 15914 pw.println("Database versions:"); 15915 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 15916 } 15917 } 15918 15919 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 15920 if (!checkin) { 15921 if (dumpState.onTitlePrinted()) 15922 pw.println(); 15923 pw.println("Verifiers:"); 15924 pw.print(" Required: "); 15925 pw.print(mRequiredVerifierPackage); 15926 pw.print(" (uid="); 15927 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15928 UserHandle.USER_SYSTEM)); 15929 pw.println(")"); 15930 } else if (mRequiredVerifierPackage != null) { 15931 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 15932 pw.print(","); 15933 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15934 UserHandle.USER_SYSTEM)); 15935 } 15936 } 15937 15938 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 15939 packageName == null) { 15940 if (mIntentFilterVerifierComponent != null) { 15941 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 15942 if (!checkin) { 15943 if (dumpState.onTitlePrinted()) 15944 pw.println(); 15945 pw.println("Intent Filter Verifier:"); 15946 pw.print(" Using: "); 15947 pw.print(verifierPackageName); 15948 pw.print(" (uid="); 15949 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15950 UserHandle.USER_SYSTEM)); 15951 pw.println(")"); 15952 } else if (verifierPackageName != null) { 15953 pw.print("ifv,"); pw.print(verifierPackageName); 15954 pw.print(","); 15955 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 15956 UserHandle.USER_SYSTEM)); 15957 } 15958 } else { 15959 pw.println(); 15960 pw.println("No Intent Filter Verifier available!"); 15961 } 15962 } 15963 15964 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 15965 boolean printedHeader = false; 15966 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 15967 while (it.hasNext()) { 15968 String name = it.next(); 15969 SharedLibraryEntry ent = mSharedLibraries.get(name); 15970 if (!checkin) { 15971 if (!printedHeader) { 15972 if (dumpState.onTitlePrinted()) 15973 pw.println(); 15974 pw.println("Libraries:"); 15975 printedHeader = true; 15976 } 15977 pw.print(" "); 15978 } else { 15979 pw.print("lib,"); 15980 } 15981 pw.print(name); 15982 if (!checkin) { 15983 pw.print(" -> "); 15984 } 15985 if (ent.path != null) { 15986 if (!checkin) { 15987 pw.print("(jar) "); 15988 pw.print(ent.path); 15989 } else { 15990 pw.print(",jar,"); 15991 pw.print(ent.path); 15992 } 15993 } else { 15994 if (!checkin) { 15995 pw.print("(apk) "); 15996 pw.print(ent.apk); 15997 } else { 15998 pw.print(",apk,"); 15999 pw.print(ent.apk); 16000 } 16001 } 16002 pw.println(); 16003 } 16004 } 16005 16006 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16007 if (dumpState.onTitlePrinted()) 16008 pw.println(); 16009 if (!checkin) { 16010 pw.println("Features:"); 16011 } 16012 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16013 while (it.hasNext()) { 16014 String name = it.next(); 16015 if (!checkin) { 16016 pw.print(" "); 16017 } else { 16018 pw.print("feat,"); 16019 } 16020 pw.println(name); 16021 } 16022 } 16023 16024 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16025 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16026 : "Activity Resolver Table:", " ", packageName, 16027 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16028 dumpState.setTitlePrinted(true); 16029 } 16030 } 16031 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16032 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16033 : "Receiver Resolver Table:", " ", packageName, 16034 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16035 dumpState.setTitlePrinted(true); 16036 } 16037 } 16038 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16039 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16040 : "Service Resolver Table:", " ", packageName, 16041 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16042 dumpState.setTitlePrinted(true); 16043 } 16044 } 16045 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16046 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16047 : "Provider Resolver Table:", " ", packageName, 16048 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16049 dumpState.setTitlePrinted(true); 16050 } 16051 } 16052 16053 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16054 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16055 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16056 int user = mSettings.mPreferredActivities.keyAt(i); 16057 if (pir.dump(pw, 16058 dumpState.getTitlePrinted() 16059 ? "\nPreferred Activities User " + user + ":" 16060 : "Preferred Activities User " + user + ":", " ", 16061 packageName, true, false)) { 16062 dumpState.setTitlePrinted(true); 16063 } 16064 } 16065 } 16066 16067 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16068 pw.flush(); 16069 FileOutputStream fout = new FileOutputStream(fd); 16070 BufferedOutputStream str = new BufferedOutputStream(fout); 16071 XmlSerializer serializer = new FastXmlSerializer(); 16072 try { 16073 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16074 serializer.startDocument(null, true); 16075 serializer.setFeature( 16076 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16077 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16078 serializer.endDocument(); 16079 serializer.flush(); 16080 } catch (IllegalArgumentException e) { 16081 pw.println("Failed writing: " + e); 16082 } catch (IllegalStateException e) { 16083 pw.println("Failed writing: " + e); 16084 } catch (IOException e) { 16085 pw.println("Failed writing: " + e); 16086 } 16087 } 16088 16089 if (!checkin 16090 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16091 && packageName == null) { 16092 pw.println(); 16093 int count = mSettings.mPackages.size(); 16094 if (count == 0) { 16095 pw.println("No applications!"); 16096 pw.println(); 16097 } else { 16098 final String prefix = " "; 16099 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16100 if (allPackageSettings.size() == 0) { 16101 pw.println("No domain preferred apps!"); 16102 pw.println(); 16103 } else { 16104 pw.println("App verification status:"); 16105 pw.println(); 16106 count = 0; 16107 for (PackageSetting ps : allPackageSettings) { 16108 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16109 if (ivi == null || ivi.getPackageName() == null) continue; 16110 pw.println(prefix + "Package: " + ivi.getPackageName()); 16111 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16112 pw.println(prefix + "Status: " + ivi.getStatusString()); 16113 pw.println(); 16114 count++; 16115 } 16116 if (count == 0) { 16117 pw.println(prefix + "No app verification established."); 16118 pw.println(); 16119 } 16120 for (int userId : sUserManager.getUserIds()) { 16121 pw.println("App linkages for user " + userId + ":"); 16122 pw.println(); 16123 count = 0; 16124 for (PackageSetting ps : allPackageSettings) { 16125 final long status = ps.getDomainVerificationStatusForUser(userId); 16126 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16127 continue; 16128 } 16129 pw.println(prefix + "Package: " + ps.name); 16130 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16131 String statusStr = IntentFilterVerificationInfo. 16132 getStatusStringFromValue(status); 16133 pw.println(prefix + "Status: " + statusStr); 16134 pw.println(); 16135 count++; 16136 } 16137 if (count == 0) { 16138 pw.println(prefix + "No configured app linkages."); 16139 pw.println(); 16140 } 16141 } 16142 } 16143 } 16144 } 16145 16146 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16147 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16148 if (packageName == null && permissionNames == null) { 16149 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16150 if (iperm == 0) { 16151 if (dumpState.onTitlePrinted()) 16152 pw.println(); 16153 pw.println("AppOp Permissions:"); 16154 } 16155 pw.print(" AppOp Permission "); 16156 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16157 pw.println(":"); 16158 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16159 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16160 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16161 } 16162 } 16163 } 16164 } 16165 16166 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16167 boolean printedSomething = false; 16168 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16169 if (packageName != null && !packageName.equals(p.info.packageName)) { 16170 continue; 16171 } 16172 if (!printedSomething) { 16173 if (dumpState.onTitlePrinted()) 16174 pw.println(); 16175 pw.println("Registered ContentProviders:"); 16176 printedSomething = true; 16177 } 16178 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16179 pw.print(" "); pw.println(p.toString()); 16180 } 16181 printedSomething = false; 16182 for (Map.Entry<String, PackageParser.Provider> entry : 16183 mProvidersByAuthority.entrySet()) { 16184 PackageParser.Provider p = entry.getValue(); 16185 if (packageName != null && !packageName.equals(p.info.packageName)) { 16186 continue; 16187 } 16188 if (!printedSomething) { 16189 if (dumpState.onTitlePrinted()) 16190 pw.println(); 16191 pw.println("ContentProvider Authorities:"); 16192 printedSomething = true; 16193 } 16194 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16195 pw.print(" "); pw.println(p.toString()); 16196 if (p.info != null && p.info.applicationInfo != null) { 16197 final String appInfo = p.info.applicationInfo.toString(); 16198 pw.print(" applicationInfo="); pw.println(appInfo); 16199 } 16200 } 16201 } 16202 16203 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16204 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16205 } 16206 16207 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16208 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16209 } 16210 16211 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16212 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16213 } 16214 16215 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16216 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16217 } 16218 16219 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16220 // XXX should handle packageName != null by dumping only install data that 16221 // the given package is involved with. 16222 if (dumpState.onTitlePrinted()) pw.println(); 16223 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16224 } 16225 16226 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16227 if (dumpState.onTitlePrinted()) pw.println(); 16228 mSettings.dumpReadMessagesLPr(pw, dumpState); 16229 16230 pw.println(); 16231 pw.println("Package warning messages:"); 16232 BufferedReader in = null; 16233 String line = null; 16234 try { 16235 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16236 while ((line = in.readLine()) != null) { 16237 if (line.contains("ignored: updated version")) continue; 16238 pw.println(line); 16239 } 16240 } catch (IOException ignored) { 16241 } finally { 16242 IoUtils.closeQuietly(in); 16243 } 16244 } 16245 16246 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16247 BufferedReader in = null; 16248 String line = null; 16249 try { 16250 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16251 while ((line = in.readLine()) != null) { 16252 if (line.contains("ignored: updated version")) continue; 16253 pw.print("msg,"); 16254 pw.println(line); 16255 } 16256 } catch (IOException ignored) { 16257 } finally { 16258 IoUtils.closeQuietly(in); 16259 } 16260 } 16261 } 16262 } 16263 16264 private String dumpDomainString(String packageName) { 16265 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16266 List<IntentFilter> filters = getAllIntentFilters(packageName); 16267 16268 ArraySet<String> result = new ArraySet<>(); 16269 if (iviList.size() > 0) { 16270 for (IntentFilterVerificationInfo ivi : iviList) { 16271 for (String host : ivi.getDomains()) { 16272 result.add(host); 16273 } 16274 } 16275 } 16276 if (filters != null && filters.size() > 0) { 16277 for (IntentFilter filter : filters) { 16278 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16279 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16280 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16281 result.addAll(filter.getHostsList()); 16282 } 16283 } 16284 } 16285 16286 StringBuilder sb = new StringBuilder(result.size() * 16); 16287 for (String domain : result) { 16288 if (sb.length() > 0) sb.append(" "); 16289 sb.append(domain); 16290 } 16291 return sb.toString(); 16292 } 16293 16294 // ------- apps on sdcard specific code ------- 16295 static final boolean DEBUG_SD_INSTALL = false; 16296 16297 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16298 16299 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16300 16301 private boolean mMediaMounted = false; 16302 16303 static String getEncryptKey() { 16304 try { 16305 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16306 SD_ENCRYPTION_KEYSTORE_NAME); 16307 if (sdEncKey == null) { 16308 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16309 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16310 if (sdEncKey == null) { 16311 Slog.e(TAG, "Failed to create encryption keys"); 16312 return null; 16313 } 16314 } 16315 return sdEncKey; 16316 } catch (NoSuchAlgorithmException nsae) { 16317 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16318 return null; 16319 } catch (IOException ioe) { 16320 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16321 return null; 16322 } 16323 } 16324 16325 /* 16326 * Update media status on PackageManager. 16327 */ 16328 @Override 16329 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16330 int callingUid = Binder.getCallingUid(); 16331 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16332 throw new SecurityException("Media status can only be updated by the system"); 16333 } 16334 // reader; this apparently protects mMediaMounted, but should probably 16335 // be a different lock in that case. 16336 synchronized (mPackages) { 16337 Log.i(TAG, "Updating external media status from " 16338 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16339 + (mediaStatus ? "mounted" : "unmounted")); 16340 if (DEBUG_SD_INSTALL) 16341 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16342 + ", mMediaMounted=" + mMediaMounted); 16343 if (mediaStatus == mMediaMounted) { 16344 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16345 : 0, -1); 16346 mHandler.sendMessage(msg); 16347 return; 16348 } 16349 mMediaMounted = mediaStatus; 16350 } 16351 // Queue up an async operation since the package installation may take a 16352 // little while. 16353 mHandler.post(new Runnable() { 16354 public void run() { 16355 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16356 } 16357 }); 16358 } 16359 16360 /** 16361 * Called by MountService when the initial ASECs to scan are available. 16362 * Should block until all the ASEC containers are finished being scanned. 16363 */ 16364 public void scanAvailableAsecs() { 16365 updateExternalMediaStatusInner(true, false, false); 16366 } 16367 16368 /* 16369 * Collect information of applications on external media, map them against 16370 * existing containers and update information based on current mount status. 16371 * Please note that we always have to report status if reportStatus has been 16372 * set to true especially when unloading packages. 16373 */ 16374 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16375 boolean externalStorage) { 16376 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16377 int[] uidArr = EmptyArray.INT; 16378 16379 final String[] list = PackageHelper.getSecureContainerList(); 16380 if (ArrayUtils.isEmpty(list)) { 16381 Log.i(TAG, "No secure containers found"); 16382 } else { 16383 // Process list of secure containers and categorize them 16384 // as active or stale based on their package internal state. 16385 16386 // reader 16387 synchronized (mPackages) { 16388 for (String cid : list) { 16389 // Leave stages untouched for now; installer service owns them 16390 if (PackageInstallerService.isStageName(cid)) continue; 16391 16392 if (DEBUG_SD_INSTALL) 16393 Log.i(TAG, "Processing container " + cid); 16394 String pkgName = getAsecPackageName(cid); 16395 if (pkgName == null) { 16396 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 16397 continue; 16398 } 16399 if (DEBUG_SD_INSTALL) 16400 Log.i(TAG, "Looking for pkg : " + pkgName); 16401 16402 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16403 if (ps == null) { 16404 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 16405 continue; 16406 } 16407 16408 /* 16409 * Skip packages that are not external if we're unmounting 16410 * external storage. 16411 */ 16412 if (externalStorage && !isMounted && !isExternal(ps)) { 16413 continue; 16414 } 16415 16416 final AsecInstallArgs args = new AsecInstallArgs(cid, 16417 getAppDexInstructionSets(ps), ps.isForwardLocked()); 16418 // The package status is changed only if the code path 16419 // matches between settings and the container id. 16420 if (ps.codePathString != null 16421 && ps.codePathString.startsWith(args.getCodePath())) { 16422 if (DEBUG_SD_INSTALL) { 16423 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 16424 + " at code path: " + ps.codePathString); 16425 } 16426 16427 // We do have a valid package installed on sdcard 16428 processCids.put(args, ps.codePathString); 16429 final int uid = ps.appId; 16430 if (uid != -1) { 16431 uidArr = ArrayUtils.appendInt(uidArr, uid); 16432 } 16433 } else { 16434 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 16435 + ps.codePathString); 16436 } 16437 } 16438 } 16439 16440 Arrays.sort(uidArr); 16441 } 16442 16443 // Process packages with valid entries. 16444 if (isMounted) { 16445 if (DEBUG_SD_INSTALL) 16446 Log.i(TAG, "Loading packages"); 16447 loadMediaPackages(processCids, uidArr, externalStorage); 16448 startCleaningPackages(); 16449 mInstallerService.onSecureContainersAvailable(); 16450 } else { 16451 if (DEBUG_SD_INSTALL) 16452 Log.i(TAG, "Unloading packages"); 16453 unloadMediaPackages(processCids, uidArr, reportStatus); 16454 } 16455 } 16456 16457 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16458 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 16459 final int size = infos.size(); 16460 final String[] packageNames = new String[size]; 16461 final int[] packageUids = new int[size]; 16462 for (int i = 0; i < size; i++) { 16463 final ApplicationInfo info = infos.get(i); 16464 packageNames[i] = info.packageName; 16465 packageUids[i] = info.uid; 16466 } 16467 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 16468 finishedReceiver); 16469 } 16470 16471 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16472 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16473 sendResourcesChangedBroadcast(mediaStatus, replacing, 16474 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 16475 } 16476 16477 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 16478 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 16479 int size = pkgList.length; 16480 if (size > 0) { 16481 // Send broadcasts here 16482 Bundle extras = new Bundle(); 16483 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 16484 if (uidArr != null) { 16485 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 16486 } 16487 if (replacing) { 16488 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 16489 } 16490 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 16491 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 16492 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 16493 } 16494 } 16495 16496 /* 16497 * Look at potentially valid container ids from processCids If package 16498 * information doesn't match the one on record or package scanning fails, 16499 * the cid is added to list of removeCids. We currently don't delete stale 16500 * containers. 16501 */ 16502 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 16503 boolean externalStorage) { 16504 ArrayList<String> pkgList = new ArrayList<String>(); 16505 Set<AsecInstallArgs> keys = processCids.keySet(); 16506 16507 for (AsecInstallArgs args : keys) { 16508 String codePath = processCids.get(args); 16509 if (DEBUG_SD_INSTALL) 16510 Log.i(TAG, "Loading container : " + args.cid); 16511 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 16512 try { 16513 // Make sure there are no container errors first. 16514 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 16515 Slog.e(TAG, "Failed to mount cid : " + args.cid 16516 + " when installing from sdcard"); 16517 continue; 16518 } 16519 // Check code path here. 16520 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 16521 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 16522 + " does not match one in settings " + codePath); 16523 continue; 16524 } 16525 // Parse package 16526 int parseFlags = mDefParseFlags; 16527 if (args.isExternalAsec()) { 16528 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 16529 } 16530 if (args.isFwdLocked()) { 16531 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 16532 } 16533 16534 synchronized (mInstallLock) { 16535 PackageParser.Package pkg = null; 16536 try { 16537 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 16538 } catch (PackageManagerException e) { 16539 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 16540 } 16541 // Scan the package 16542 if (pkg != null) { 16543 /* 16544 * TODO why is the lock being held? doPostInstall is 16545 * called in other places without the lock. This needs 16546 * to be straightened out. 16547 */ 16548 // writer 16549 synchronized (mPackages) { 16550 retCode = PackageManager.INSTALL_SUCCEEDED; 16551 pkgList.add(pkg.packageName); 16552 // Post process args 16553 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 16554 pkg.applicationInfo.uid); 16555 } 16556 } else { 16557 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 16558 } 16559 } 16560 16561 } finally { 16562 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 16563 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 16564 } 16565 } 16566 } 16567 // writer 16568 synchronized (mPackages) { 16569 // If the platform SDK has changed since the last time we booted, 16570 // we need to re-grant app permission to catch any new ones that 16571 // appear. This is really a hack, and means that apps can in some 16572 // cases get permissions that the user didn't initially explicitly 16573 // allow... it would be nice to have some better way to handle 16574 // this situation. 16575 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 16576 : mSettings.getInternalVersion(); 16577 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 16578 : StorageManager.UUID_PRIVATE_INTERNAL; 16579 16580 int updateFlags = UPDATE_PERMISSIONS_ALL; 16581 if (ver.sdkVersion != mSdkVersion) { 16582 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16583 + mSdkVersion + "; regranting permissions for external"); 16584 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16585 } 16586 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16587 16588 // Yay, everything is now upgraded 16589 ver.forceCurrent(); 16590 16591 // can downgrade to reader 16592 // Persist settings 16593 mSettings.writeLPr(); 16594 } 16595 // Send a broadcast to let everyone know we are done processing 16596 if (pkgList.size() > 0) { 16597 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 16598 } 16599 } 16600 16601 /* 16602 * Utility method to unload a list of specified containers 16603 */ 16604 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 16605 // Just unmount all valid containers. 16606 for (AsecInstallArgs arg : cidArgs) { 16607 synchronized (mInstallLock) { 16608 arg.doPostDeleteLI(false); 16609 } 16610 } 16611 } 16612 16613 /* 16614 * Unload packages mounted on external media. This involves deleting package 16615 * data from internal structures, sending broadcasts about diabled packages, 16616 * gc'ing to free up references, unmounting all secure containers 16617 * corresponding to packages on external media, and posting a 16618 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 16619 * that we always have to post this message if status has been requested no 16620 * matter what. 16621 */ 16622 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 16623 final boolean reportStatus) { 16624 if (DEBUG_SD_INSTALL) 16625 Log.i(TAG, "unloading media packages"); 16626 ArrayList<String> pkgList = new ArrayList<String>(); 16627 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 16628 final Set<AsecInstallArgs> keys = processCids.keySet(); 16629 for (AsecInstallArgs args : keys) { 16630 String pkgName = args.getPackageName(); 16631 if (DEBUG_SD_INSTALL) 16632 Log.i(TAG, "Trying to unload pkg : " + pkgName); 16633 // Delete package internally 16634 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16635 synchronized (mInstallLock) { 16636 boolean res = deletePackageLI(pkgName, null, false, null, null, 16637 PackageManager.DELETE_KEEP_DATA, outInfo, false); 16638 if (res) { 16639 pkgList.add(pkgName); 16640 } else { 16641 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 16642 failedList.add(args); 16643 } 16644 } 16645 } 16646 16647 // reader 16648 synchronized (mPackages) { 16649 // We didn't update the settings after removing each package; 16650 // write them now for all packages. 16651 mSettings.writeLPr(); 16652 } 16653 16654 // We have to absolutely send UPDATED_MEDIA_STATUS only 16655 // after confirming that all the receivers processed the ordered 16656 // broadcast when packages get disabled, force a gc to clean things up. 16657 // and unload all the containers. 16658 if (pkgList.size() > 0) { 16659 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 16660 new IIntentReceiver.Stub() { 16661 public void performReceive(Intent intent, int resultCode, String data, 16662 Bundle extras, boolean ordered, boolean sticky, 16663 int sendingUser) throws RemoteException { 16664 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 16665 reportStatus ? 1 : 0, 1, keys); 16666 mHandler.sendMessage(msg); 16667 } 16668 }); 16669 } else { 16670 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 16671 keys); 16672 mHandler.sendMessage(msg); 16673 } 16674 } 16675 16676 private void loadPrivatePackages(final VolumeInfo vol) { 16677 mHandler.post(new Runnable() { 16678 @Override 16679 public void run() { 16680 loadPrivatePackagesInner(vol); 16681 } 16682 }); 16683 } 16684 16685 private void loadPrivatePackagesInner(VolumeInfo vol) { 16686 final String volumeUuid = vol.fsUuid; 16687 if (TextUtils.isEmpty(volumeUuid)) { 16688 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 16689 return; 16690 } 16691 16692 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 16693 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 16694 16695 final VersionInfo ver; 16696 final List<PackageSetting> packages; 16697 synchronized (mPackages) { 16698 ver = mSettings.findOrCreateVersion(volumeUuid); 16699 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16700 } 16701 16702 // TODO: introduce a new concept similar to "frozen" to prevent these 16703 // apps from being launched until after data has been fully reconciled 16704 for (PackageSetting ps : packages) { 16705 synchronized (mInstallLock) { 16706 final PackageParser.Package pkg; 16707 try { 16708 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 16709 loaded.add(pkg.applicationInfo); 16710 16711 } catch (PackageManagerException e) { 16712 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 16713 } 16714 16715 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 16716 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 16717 } 16718 } 16719 } 16720 16721 // Reconcile app data for all started/unlocked users 16722 final UserManager um = mContext.getSystemService(UserManager.class); 16723 for (UserInfo user : um.getUsers()) { 16724 if (um.isUserUnlocked(user.id)) { 16725 reconcileAppsData(volumeUuid, user.id, 16726 Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE); 16727 } else if (um.isUserRunning(user.id)) { 16728 reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE); 16729 } else { 16730 continue; 16731 } 16732 } 16733 16734 synchronized (mPackages) { 16735 int updateFlags = UPDATE_PERMISSIONS_ALL; 16736 if (ver.sdkVersion != mSdkVersion) { 16737 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 16738 + mSdkVersion + "; regranting permissions for " + volumeUuid); 16739 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 16740 } 16741 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 16742 16743 // Yay, everything is now upgraded 16744 ver.forceCurrent(); 16745 16746 mSettings.writeLPr(); 16747 } 16748 16749 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 16750 sendResourcesChangedBroadcast(true, false, loaded, null); 16751 } 16752 16753 private void unloadPrivatePackages(final VolumeInfo vol) { 16754 mHandler.post(new Runnable() { 16755 @Override 16756 public void run() { 16757 unloadPrivatePackagesInner(vol); 16758 } 16759 }); 16760 } 16761 16762 private void unloadPrivatePackagesInner(VolumeInfo vol) { 16763 final String volumeUuid = vol.fsUuid; 16764 if (TextUtils.isEmpty(volumeUuid)) { 16765 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 16766 return; 16767 } 16768 16769 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 16770 synchronized (mInstallLock) { 16771 synchronized (mPackages) { 16772 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 16773 for (PackageSetting ps : packages) { 16774 if (ps.pkg == null) continue; 16775 16776 final ApplicationInfo info = ps.pkg.applicationInfo; 16777 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 16778 if (deletePackageLI(ps.name, null, false, null, null, 16779 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 16780 unloaded.add(info); 16781 } else { 16782 Slog.w(TAG, "Failed to unload " + ps.codePath); 16783 } 16784 } 16785 16786 mSettings.writeLPr(); 16787 } 16788 } 16789 16790 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 16791 sendResourcesChangedBroadcast(false, false, unloaded, null); 16792 } 16793 16794 /** 16795 * Examine all users present on given mounted volume, and destroy data 16796 * belonging to users that are no longer valid, or whose user ID has been 16797 * recycled. 16798 */ 16799 private void reconcileUsers(String volumeUuid) { 16800 final File[] files = FileUtils 16801 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 16802 for (File file : files) { 16803 if (!file.isDirectory()) continue; 16804 16805 final int userId; 16806 final UserInfo info; 16807 try { 16808 userId = Integer.parseInt(file.getName()); 16809 info = sUserManager.getUserInfo(userId); 16810 } catch (NumberFormatException e) { 16811 Slog.w(TAG, "Invalid user directory " + file); 16812 continue; 16813 } 16814 16815 boolean destroyUser = false; 16816 if (info == null) { 16817 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16818 + " because no matching user was found"); 16819 destroyUser = true; 16820 } else { 16821 try { 16822 UserManagerService.enforceSerialNumber(file, info.serialNumber); 16823 } catch (IOException e) { 16824 logCriticalInfo(Log.WARN, "Destroying user directory " + file 16825 + " because we failed to enforce serial number: " + e); 16826 destroyUser = true; 16827 } 16828 } 16829 16830 if (destroyUser) { 16831 synchronized (mInstallLock) { 16832 try { 16833 mInstaller.removeUserDataDirs(volumeUuid, userId); 16834 } catch (InstallerException e) { 16835 Slog.w(TAG, "Failed to clean up user dirs", e); 16836 } 16837 } 16838 } 16839 } 16840 16841 final StorageManager sm = mContext.getSystemService(StorageManager.class); 16842 final UserManager um = mContext.getSystemService(UserManager.class); 16843 for (UserInfo user : um.getUsers()) { 16844 final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id); 16845 if (userDir.exists()) continue; 16846 16847 try { 16848 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral()); 16849 UserManagerService.enforceSerialNumber(userDir, user.serialNumber); 16850 } catch (IOException e) { 16851 Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e); 16852 } 16853 } 16854 } 16855 16856 private void assertPackageKnown(String volumeUuid, String packageName) 16857 throws PackageManagerException { 16858 synchronized (mPackages) { 16859 final PackageSetting ps = mSettings.mPackages.get(packageName); 16860 if (ps == null) { 16861 throw new PackageManagerException("Package " + packageName + " is unknown"); 16862 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16863 throw new PackageManagerException( 16864 "Package " + packageName + " found on unknown volume " + volumeUuid 16865 + "; expected volume " + ps.volumeUuid); 16866 } 16867 } 16868 } 16869 16870 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 16871 throws PackageManagerException { 16872 synchronized (mPackages) { 16873 final PackageSetting ps = mSettings.mPackages.get(packageName); 16874 if (ps == null) { 16875 throw new PackageManagerException("Package " + packageName + " is unknown"); 16876 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 16877 throw new PackageManagerException( 16878 "Package " + packageName + " found on unknown volume " + volumeUuid 16879 + "; expected volume " + ps.volumeUuid); 16880 } else if (!ps.getInstalled(userId)) { 16881 throw new PackageManagerException( 16882 "Package " + packageName + " not installed for user " + userId); 16883 } 16884 } 16885 } 16886 16887 /** 16888 * Examine all apps present on given mounted volume, and destroy apps that 16889 * aren't expected, either due to uninstallation or reinstallation on 16890 * another volume. 16891 */ 16892 private void reconcileApps(String volumeUuid) { 16893 final File[] files = FileUtils 16894 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 16895 for (File file : files) { 16896 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 16897 && !PackageInstallerService.isStageName(file.getName()); 16898 if (!isPackage) { 16899 // Ignore entries which are not packages 16900 continue; 16901 } 16902 16903 try { 16904 final PackageLite pkg = PackageParser.parsePackageLite(file, 16905 PackageParser.PARSE_MUST_BE_APK); 16906 assertPackageKnown(volumeUuid, pkg.packageName); 16907 16908 } catch (PackageParserException | PackageManagerException e) { 16909 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16910 synchronized (mInstallLock) { 16911 removeCodePathLI(file); 16912 } 16913 } 16914 } 16915 } 16916 16917 /** 16918 * Reconcile all app data for the given user. 16919 * <p> 16920 * Verifies that directories exist and that ownership and labeling is 16921 * correct for all installed apps on all mounted volumes. 16922 */ 16923 void reconcileAppsData(int userId, @StorageFlags int flags) { 16924 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16925 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 16926 final String volumeUuid = vol.getFsUuid(); 16927 reconcileAppsData(volumeUuid, userId, flags); 16928 } 16929 } 16930 16931 /** 16932 * Reconcile all app data on given mounted volume. 16933 * <p> 16934 * Destroys app data that isn't expected, either due to uninstallation or 16935 * reinstallation on another volume. 16936 * <p> 16937 * Verifies that directories exist and that ownership and labeling is 16938 * correct for all installed apps. 16939 */ 16940 private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) { 16941 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 16942 + Integer.toHexString(flags)); 16943 16944 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 16945 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 16946 16947 boolean restoreconNeeded = false; 16948 16949 // First look for stale data that doesn't belong, and check if things 16950 // have changed since we did our last restorecon 16951 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 16952 if (!isUserKeyUnlocked(userId)) { 16953 throw new RuntimeException( 16954 "Yikes, someone asked us to reconcile CE storage while " + userId 16955 + " was still locked; this would have caused massive data loss!"); 16956 } 16957 16958 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 16959 16960 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 16961 for (File file : files) { 16962 final String packageName = file.getName(); 16963 try { 16964 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16965 } catch (PackageManagerException e) { 16966 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16967 synchronized (mInstallLock) { 16968 destroyAppDataLI(volumeUuid, packageName, userId, 16969 Installer.FLAG_CE_STORAGE); 16970 } 16971 } 16972 } 16973 } 16974 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 16975 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 16976 16977 final File[] files = FileUtils.listFilesOrEmpty(deDir); 16978 for (File file : files) { 16979 final String packageName = file.getName(); 16980 try { 16981 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 16982 } catch (PackageManagerException e) { 16983 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 16984 synchronized (mInstallLock) { 16985 destroyAppDataLI(volumeUuid, packageName, userId, 16986 Installer.FLAG_DE_STORAGE); 16987 } 16988 } 16989 } 16990 } 16991 16992 // Ensure that data directories are ready to roll for all packages 16993 // installed for this volume and user 16994 final List<PackageSetting> packages; 16995 synchronized (mPackages) { 16996 packages = mSettings.getVolumePackagesLPr(volumeUuid); 16997 } 16998 int preparedCount = 0; 16999 for (PackageSetting ps : packages) { 17000 final String packageName = ps.name; 17001 if (ps.pkg == null) { 17002 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17003 // TODO: might be due to legacy ASEC apps; we should circle back 17004 // and reconcile again once they're scanned 17005 continue; 17006 } 17007 17008 if (ps.getInstalled(userId)) { 17009 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17010 preparedCount++; 17011 } 17012 } 17013 17014 if (restoreconNeeded) { 17015 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17016 SELinuxMMAC.setRestoreconDone(ceDir); 17017 } 17018 if ((flags & Installer.FLAG_DE_STORAGE) != 0) { 17019 SELinuxMMAC.setRestoreconDone(deDir); 17020 } 17021 } 17022 17023 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17024 + " packages; restoreconNeeded was " + restoreconNeeded); 17025 } 17026 17027 /** 17028 * Prepare app data for the given app just after it was installed or 17029 * upgraded. This method carefully only touches users that it's installed 17030 * for, and it forces a restorecon to handle any seinfo changes. 17031 * <p> 17032 * Verifies that directories exist and that ownership and labeling is 17033 * correct for all installed apps. If there is an ownership mismatch, it 17034 * will try recovering system apps by wiping data; third-party app data is 17035 * left intact. 17036 */ 17037 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17038 final PackageSetting ps; 17039 synchronized (mPackages) { 17040 ps = mSettings.mPackages.get(pkg.packageName); 17041 } 17042 17043 final UserManager um = mContext.getSystemService(UserManager.class); 17044 for (UserInfo user : um.getUsers()) { 17045 final int flags; 17046 if (um.isUserUnlocked(user.id)) { 17047 flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE; 17048 } else if (um.isUserRunning(user.id)) { 17049 flags = Installer.FLAG_DE_STORAGE; 17050 } else { 17051 continue; 17052 } 17053 17054 if (ps.getInstalled(user.id)) { 17055 // Whenever an app changes, force a restorecon of its data 17056 // TODO: when user data is locked, mark that we're still dirty 17057 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17058 } 17059 } 17060 } 17061 17062 /** 17063 * Prepare app data for the given app. 17064 * <p> 17065 * Verifies that directories exist and that ownership and labeling is 17066 * correct for all installed apps. If there is an ownership mismatch, this 17067 * will try recovering system apps by wiping data; third-party app data is 17068 * left intact. 17069 */ 17070 private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags, 17071 PackageParser.Package pkg, boolean restoreconNeeded) { 17072 if (DEBUG_APP_DATA) { 17073 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17074 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17075 } 17076 17077 final String packageName = pkg.packageName; 17078 final ApplicationInfo app = pkg.applicationInfo; 17079 final int appId = UserHandle.getAppId(app.uid); 17080 17081 Preconditions.checkNotNull(app.seinfo); 17082 17083 synchronized (mInstallLock) { 17084 try { 17085 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17086 appId, app.seinfo, app.targetSdkVersion); 17087 } catch (InstallerException e) { 17088 if (app.isSystemApp()) { 17089 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17090 + ", but trying to recover: " + e); 17091 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17092 try { 17093 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17094 appId, app.seinfo, app.targetSdkVersion); 17095 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17096 } catch (InstallerException e2) { 17097 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17098 } 17099 } else { 17100 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17101 } 17102 } 17103 17104 if (restoreconNeeded) { 17105 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17106 } 17107 17108 if ((flags & Installer.FLAG_CE_STORAGE) != 0) { 17109 // Create a native library symlink only if we have native libraries 17110 // and if the native libraries are 32 bit libraries. We do not provide 17111 // this symlink for 64 bit libraries. 17112 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17113 final String nativeLibPath = app.nativeLibraryDir; 17114 try { 17115 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17116 nativeLibPath, userId); 17117 } catch (InstallerException e) { 17118 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17119 } 17120 } 17121 } 17122 } 17123 } 17124 17125 private void unfreezePackage(String packageName) { 17126 synchronized (mPackages) { 17127 final PackageSetting ps = mSettings.mPackages.get(packageName); 17128 if (ps != null) { 17129 ps.frozen = false; 17130 } 17131 } 17132 } 17133 17134 @Override 17135 public int movePackage(final String packageName, final String volumeUuid) { 17136 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17137 17138 final int moveId = mNextMoveId.getAndIncrement(); 17139 mHandler.post(new Runnable() { 17140 @Override 17141 public void run() { 17142 try { 17143 movePackageInternal(packageName, volumeUuid, moveId); 17144 } catch (PackageManagerException e) { 17145 Slog.w(TAG, "Failed to move " + packageName, e); 17146 mMoveCallbacks.notifyStatusChanged(moveId, 17147 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17148 } 17149 } 17150 }); 17151 return moveId; 17152 } 17153 17154 private void movePackageInternal(final String packageName, final String volumeUuid, 17155 final int moveId) throws PackageManagerException { 17156 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17157 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17158 final PackageManager pm = mContext.getPackageManager(); 17159 17160 final boolean currentAsec; 17161 final String currentVolumeUuid; 17162 final File codeFile; 17163 final String installerPackageName; 17164 final String packageAbiOverride; 17165 final int appId; 17166 final String seinfo; 17167 final String label; 17168 final int targetSdkVersion; 17169 17170 // reader 17171 synchronized (mPackages) { 17172 final PackageParser.Package pkg = mPackages.get(packageName); 17173 final PackageSetting ps = mSettings.mPackages.get(packageName); 17174 if (pkg == null || ps == null) { 17175 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17176 } 17177 17178 if (pkg.applicationInfo.isSystemApp()) { 17179 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17180 "Cannot move system application"); 17181 } 17182 17183 if (pkg.applicationInfo.isExternalAsec()) { 17184 currentAsec = true; 17185 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17186 } else if (pkg.applicationInfo.isForwardLocked()) { 17187 currentAsec = true; 17188 currentVolumeUuid = "forward_locked"; 17189 } else { 17190 currentAsec = false; 17191 currentVolumeUuid = ps.volumeUuid; 17192 17193 final File probe = new File(pkg.codePath); 17194 final File probeOat = new File(probe, "oat"); 17195 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17197 "Move only supported for modern cluster style installs"); 17198 } 17199 } 17200 17201 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17202 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17203 "Package already moved to " + volumeUuid); 17204 } 17205 17206 if (ps.frozen) { 17207 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17208 "Failed to move already frozen package"); 17209 } 17210 ps.frozen = true; 17211 17212 codeFile = new File(pkg.codePath); 17213 installerPackageName = ps.installerPackageName; 17214 packageAbiOverride = ps.cpuAbiOverrideString; 17215 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17216 seinfo = pkg.applicationInfo.seinfo; 17217 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17218 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17219 } 17220 17221 // Now that we're guarded by frozen state, kill app during move 17222 final long token = Binder.clearCallingIdentity(); 17223 try { 17224 killApplication(packageName, appId, "move pkg"); 17225 } finally { 17226 Binder.restoreCallingIdentity(token); 17227 } 17228 17229 final Bundle extras = new Bundle(); 17230 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17231 extras.putString(Intent.EXTRA_TITLE, label); 17232 mMoveCallbacks.notifyCreated(moveId, extras); 17233 17234 int installFlags; 17235 final boolean moveCompleteApp; 17236 final File measurePath; 17237 17238 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17239 installFlags = INSTALL_INTERNAL; 17240 moveCompleteApp = !currentAsec; 17241 measurePath = Environment.getDataAppDirectory(volumeUuid); 17242 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17243 installFlags = INSTALL_EXTERNAL; 17244 moveCompleteApp = false; 17245 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17246 } else { 17247 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17248 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17249 || !volume.isMountedWritable()) { 17250 unfreezePackage(packageName); 17251 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17252 "Move location not mounted private volume"); 17253 } 17254 17255 Preconditions.checkState(!currentAsec); 17256 17257 installFlags = INSTALL_INTERNAL; 17258 moveCompleteApp = true; 17259 measurePath = Environment.getDataAppDirectory(volumeUuid); 17260 } 17261 17262 final PackageStats stats = new PackageStats(null, -1); 17263 synchronized (mInstaller) { 17264 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17265 unfreezePackage(packageName); 17266 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17267 "Failed to measure package size"); 17268 } 17269 } 17270 17271 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17272 + stats.dataSize); 17273 17274 final long startFreeBytes = measurePath.getFreeSpace(); 17275 final long sizeBytes; 17276 if (moveCompleteApp) { 17277 sizeBytes = stats.codeSize + stats.dataSize; 17278 } else { 17279 sizeBytes = stats.codeSize; 17280 } 17281 17282 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17283 unfreezePackage(packageName); 17284 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17285 "Not enough free space to move"); 17286 } 17287 17288 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17289 17290 final CountDownLatch installedLatch = new CountDownLatch(1); 17291 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17292 @Override 17293 public void onUserActionRequired(Intent intent) throws RemoteException { 17294 throw new IllegalStateException(); 17295 } 17296 17297 @Override 17298 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17299 Bundle extras) throws RemoteException { 17300 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17301 + PackageManager.installStatusToString(returnCode, msg)); 17302 17303 installedLatch.countDown(); 17304 17305 // Regardless of success or failure of the move operation, 17306 // always unfreeze the package 17307 unfreezePackage(packageName); 17308 17309 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17310 switch (status) { 17311 case PackageInstaller.STATUS_SUCCESS: 17312 mMoveCallbacks.notifyStatusChanged(moveId, 17313 PackageManager.MOVE_SUCCEEDED); 17314 break; 17315 case PackageInstaller.STATUS_FAILURE_STORAGE: 17316 mMoveCallbacks.notifyStatusChanged(moveId, 17317 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17318 break; 17319 default: 17320 mMoveCallbacks.notifyStatusChanged(moveId, 17321 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17322 break; 17323 } 17324 } 17325 }; 17326 17327 final MoveInfo move; 17328 if (moveCompleteApp) { 17329 // Kick off a thread to report progress estimates 17330 new Thread() { 17331 @Override 17332 public void run() { 17333 while (true) { 17334 try { 17335 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17336 break; 17337 } 17338 } catch (InterruptedException ignored) { 17339 } 17340 17341 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17342 final int progress = 10 + (int) MathUtils.constrain( 17343 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17344 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17345 } 17346 } 17347 }.start(); 17348 17349 final String dataAppName = codeFile.getName(); 17350 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17351 dataAppName, appId, seinfo, targetSdkVersion); 17352 } else { 17353 move = null; 17354 } 17355 17356 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17357 17358 final Message msg = mHandler.obtainMessage(INIT_COPY); 17359 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17360 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17361 installerPackageName, volumeUuid, null, user, packageAbiOverride, null); 17362 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17363 msg.obj = params; 17364 17365 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17366 System.identityHashCode(msg.obj)); 17367 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17368 System.identityHashCode(msg.obj)); 17369 17370 mHandler.sendMessage(msg); 17371 } 17372 17373 @Override 17374 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17375 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17376 17377 final int realMoveId = mNextMoveId.getAndIncrement(); 17378 final Bundle extras = new Bundle(); 17379 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 17380 mMoveCallbacks.notifyCreated(realMoveId, extras); 17381 17382 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 17383 @Override 17384 public void onCreated(int moveId, Bundle extras) { 17385 // Ignored 17386 } 17387 17388 @Override 17389 public void onStatusChanged(int moveId, int status, long estMillis) { 17390 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 17391 } 17392 }; 17393 17394 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17395 storage.setPrimaryStorageUuid(volumeUuid, callback); 17396 return realMoveId; 17397 } 17398 17399 @Override 17400 public int getMoveStatus(int moveId) { 17401 mContext.enforceCallingOrSelfPermission( 17402 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17403 return mMoveCallbacks.mLastStatus.get(moveId); 17404 } 17405 17406 @Override 17407 public void registerMoveCallback(IPackageMoveObserver callback) { 17408 mContext.enforceCallingOrSelfPermission( 17409 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17410 mMoveCallbacks.register(callback); 17411 } 17412 17413 @Override 17414 public void unregisterMoveCallback(IPackageMoveObserver callback) { 17415 mContext.enforceCallingOrSelfPermission( 17416 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 17417 mMoveCallbacks.unregister(callback); 17418 } 17419 17420 @Override 17421 public boolean setInstallLocation(int loc) { 17422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 17423 null); 17424 if (getInstallLocation() == loc) { 17425 return true; 17426 } 17427 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 17428 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 17429 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 17430 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 17431 return true; 17432 } 17433 return false; 17434 } 17435 17436 @Override 17437 public int getInstallLocation() { 17438 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 17439 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 17440 PackageHelper.APP_INSTALL_AUTO); 17441 } 17442 17443 /** Called by UserManagerService */ 17444 void cleanUpUser(UserManagerService userManager, int userHandle) { 17445 synchronized (mPackages) { 17446 mDirtyUsers.remove(userHandle); 17447 mUserNeedsBadging.delete(userHandle); 17448 mSettings.removeUserLPw(userHandle); 17449 mPendingBroadcasts.remove(userHandle); 17450 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 17451 } 17452 synchronized (mInstallLock) { 17453 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17454 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17455 final String volumeUuid = vol.getFsUuid(); 17456 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 17457 try { 17458 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 17459 } catch (InstallerException e) { 17460 Slog.w(TAG, "Failed to remove user data", e); 17461 } 17462 } 17463 synchronized (mPackages) { 17464 removeUnusedPackagesLILPw(userManager, userHandle); 17465 } 17466 } 17467 } 17468 17469 /** 17470 * We're removing userHandle and would like to remove any downloaded packages 17471 * that are no longer in use by any other user. 17472 * @param userHandle the user being removed 17473 */ 17474 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 17475 final boolean DEBUG_CLEAN_APKS = false; 17476 int [] users = userManager.getUserIds(); 17477 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 17478 while (psit.hasNext()) { 17479 PackageSetting ps = psit.next(); 17480 if (ps.pkg == null) { 17481 continue; 17482 } 17483 final String packageName = ps.pkg.packageName; 17484 // Skip over if system app 17485 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 17486 continue; 17487 } 17488 if (DEBUG_CLEAN_APKS) { 17489 Slog.i(TAG, "Checking package " + packageName); 17490 } 17491 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 17492 if (keep) { 17493 if (DEBUG_CLEAN_APKS) { 17494 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 17495 } 17496 } else { 17497 for (int i = 0; i < users.length; i++) { 17498 if (users[i] != userHandle && ps.getInstalled(users[i])) { 17499 keep = true; 17500 if (DEBUG_CLEAN_APKS) { 17501 Slog.i(TAG, " Keeping package " + packageName + " for user " 17502 + users[i]); 17503 } 17504 break; 17505 } 17506 } 17507 } 17508 if (!keep) { 17509 if (DEBUG_CLEAN_APKS) { 17510 Slog.i(TAG, " Removing package " + packageName); 17511 } 17512 mHandler.post(new Runnable() { 17513 public void run() { 17514 deletePackageX(packageName, userHandle, 0); 17515 } //end run 17516 }); 17517 } 17518 } 17519 } 17520 17521 /** Called by UserManagerService */ 17522 void createNewUser(int userHandle) { 17523 synchronized (mInstallLock) { 17524 try { 17525 mInstaller.createUserConfig(userHandle); 17526 } catch (InstallerException e) { 17527 Slog.w(TAG, "Failed to create user config", e); 17528 } 17529 mSettings.createNewUserLI(this, mInstaller, userHandle); 17530 } 17531 synchronized (mPackages) { 17532 applyFactoryDefaultBrowserLPw(userHandle); 17533 primeDomainVerificationsLPw(userHandle); 17534 } 17535 } 17536 17537 void newUserCreated(final int userHandle) { 17538 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 17539 // If permission review for legacy apps is required, we represent 17540 // dagerous permissions for such apps as always granted runtime 17541 // permissions to keep per user flag state whether review is needed. 17542 // Hence, if a new user is added we have to propagate dangerous 17543 // permission grants for these legacy apps. 17544 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 17545 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 17546 | UPDATE_PERMISSIONS_REPLACE_ALL); 17547 } 17548 } 17549 17550 @Override 17551 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 17552 mContext.enforceCallingOrSelfPermission( 17553 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 17554 "Only package verification agents can read the verifier device identity"); 17555 17556 synchronized (mPackages) { 17557 return mSettings.getVerifierDeviceIdentityLPw(); 17558 } 17559 } 17560 17561 @Override 17562 public void setPermissionEnforced(String permission, boolean enforced) { 17563 // TODO: Now that we no longer change GID for storage, this should to away. 17564 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 17565 "setPermissionEnforced"); 17566 if (READ_EXTERNAL_STORAGE.equals(permission)) { 17567 synchronized (mPackages) { 17568 if (mSettings.mReadExternalStorageEnforced == null 17569 || mSettings.mReadExternalStorageEnforced != enforced) { 17570 mSettings.mReadExternalStorageEnforced = enforced; 17571 mSettings.writeLPr(); 17572 } 17573 } 17574 // kill any non-foreground processes so we restart them and 17575 // grant/revoke the GID. 17576 final IActivityManager am = ActivityManagerNative.getDefault(); 17577 if (am != null) { 17578 final long token = Binder.clearCallingIdentity(); 17579 try { 17580 am.killProcessesBelowForeground("setPermissionEnforcement"); 17581 } catch (RemoteException e) { 17582 } finally { 17583 Binder.restoreCallingIdentity(token); 17584 } 17585 } 17586 } else { 17587 throw new IllegalArgumentException("No selective enforcement for " + permission); 17588 } 17589 } 17590 17591 @Override 17592 @Deprecated 17593 public boolean isPermissionEnforced(String permission) { 17594 return true; 17595 } 17596 17597 @Override 17598 public boolean isStorageLow() { 17599 final long token = Binder.clearCallingIdentity(); 17600 try { 17601 final DeviceStorageMonitorInternal 17602 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 17603 if (dsm != null) { 17604 return dsm.isMemoryLow(); 17605 } else { 17606 return false; 17607 } 17608 } finally { 17609 Binder.restoreCallingIdentity(token); 17610 } 17611 } 17612 17613 @Override 17614 public IPackageInstaller getPackageInstaller() { 17615 return mInstallerService; 17616 } 17617 17618 private boolean userNeedsBadging(int userId) { 17619 int index = mUserNeedsBadging.indexOfKey(userId); 17620 if (index < 0) { 17621 final UserInfo userInfo; 17622 final long token = Binder.clearCallingIdentity(); 17623 try { 17624 userInfo = sUserManager.getUserInfo(userId); 17625 } finally { 17626 Binder.restoreCallingIdentity(token); 17627 } 17628 final boolean b; 17629 if (userInfo != null && userInfo.isManagedProfile()) { 17630 b = true; 17631 } else { 17632 b = false; 17633 } 17634 mUserNeedsBadging.put(userId, b); 17635 return b; 17636 } 17637 return mUserNeedsBadging.valueAt(index); 17638 } 17639 17640 @Override 17641 public KeySet getKeySetByAlias(String packageName, String alias) { 17642 if (packageName == null || alias == null) { 17643 return null; 17644 } 17645 synchronized(mPackages) { 17646 final PackageParser.Package pkg = mPackages.get(packageName); 17647 if (pkg == null) { 17648 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17649 throw new IllegalArgumentException("Unknown package: " + packageName); 17650 } 17651 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17652 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 17653 } 17654 } 17655 17656 @Override 17657 public KeySet getSigningKeySet(String packageName) { 17658 if (packageName == null) { 17659 return null; 17660 } 17661 synchronized(mPackages) { 17662 final PackageParser.Package pkg = mPackages.get(packageName); 17663 if (pkg == null) { 17664 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17665 throw new IllegalArgumentException("Unknown package: " + packageName); 17666 } 17667 if (pkg.applicationInfo.uid != Binder.getCallingUid() 17668 && Process.SYSTEM_UID != Binder.getCallingUid()) { 17669 throw new SecurityException("May not access signing KeySet of other apps."); 17670 } 17671 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17672 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 17673 } 17674 } 17675 17676 @Override 17677 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 17678 if (packageName == null || ks == null) { 17679 return false; 17680 } 17681 synchronized(mPackages) { 17682 final PackageParser.Package pkg = mPackages.get(packageName); 17683 if (pkg == null) { 17684 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17685 throw new IllegalArgumentException("Unknown package: " + packageName); 17686 } 17687 IBinder ksh = ks.getToken(); 17688 if (ksh instanceof KeySetHandle) { 17689 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17690 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 17691 } 17692 return false; 17693 } 17694 } 17695 17696 @Override 17697 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 17698 if (packageName == null || ks == null) { 17699 return false; 17700 } 17701 synchronized(mPackages) { 17702 final PackageParser.Package pkg = mPackages.get(packageName); 17703 if (pkg == null) { 17704 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 17705 throw new IllegalArgumentException("Unknown package: " + packageName); 17706 } 17707 IBinder ksh = ks.getToken(); 17708 if (ksh instanceof KeySetHandle) { 17709 KeySetManagerService ksms = mSettings.mKeySetManagerService; 17710 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 17711 } 17712 return false; 17713 } 17714 } 17715 17716 private void deletePackageIfUnusedLPr(final String packageName) { 17717 PackageSetting ps = mSettings.mPackages.get(packageName); 17718 if (ps == null) { 17719 return; 17720 } 17721 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 17722 // TODO Implement atomic delete if package is unused 17723 // It is currently possible that the package will be deleted even if it is installed 17724 // after this method returns. 17725 mHandler.post(new Runnable() { 17726 public void run() { 17727 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 17728 } 17729 }); 17730 } 17731 } 17732 17733 /** 17734 * Check and throw if the given before/after packages would be considered a 17735 * downgrade. 17736 */ 17737 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 17738 throws PackageManagerException { 17739 if (after.versionCode < before.mVersionCode) { 17740 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17741 "Update version code " + after.versionCode + " is older than current " 17742 + before.mVersionCode); 17743 } else if (after.versionCode == before.mVersionCode) { 17744 if (after.baseRevisionCode < before.baseRevisionCode) { 17745 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17746 "Update base revision code " + after.baseRevisionCode 17747 + " is older than current " + before.baseRevisionCode); 17748 } 17749 17750 if (!ArrayUtils.isEmpty(after.splitNames)) { 17751 for (int i = 0; i < after.splitNames.length; i++) { 17752 final String splitName = after.splitNames[i]; 17753 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 17754 if (j != -1) { 17755 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 17756 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 17757 "Update split " + splitName + " revision code " 17758 + after.splitRevisionCodes[i] + " is older than current " 17759 + before.splitRevisionCodes[j]); 17760 } 17761 } 17762 } 17763 } 17764 } 17765 } 17766 17767 private static class MoveCallbacks extends Handler { 17768 private static final int MSG_CREATED = 1; 17769 private static final int MSG_STATUS_CHANGED = 2; 17770 17771 private final RemoteCallbackList<IPackageMoveObserver> 17772 mCallbacks = new RemoteCallbackList<>(); 17773 17774 private final SparseIntArray mLastStatus = new SparseIntArray(); 17775 17776 public MoveCallbacks(Looper looper) { 17777 super(looper); 17778 } 17779 17780 public void register(IPackageMoveObserver callback) { 17781 mCallbacks.register(callback); 17782 } 17783 17784 public void unregister(IPackageMoveObserver callback) { 17785 mCallbacks.unregister(callback); 17786 } 17787 17788 @Override 17789 public void handleMessage(Message msg) { 17790 final SomeArgs args = (SomeArgs) msg.obj; 17791 final int n = mCallbacks.beginBroadcast(); 17792 for (int i = 0; i < n; i++) { 17793 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 17794 try { 17795 invokeCallback(callback, msg.what, args); 17796 } catch (RemoteException ignored) { 17797 } 17798 } 17799 mCallbacks.finishBroadcast(); 17800 args.recycle(); 17801 } 17802 17803 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 17804 throws RemoteException { 17805 switch (what) { 17806 case MSG_CREATED: { 17807 callback.onCreated(args.argi1, (Bundle) args.arg2); 17808 break; 17809 } 17810 case MSG_STATUS_CHANGED: { 17811 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 17812 break; 17813 } 17814 } 17815 } 17816 17817 private void notifyCreated(int moveId, Bundle extras) { 17818 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 17819 17820 final SomeArgs args = SomeArgs.obtain(); 17821 args.argi1 = moveId; 17822 args.arg2 = extras; 17823 obtainMessage(MSG_CREATED, args).sendToTarget(); 17824 } 17825 17826 private void notifyStatusChanged(int moveId, int status) { 17827 notifyStatusChanged(moveId, status, -1); 17828 } 17829 17830 private void notifyStatusChanged(int moveId, int status, long estMillis) { 17831 Slog.v(TAG, "Move " + moveId + " status " + status); 17832 17833 final SomeArgs args = SomeArgs.obtain(); 17834 args.argi1 = moveId; 17835 args.argi2 = status; 17836 args.arg3 = estMillis; 17837 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 17838 17839 synchronized (mLastStatus) { 17840 mLastStatus.put(moveId, status); 17841 } 17842 } 17843 } 17844 17845 private final static class OnPermissionChangeListeners extends Handler { 17846 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 17847 17848 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 17849 new RemoteCallbackList<>(); 17850 17851 public OnPermissionChangeListeners(Looper looper) { 17852 super(looper); 17853 } 17854 17855 @Override 17856 public void handleMessage(Message msg) { 17857 switch (msg.what) { 17858 case MSG_ON_PERMISSIONS_CHANGED: { 17859 final int uid = msg.arg1; 17860 handleOnPermissionsChanged(uid); 17861 } break; 17862 } 17863 } 17864 17865 public void addListenerLocked(IOnPermissionsChangeListener listener) { 17866 mPermissionListeners.register(listener); 17867 17868 } 17869 17870 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 17871 mPermissionListeners.unregister(listener); 17872 } 17873 17874 public void onPermissionsChanged(int uid) { 17875 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 17876 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 17877 } 17878 } 17879 17880 private void handleOnPermissionsChanged(int uid) { 17881 final int count = mPermissionListeners.beginBroadcast(); 17882 try { 17883 for (int i = 0; i < count; i++) { 17884 IOnPermissionsChangeListener callback = mPermissionListeners 17885 .getBroadcastItem(i); 17886 try { 17887 callback.onPermissionsChanged(uid); 17888 } catch (RemoteException e) { 17889 Log.e(TAG, "Permission listener is dead", e); 17890 } 17891 } 17892 } finally { 17893 mPermissionListeners.finishBroadcast(); 17894 } 17895 } 17896 } 17897 17898 private class PackageManagerInternalImpl extends PackageManagerInternal { 17899 @Override 17900 public void setLocationPackagesProvider(PackagesProvider provider) { 17901 synchronized (mPackages) { 17902 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 17903 } 17904 } 17905 17906 @Override 17907 public void setImePackagesProvider(PackagesProvider provider) { 17908 synchronized (mPackages) { 17909 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 17910 } 17911 } 17912 17913 @Override 17914 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 17915 synchronized (mPackages) { 17916 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 17917 } 17918 } 17919 17920 @Override 17921 public void setSmsAppPackagesProvider(PackagesProvider provider) { 17922 synchronized (mPackages) { 17923 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 17924 } 17925 } 17926 17927 @Override 17928 public void setDialerAppPackagesProvider(PackagesProvider provider) { 17929 synchronized (mPackages) { 17930 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 17931 } 17932 } 17933 17934 @Override 17935 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 17936 synchronized (mPackages) { 17937 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 17938 } 17939 } 17940 17941 @Override 17942 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 17943 synchronized (mPackages) { 17944 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 17945 } 17946 } 17947 17948 @Override 17949 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 17950 synchronized (mPackages) { 17951 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 17952 packageName, userId); 17953 } 17954 } 17955 17956 @Override 17957 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 17958 synchronized (mPackages) { 17959 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 17960 packageName, userId); 17961 } 17962 } 17963 17964 @Override 17965 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 17966 synchronized (mPackages) { 17967 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 17968 packageName, userId); 17969 } 17970 } 17971 17972 @Override 17973 public void setKeepUninstalledPackages(final List<String> packageList) { 17974 Preconditions.checkNotNull(packageList); 17975 List<String> removedFromList = null; 17976 synchronized (mPackages) { 17977 if (mKeepUninstalledPackages != null) { 17978 final int packagesCount = mKeepUninstalledPackages.size(); 17979 for (int i = 0; i < packagesCount; i++) { 17980 String oldPackage = mKeepUninstalledPackages.get(i); 17981 if (packageList != null && packageList.contains(oldPackage)) { 17982 continue; 17983 } 17984 if (removedFromList == null) { 17985 removedFromList = new ArrayList<>(); 17986 } 17987 removedFromList.add(oldPackage); 17988 } 17989 } 17990 mKeepUninstalledPackages = new ArrayList<>(packageList); 17991 if (removedFromList != null) { 17992 final int removedCount = removedFromList.size(); 17993 for (int i = 0; i < removedCount; i++) { 17994 deletePackageIfUnusedLPr(removedFromList.get(i)); 17995 } 17996 } 17997 } 17998 } 17999 18000 @Override 18001 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18002 synchronized (mPackages) { 18003 // If we do not support permission review, done. 18004 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18005 return false; 18006 } 18007 18008 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18009 if (packageSetting == null) { 18010 return false; 18011 } 18012 18013 // Permission review applies only to apps not supporting the new permission model. 18014 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18015 return false; 18016 } 18017 18018 // Legacy apps have the permission and get user consent on launch. 18019 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18020 return permissionsState.isPermissionReviewRequired(userId); 18021 } 18022 } 18023 } 18024 18025 @Override 18026 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18027 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18028 synchronized (mPackages) { 18029 final long identity = Binder.clearCallingIdentity(); 18030 try { 18031 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18032 packageNames, userId); 18033 } finally { 18034 Binder.restoreCallingIdentity(identity); 18035 } 18036 } 18037 } 18038 18039 private static void enforceSystemOrPhoneCaller(String tag) { 18040 int callingUid = Binder.getCallingUid(); 18041 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18042 throw new SecurityException( 18043 "Cannot call " + tag + " from UID " + callingUid); 18044 } 18045 } 18046} 18047