PackageManagerService.java revision 9706c01f9b92cee64bb84782138735225c8588e0
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.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 65import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 67import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 68import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 69import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 70import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 71import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 72import static android.content.pm.PackageManager.PERMISSION_DENIED; 73import static android.content.pm.PackageManager.PERMISSION_GRANTED; 74import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 75import static android.content.pm.PackageParser.isApkFile; 76import static android.os.Process.PACKAGE_INFO_GID; 77import static android.os.Process.SYSTEM_UID; 78import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 79import static android.system.OsConstants.O_CREAT; 80import static android.system.OsConstants.O_RDWR; 81 82import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 84import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 85import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 86import static com.android.internal.util.ArrayUtils.appendInt; 87import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 88import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 89import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 91import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 92import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 94import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 96 97import android.Manifest; 98import android.annotation.NonNull; 99import android.annotation.Nullable; 100import android.app.ActivityManager; 101import android.app.ActivityManagerNative; 102import android.app.AppGlobals; 103import android.app.IActivityManager; 104import android.app.admin.IDevicePolicyManager; 105import android.app.backup.IBackupManager; 106import android.content.BroadcastReceiver; 107import android.content.ComponentName; 108import android.content.Context; 109import android.content.IIntentReceiver; 110import android.content.Intent; 111import android.content.IntentFilter; 112import android.content.IntentSender; 113import android.content.IntentSender.SendIntentException; 114import android.content.ServiceConnection; 115import android.content.pm.ActivityInfo; 116import android.content.pm.ApplicationInfo; 117import android.content.pm.AppsQueryHelper; 118import android.content.pm.ComponentInfo; 119import android.content.pm.EphemeralApplicationInfo; 120import android.content.pm.EphemeralResolveInfo; 121import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 122import android.content.pm.FeatureInfo; 123import android.content.pm.IOnPermissionsChangeListener; 124import android.content.pm.IPackageDataObserver; 125import android.content.pm.IPackageDeleteObserver; 126import android.content.pm.IPackageDeleteObserver2; 127import android.content.pm.IPackageInstallObserver2; 128import android.content.pm.IPackageInstaller; 129import android.content.pm.IPackageManager; 130import android.content.pm.IPackageMoveObserver; 131import android.content.pm.IPackageStatsObserver; 132import android.content.pm.InstrumentationInfo; 133import android.content.pm.IntentFilterVerificationInfo; 134import android.content.pm.KeySet; 135import android.content.pm.PackageCleanItem; 136import android.content.pm.PackageInfo; 137import android.content.pm.PackageInfoLite; 138import android.content.pm.PackageInstaller; 139import android.content.pm.PackageManager; 140import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 141import android.content.pm.PackageManagerInternal; 142import android.content.pm.PackageParser; 143import android.content.pm.PackageParser.ActivityIntentInfo; 144import android.content.pm.PackageParser.Package; 145import android.content.pm.PackageParser.PackageLite; 146import android.content.pm.PackageParser.PackageParserException; 147import android.content.pm.PackageStats; 148import android.content.pm.PackageUserState; 149import android.content.pm.ParceledListSlice; 150import android.content.pm.PermissionGroupInfo; 151import android.content.pm.PermissionInfo; 152import android.content.pm.ProviderInfo; 153import android.content.pm.ResolveInfo; 154import android.content.pm.ServiceInfo; 155import android.content.pm.Signature; 156import android.content.pm.UserInfo; 157import android.content.pm.VerifierDeviceIdentity; 158import android.content.pm.VerifierInfo; 159import android.content.res.Resources; 160import android.graphics.Bitmap; 161import android.hardware.display.DisplayManager; 162import android.net.Uri; 163import android.os.Binder; 164import android.os.Build; 165import android.os.Bundle; 166import android.os.Debug; 167import android.os.Environment; 168import android.os.Environment.UserEnvironment; 169import android.os.FileUtils; 170import android.os.Handler; 171import android.os.IBinder; 172import android.os.Looper; 173import android.os.Message; 174import android.os.Parcel; 175import android.os.ParcelFileDescriptor; 176import android.os.Parcelable; 177import android.os.Process; 178import android.os.RemoteCallbackList; 179import android.os.RemoteException; 180import android.os.ResultReceiver; 181import android.os.SELinux; 182import android.os.ServiceManager; 183import android.os.SystemClock; 184import android.os.SystemProperties; 185import android.os.Trace; 186import android.os.UserHandle; 187import android.os.UserManager; 188import android.os.storage.IMountService; 189import android.os.storage.MountServiceInternal; 190import android.os.storage.StorageEventListener; 191import android.os.storage.StorageManager; 192import android.os.storage.VolumeInfo; 193import android.os.storage.VolumeRecord; 194import android.security.KeyStore; 195import android.security.SystemKeyStore; 196import android.system.ErrnoException; 197import android.system.Os; 198import android.text.TextUtils; 199import android.text.format.DateUtils; 200import android.util.ArrayMap; 201import android.util.ArraySet; 202import android.util.AtomicFile; 203import android.util.DisplayMetrics; 204import android.util.EventLog; 205import android.util.ExceptionUtils; 206import android.util.Log; 207import android.util.LogPrinter; 208import android.util.MathUtils; 209import android.util.PrintStreamPrinter; 210import android.util.Slog; 211import android.util.SparseArray; 212import android.util.SparseBooleanArray; 213import android.util.SparseIntArray; 214import android.util.Xml; 215import android.view.Display; 216 217import com.android.internal.R; 218import com.android.internal.annotations.GuardedBy; 219import com.android.internal.app.IMediaContainerService; 220import com.android.internal.app.ResolverActivity; 221import com.android.internal.content.NativeLibraryHelper; 222import com.android.internal.content.PackageHelper; 223import com.android.internal.os.IParcelFileDescriptorFactory; 224import com.android.internal.os.InstallerConnection.InstallerException; 225import com.android.internal.os.SomeArgs; 226import com.android.internal.os.Zygote; 227import com.android.internal.util.ArrayUtils; 228import com.android.internal.util.FastPrintWriter; 229import com.android.internal.util.FastXmlSerializer; 230import com.android.internal.util.IndentingPrintWriter; 231import com.android.internal.util.Preconditions; 232import com.android.internal.util.XmlUtils; 233import com.android.server.EventLogTags; 234import com.android.server.FgThread; 235import com.android.server.IntentResolver; 236import com.android.server.LocalServices; 237import com.android.server.ServiceThread; 238import com.android.server.SystemConfig; 239import com.android.server.Watchdog; 240import com.android.server.pm.PermissionsState.PermissionState; 241import com.android.server.pm.Settings.DatabaseVersion; 242import com.android.server.pm.Settings.VersionInfo; 243import com.android.server.storage.DeviceStorageMonitorInternal; 244 245import dalvik.system.DexFile; 246import dalvik.system.VMRuntime; 247 248import libcore.io.IoUtils; 249import libcore.util.EmptyArray; 250 251import org.xmlpull.v1.XmlPullParser; 252import org.xmlpull.v1.XmlPullParserException; 253import org.xmlpull.v1.XmlSerializer; 254 255import java.io.BufferedInputStream; 256import java.io.BufferedOutputStream; 257import java.io.BufferedReader; 258import java.io.ByteArrayInputStream; 259import java.io.ByteArrayOutputStream; 260import java.io.File; 261import java.io.FileDescriptor; 262import java.io.FileNotFoundException; 263import java.io.FileOutputStream; 264import java.io.FileReader; 265import java.io.FilenameFilter; 266import java.io.IOException; 267import java.io.InputStream; 268import java.io.PrintStream; 269import java.io.PrintWriter; 270import java.nio.charset.StandardCharsets; 271import java.security.MessageDigest; 272import java.security.NoSuchAlgorithmException; 273import java.security.PublicKey; 274import java.security.cert.CertificateEncodingException; 275import java.security.cert.CertificateException; 276import java.text.SimpleDateFormat; 277import java.util.ArrayList; 278import java.util.Arrays; 279import java.util.Collection; 280import java.util.Collections; 281import java.util.Comparator; 282import java.util.Date; 283import java.util.HashSet; 284import java.util.Iterator; 285import java.util.List; 286import java.util.Map; 287import java.util.Objects; 288import java.util.Set; 289import java.util.concurrent.CountDownLatch; 290import java.util.concurrent.TimeUnit; 291import java.util.concurrent.atomic.AtomicBoolean; 292import java.util.concurrent.atomic.AtomicInteger; 293import java.util.concurrent.atomic.AtomicLong; 294 295/** 296 * Keep track of all those .apks everywhere. 297 * 298 * This is very central to the platform's security; please run the unit 299 * tests whenever making modifications here: 300 * 301runtest -c android.content.pm.PackageManagerTests frameworks-core 302 * 303 * {@hide} 304 */ 305public class PackageManagerService extends IPackageManager.Stub { 306 static final String TAG = "PackageManager"; 307 static final boolean DEBUG_SETTINGS = false; 308 static final boolean DEBUG_PREFERRED = false; 309 static final boolean DEBUG_UPGRADE = false; 310 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 311 private static final boolean DEBUG_BACKUP = false; 312 private static final boolean DEBUG_INSTALL = false; 313 private static final boolean DEBUG_REMOVE = false; 314 private static final boolean DEBUG_BROADCASTS = false; 315 private static final boolean DEBUG_SHOW_INFO = false; 316 private static final boolean DEBUG_PACKAGE_INFO = false; 317 private static final boolean DEBUG_INTENT_MATCHING = false; 318 private static final boolean DEBUG_PACKAGE_SCANNING = false; 319 private static final boolean DEBUG_VERIFY = false; 320 321 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 322 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 323 // user, but by default initialize to this. 324 static final boolean DEBUG_DEXOPT = false; 325 326 private static final boolean DEBUG_ABI_SELECTION = false; 327 private static final boolean DEBUG_EPHEMERAL = false; 328 private static final boolean DEBUG_TRIAGED_MISSING = false; 329 private static final boolean DEBUG_APP_DATA = false; 330 331 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 332 333 private static final boolean DISABLE_EPHEMERAL_APPS = true; 334 335 private static final int RADIO_UID = Process.PHONE_UID; 336 private static final int LOG_UID = Process.LOG_UID; 337 private static final int NFC_UID = Process.NFC_UID; 338 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 339 private static final int SHELL_UID = Process.SHELL_UID; 340 341 // Cap the size of permission trees that 3rd party apps can define 342 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 343 344 // Suffix used during package installation when copying/moving 345 // package apks to install directory. 346 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 347 348 static final int SCAN_NO_DEX = 1<<1; 349 static final int SCAN_FORCE_DEX = 1<<2; 350 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 351 static final int SCAN_NEW_INSTALL = 1<<4; 352 static final int SCAN_NO_PATHS = 1<<5; 353 static final int SCAN_UPDATE_TIME = 1<<6; 354 static final int SCAN_DEFER_DEX = 1<<7; 355 static final int SCAN_BOOTING = 1<<8; 356 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 357 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 358 static final int SCAN_REPLACING = 1<<11; 359 static final int SCAN_REQUIRE_KNOWN = 1<<12; 360 static final int SCAN_MOVE = 1<<13; 361 static final int SCAN_INITIAL = 1<<14; 362 static final int SCAN_CHECK_ONLY = 1<<15; 363 364 static final int REMOVE_CHATTY = 1<<16; 365 366 private static final int[] EMPTY_INT_ARRAY = new int[0]; 367 368 /** 369 * Timeout (in milliseconds) after which the watchdog should declare that 370 * our handler thread is wedged. The usual default for such things is one 371 * minute but we sometimes do very lengthy I/O operations on this thread, 372 * such as installing multi-gigabyte applications, so ours needs to be longer. 373 */ 374 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 375 376 /** 377 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 378 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 379 * settings entry if available, otherwise we use the hardcoded default. If it's been 380 * more than this long since the last fstrim, we force one during the boot sequence. 381 * 382 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 383 * one gets run at the next available charging+idle time. This final mandatory 384 * no-fstrim check kicks in only of the other scheduling criteria is never met. 385 */ 386 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 387 388 /** 389 * Whether verification is enabled by default. 390 */ 391 private static final boolean DEFAULT_VERIFY_ENABLE = true; 392 393 /** 394 * The default maximum time to wait for the verification agent to return in 395 * milliseconds. 396 */ 397 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 398 399 /** 400 * The default response for package verification timeout. 401 * 402 * This can be either PackageManager.VERIFICATION_ALLOW or 403 * PackageManager.VERIFICATION_REJECT. 404 */ 405 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 406 407 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 408 409 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 410 DEFAULT_CONTAINER_PACKAGE, 411 "com.android.defcontainer.DefaultContainerService"); 412 413 private static final String KILL_APP_REASON_GIDS_CHANGED = 414 "permission grant or revoke changed gids"; 415 416 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 417 "permissions revoked"; 418 419 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 420 421 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 422 423 /** Permission grant: not grant the permission. */ 424 private static final int GRANT_DENIED = 1; 425 426 /** Permission grant: grant the permission as an install permission. */ 427 private static final int GRANT_INSTALL = 2; 428 429 /** Permission grant: grant the permission as a runtime one. */ 430 private static final int GRANT_RUNTIME = 3; 431 432 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 433 private static final int GRANT_UPGRADE = 4; 434 435 /** Canonical intent used to identify what counts as a "web browser" app */ 436 private static final Intent sBrowserIntent; 437 static { 438 sBrowserIntent = new Intent(); 439 sBrowserIntent.setAction(Intent.ACTION_VIEW); 440 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 441 sBrowserIntent.setData(Uri.parse("http:")); 442 } 443 444 final ServiceThread mHandlerThread; 445 446 final PackageHandler mHandler; 447 448 /** 449 * Messages for {@link #mHandler} that need to wait for system ready before 450 * being dispatched. 451 */ 452 private ArrayList<Message> mPostSystemReadyMessages; 453 454 final int mSdkVersion = Build.VERSION.SDK_INT; 455 456 final Context mContext; 457 final boolean mFactoryTest; 458 final boolean mOnlyCore; 459 final DisplayMetrics mMetrics; 460 final int mDefParseFlags; 461 final String[] mSeparateProcesses; 462 final boolean mIsUpgrade; 463 464 /** The location for ASEC container files on internal storage. */ 465 final String mAsecInternalPath; 466 467 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 468 // LOCK HELD. Can be called with mInstallLock held. 469 @GuardedBy("mInstallLock") 470 final Installer mInstaller; 471 472 /** Directory where installed third-party apps stored */ 473 final File mAppInstallDir; 474 final File mEphemeralInstallDir; 475 476 /** 477 * Directory to which applications installed internally have their 478 * 32 bit native libraries copied. 479 */ 480 private File mAppLib32InstallDir; 481 482 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 483 // apps. 484 final File mDrmAppPrivateInstallDir; 485 486 // ---------------------------------------------------------------- 487 488 // Lock for state used when installing and doing other long running 489 // operations. Methods that must be called with this lock held have 490 // the suffix "LI". 491 final Object mInstallLock = new Object(); 492 493 // ---------------------------------------------------------------- 494 495 // Keys are String (package name), values are Package. This also serves 496 // as the lock for the global state. Methods that must be called with 497 // this lock held have the prefix "LP". 498 @GuardedBy("mPackages") 499 final ArrayMap<String, PackageParser.Package> mPackages = 500 new ArrayMap<String, PackageParser.Package>(); 501 502 // Tracks available target package names -> overlay package paths. 503 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 504 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 505 506 /** 507 * Tracks new system packages [received in an OTA] that we expect to 508 * find updated user-installed versions. Keys are package name, values 509 * are package location. 510 */ 511 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 512 513 /** 514 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 515 */ 516 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 517 /** 518 * Whether or not system app permissions should be promoted from install to runtime. 519 */ 520 boolean mPromoteSystemApps; 521 522 final Settings mSettings; 523 boolean mRestoredSettings; 524 525 // System configuration read by SystemConfig. 526 final int[] mGlobalGids; 527 final SparseArray<ArraySet<String>> mSystemPermissions; 528 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 529 530 // If mac_permissions.xml was found for seinfo labeling. 531 boolean mFoundPolicyFile; 532 533 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 534 535 public static final class SharedLibraryEntry { 536 public final String path; 537 public final String apk; 538 539 SharedLibraryEntry(String _path, String _apk) { 540 path = _path; 541 apk = _apk; 542 } 543 } 544 545 // Currently known shared libraries. 546 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 547 new ArrayMap<String, SharedLibraryEntry>(); 548 549 // All available activities, for your resolving pleasure. 550 final ActivityIntentResolver mActivities = 551 new ActivityIntentResolver(); 552 553 // All available receivers, for your resolving pleasure. 554 final ActivityIntentResolver mReceivers = 555 new ActivityIntentResolver(); 556 557 // All available services, for your resolving pleasure. 558 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 559 560 // All available providers, for your resolving pleasure. 561 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 562 563 // Mapping from provider base names (first directory in content URI codePath) 564 // to the provider information. 565 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 566 new ArrayMap<String, PackageParser.Provider>(); 567 568 // Mapping from instrumentation class names to info about them. 569 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 570 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 571 572 // Mapping from permission names to info about them. 573 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 574 new ArrayMap<String, PackageParser.PermissionGroup>(); 575 576 // Packages whose data we have transfered into another package, thus 577 // should no longer exist. 578 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 579 580 // Broadcast actions that are only available to the system. 581 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 582 583 /** List of packages waiting for verification. */ 584 final SparseArray<PackageVerificationState> mPendingVerification 585 = new SparseArray<PackageVerificationState>(); 586 587 /** Set of packages associated with each app op permission. */ 588 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 589 590 final PackageInstallerService mInstallerService; 591 592 private final PackageDexOptimizer mPackageDexOptimizer; 593 594 private AtomicInteger mNextMoveId = new AtomicInteger(); 595 private final MoveCallbacks mMoveCallbacks; 596 597 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 598 599 // Cache of users who need badging. 600 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 601 602 /** Token for keys in mPendingVerification. */ 603 private int mPendingVerificationToken = 0; 604 605 volatile boolean mSystemReady; 606 volatile boolean mSafeMode; 607 volatile boolean mHasSystemUidErrors; 608 609 ApplicationInfo mAndroidApplication; 610 final ActivityInfo mResolveActivity = new ActivityInfo(); 611 final ResolveInfo mResolveInfo = new ResolveInfo(); 612 ComponentName mResolveComponentName; 613 PackageParser.Package mPlatformPackage; 614 ComponentName mCustomResolverComponentName; 615 616 boolean mResolverReplaced = false; 617 618 private final @Nullable ComponentName mIntentFilterVerifierComponent; 619 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 620 621 private int mIntentFilterVerificationToken = 0; 622 623 /** Component that knows whether or not an ephemeral application exists */ 624 final ComponentName mEphemeralResolverComponent; 625 /** The service connection to the ephemeral resolver */ 626 final EphemeralResolverConnection mEphemeralResolverConnection; 627 628 /** Component used to install ephemeral applications */ 629 final ComponentName mEphemeralInstallerComponent; 630 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 631 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 632 633 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 634 = new SparseArray<IntentFilterVerificationState>(); 635 636 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 637 new DefaultPermissionGrantPolicy(this); 638 639 // List of packages names to keep cached, even if they are uninstalled for all users 640 private List<String> mKeepUninstalledPackages; 641 642 private boolean mUseJitProfiles = 643 SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false); 644 645 private static class IFVerificationParams { 646 PackageParser.Package pkg; 647 boolean replacing; 648 int userId; 649 int verifierUid; 650 651 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 652 int _userId, int _verifierUid) { 653 pkg = _pkg; 654 replacing = _replacing; 655 userId = _userId; 656 replacing = _replacing; 657 verifierUid = _verifierUid; 658 } 659 } 660 661 private interface IntentFilterVerifier<T extends IntentFilter> { 662 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 663 T filter, String packageName); 664 void startVerifications(int userId); 665 void receiveVerificationResponse(int verificationId); 666 } 667 668 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 669 private Context mContext; 670 private ComponentName mIntentFilterVerifierComponent; 671 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 672 673 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 674 mContext = context; 675 mIntentFilterVerifierComponent = verifierComponent; 676 } 677 678 private String getDefaultScheme() { 679 return IntentFilter.SCHEME_HTTPS; 680 } 681 682 @Override 683 public void startVerifications(int userId) { 684 // Launch verifications requests 685 int count = mCurrentIntentFilterVerifications.size(); 686 for (int n=0; n<count; n++) { 687 int verificationId = mCurrentIntentFilterVerifications.get(n); 688 final IntentFilterVerificationState ivs = 689 mIntentFilterVerificationStates.get(verificationId); 690 691 String packageName = ivs.getPackageName(); 692 693 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 694 final int filterCount = filters.size(); 695 ArraySet<String> domainsSet = new ArraySet<>(); 696 for (int m=0; m<filterCount; m++) { 697 PackageParser.ActivityIntentInfo filter = filters.get(m); 698 domainsSet.addAll(filter.getHostsList()); 699 } 700 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 701 synchronized (mPackages) { 702 if (mSettings.createIntentFilterVerificationIfNeededLPw( 703 packageName, domainsList) != null) { 704 scheduleWriteSettingsLocked(); 705 } 706 } 707 sendVerificationRequest(userId, verificationId, ivs); 708 } 709 mCurrentIntentFilterVerifications.clear(); 710 } 711 712 private void sendVerificationRequest(int userId, int verificationId, 713 IntentFilterVerificationState ivs) { 714 715 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 716 verificationIntent.putExtra( 717 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 718 verificationId); 719 verificationIntent.putExtra( 720 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 721 getDefaultScheme()); 722 verificationIntent.putExtra( 723 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 724 ivs.getHostsString()); 725 verificationIntent.putExtra( 726 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 727 ivs.getPackageName()); 728 verificationIntent.setComponent(mIntentFilterVerifierComponent); 729 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 730 731 UserHandle user = new UserHandle(userId); 732 mContext.sendBroadcastAsUser(verificationIntent, user); 733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 734 "Sending IntentFilter verification broadcast"); 735 } 736 737 public void receiveVerificationResponse(int verificationId) { 738 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 739 740 final boolean verified = ivs.isVerified(); 741 742 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 743 final int count = filters.size(); 744 if (DEBUG_DOMAIN_VERIFICATION) { 745 Slog.i(TAG, "Received verification response " + verificationId 746 + " for " + count + " filters, verified=" + verified); 747 } 748 for (int n=0; n<count; n++) { 749 PackageParser.ActivityIntentInfo filter = filters.get(n); 750 filter.setVerified(verified); 751 752 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 753 + " verified with result:" + verified + " and hosts:" 754 + ivs.getHostsString()); 755 } 756 757 mIntentFilterVerificationStates.remove(verificationId); 758 759 final String packageName = ivs.getPackageName(); 760 IntentFilterVerificationInfo ivi = null; 761 762 synchronized (mPackages) { 763 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 764 } 765 if (ivi == null) { 766 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 767 + verificationId + " packageName:" + packageName); 768 return; 769 } 770 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 771 "Updating IntentFilterVerificationInfo for package " + packageName 772 +" verificationId:" + verificationId); 773 774 synchronized (mPackages) { 775 if (verified) { 776 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 777 } else { 778 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 779 } 780 scheduleWriteSettingsLocked(); 781 782 final int userId = ivs.getUserId(); 783 if (userId != UserHandle.USER_ALL) { 784 final int userStatus = 785 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 786 787 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 788 boolean needUpdate = false; 789 790 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 791 // already been set by the User thru the Disambiguation dialog 792 switch (userStatus) { 793 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 794 if (verified) { 795 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 796 } else { 797 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 798 } 799 needUpdate = true; 800 break; 801 802 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 803 if (verified) { 804 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 805 needUpdate = true; 806 } 807 break; 808 809 default: 810 // Nothing to do 811 } 812 813 if (needUpdate) { 814 mSettings.updateIntentFilterVerificationStatusLPw( 815 packageName, updatedStatus, userId); 816 scheduleWritePackageRestrictionsLocked(userId); 817 } 818 } 819 } 820 } 821 822 @Override 823 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 824 ActivityIntentInfo filter, String packageName) { 825 if (!hasValidDomains(filter)) { 826 return false; 827 } 828 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 829 if (ivs == null) { 830 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 831 packageName); 832 } 833 if (DEBUG_DOMAIN_VERIFICATION) { 834 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 835 } 836 ivs.addFilter(filter); 837 return true; 838 } 839 840 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 841 int userId, int verificationId, String packageName) { 842 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 843 verifierUid, userId, packageName); 844 ivs.setPendingState(); 845 synchronized (mPackages) { 846 mIntentFilterVerificationStates.append(verificationId, ivs); 847 mCurrentIntentFilterVerifications.add(verificationId); 848 } 849 return ivs; 850 } 851 } 852 853 private static boolean hasValidDomains(ActivityIntentInfo filter) { 854 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 855 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 856 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 857 } 858 859 // Set of pending broadcasts for aggregating enable/disable of components. 860 static class PendingPackageBroadcasts { 861 // for each user id, a map of <package name -> components within that package> 862 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 863 864 public PendingPackageBroadcasts() { 865 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 866 } 867 868 public ArrayList<String> get(int userId, String packageName) { 869 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 870 return packages.get(packageName); 871 } 872 873 public void put(int userId, String packageName, ArrayList<String> components) { 874 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 875 packages.put(packageName, components); 876 } 877 878 public void remove(int userId, String packageName) { 879 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 880 if (packages != null) { 881 packages.remove(packageName); 882 } 883 } 884 885 public void remove(int userId) { 886 mUidMap.remove(userId); 887 } 888 889 public int userIdCount() { 890 return mUidMap.size(); 891 } 892 893 public int userIdAt(int n) { 894 return mUidMap.keyAt(n); 895 } 896 897 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 898 return mUidMap.get(userId); 899 } 900 901 public int size() { 902 // total number of pending broadcast entries across all userIds 903 int num = 0; 904 for (int i = 0; i< mUidMap.size(); i++) { 905 num += mUidMap.valueAt(i).size(); 906 } 907 return num; 908 } 909 910 public void clear() { 911 mUidMap.clear(); 912 } 913 914 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 915 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 916 if (map == null) { 917 map = new ArrayMap<String, ArrayList<String>>(); 918 mUidMap.put(userId, map); 919 } 920 return map; 921 } 922 } 923 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 924 925 // Service Connection to remote media container service to copy 926 // package uri's from external media onto secure containers 927 // or internal storage. 928 private IMediaContainerService mContainerService = null; 929 930 static final int SEND_PENDING_BROADCAST = 1; 931 static final int MCS_BOUND = 3; 932 static final int END_COPY = 4; 933 static final int INIT_COPY = 5; 934 static final int MCS_UNBIND = 6; 935 static final int START_CLEANING_PACKAGE = 7; 936 static final int FIND_INSTALL_LOC = 8; 937 static final int POST_INSTALL = 9; 938 static final int MCS_RECONNECT = 10; 939 static final int MCS_GIVE_UP = 11; 940 static final int UPDATED_MEDIA_STATUS = 12; 941 static final int WRITE_SETTINGS = 13; 942 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 943 static final int PACKAGE_VERIFIED = 15; 944 static final int CHECK_PENDING_VERIFICATION = 16; 945 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 946 static final int INTENT_FILTER_VERIFIED = 18; 947 948 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 949 950 // Delay time in millisecs 951 static final int BROADCAST_DELAY = 10 * 1000; 952 953 static UserManagerService sUserManager; 954 955 // Stores a list of users whose package restrictions file needs to be updated 956 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 957 958 final private DefaultContainerConnection mDefContainerConn = 959 new DefaultContainerConnection(); 960 class DefaultContainerConnection implements ServiceConnection { 961 public void onServiceConnected(ComponentName name, IBinder service) { 962 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 963 IMediaContainerService imcs = 964 IMediaContainerService.Stub.asInterface(service); 965 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 966 } 967 968 public void onServiceDisconnected(ComponentName name) { 969 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 970 } 971 } 972 973 // Recordkeeping of restore-after-install operations that are currently in flight 974 // between the Package Manager and the Backup Manager 975 static class PostInstallData { 976 public InstallArgs args; 977 public PackageInstalledInfo res; 978 979 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 980 args = _a; 981 res = _r; 982 } 983 } 984 985 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 986 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 987 988 // XML tags for backup/restore of various bits of state 989 private static final String TAG_PREFERRED_BACKUP = "pa"; 990 private static final String TAG_DEFAULT_APPS = "da"; 991 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 992 993 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 994 private static final String TAG_ALL_GRANTS = "rt-grants"; 995 private static final String TAG_GRANT = "grant"; 996 private static final String ATTR_PACKAGE_NAME = "pkg"; 997 998 private static final String TAG_PERMISSION = "perm"; 999 private static final String ATTR_PERMISSION_NAME = "name"; 1000 private static final String ATTR_IS_GRANTED = "g"; 1001 private static final String ATTR_USER_SET = "set"; 1002 private static final String ATTR_USER_FIXED = "fixed"; 1003 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1004 1005 // System/policy permission grants are not backed up 1006 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1007 FLAG_PERMISSION_POLICY_FIXED 1008 | FLAG_PERMISSION_SYSTEM_FIXED 1009 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1010 1011 // And we back up these user-adjusted states 1012 private static final int USER_RUNTIME_GRANT_MASK = 1013 FLAG_PERMISSION_USER_SET 1014 | FLAG_PERMISSION_USER_FIXED 1015 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1016 1017 final @Nullable String mRequiredVerifierPackage; 1018 final @Nullable String mRequiredInstallerPackage; 1019 1020 private final PackageUsage mPackageUsage = new PackageUsage(); 1021 1022 private class PackageUsage { 1023 private static final int WRITE_INTERVAL 1024 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1025 1026 private final Object mFileLock = new Object(); 1027 private final AtomicLong mLastWritten = new AtomicLong(0); 1028 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1029 1030 private boolean mIsHistoricalPackageUsageAvailable = true; 1031 1032 boolean isHistoricalPackageUsageAvailable() { 1033 return mIsHistoricalPackageUsageAvailable; 1034 } 1035 1036 void write(boolean force) { 1037 if (force) { 1038 writeInternal(); 1039 return; 1040 } 1041 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1042 && !DEBUG_DEXOPT) { 1043 return; 1044 } 1045 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1046 new Thread("PackageUsage_DiskWriter") { 1047 @Override 1048 public void run() { 1049 try { 1050 writeInternal(); 1051 } finally { 1052 mBackgroundWriteRunning.set(false); 1053 } 1054 } 1055 }.start(); 1056 } 1057 } 1058 1059 private void writeInternal() { 1060 synchronized (mPackages) { 1061 synchronized (mFileLock) { 1062 AtomicFile file = getFile(); 1063 FileOutputStream f = null; 1064 try { 1065 f = file.startWrite(); 1066 BufferedOutputStream out = new BufferedOutputStream(f); 1067 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1068 StringBuilder sb = new StringBuilder(); 1069 for (PackageParser.Package pkg : mPackages.values()) { 1070 if (pkg.mLastPackageUsageTimeInMills == 0) { 1071 continue; 1072 } 1073 sb.setLength(0); 1074 sb.append(pkg.packageName); 1075 sb.append(' '); 1076 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1077 sb.append('\n'); 1078 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1079 } 1080 out.flush(); 1081 file.finishWrite(f); 1082 } catch (IOException e) { 1083 if (f != null) { 1084 file.failWrite(f); 1085 } 1086 Log.e(TAG, "Failed to write package usage times", e); 1087 } 1088 } 1089 } 1090 mLastWritten.set(SystemClock.elapsedRealtime()); 1091 } 1092 1093 void readLP() { 1094 synchronized (mFileLock) { 1095 AtomicFile file = getFile(); 1096 BufferedInputStream in = null; 1097 try { 1098 in = new BufferedInputStream(file.openRead()); 1099 StringBuffer sb = new StringBuffer(); 1100 while (true) { 1101 String packageName = readToken(in, sb, ' '); 1102 if (packageName == null) { 1103 break; 1104 } 1105 String timeInMillisString = readToken(in, sb, '\n'); 1106 if (timeInMillisString == null) { 1107 throw new IOException("Failed to find last usage time for package " 1108 + packageName); 1109 } 1110 PackageParser.Package pkg = mPackages.get(packageName); 1111 if (pkg == null) { 1112 continue; 1113 } 1114 long timeInMillis; 1115 try { 1116 timeInMillis = Long.parseLong(timeInMillisString); 1117 } catch (NumberFormatException e) { 1118 throw new IOException("Failed to parse " + timeInMillisString 1119 + " as a long.", e); 1120 } 1121 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1122 } 1123 } catch (FileNotFoundException expected) { 1124 mIsHistoricalPackageUsageAvailable = false; 1125 } catch (IOException e) { 1126 Log.w(TAG, "Failed to read package usage times", e); 1127 } finally { 1128 IoUtils.closeQuietly(in); 1129 } 1130 } 1131 mLastWritten.set(SystemClock.elapsedRealtime()); 1132 } 1133 1134 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1135 throws IOException { 1136 sb.setLength(0); 1137 while (true) { 1138 int ch = in.read(); 1139 if (ch == -1) { 1140 if (sb.length() == 0) { 1141 return null; 1142 } 1143 throw new IOException("Unexpected EOF"); 1144 } 1145 if (ch == endOfToken) { 1146 return sb.toString(); 1147 } 1148 sb.append((char)ch); 1149 } 1150 } 1151 1152 private AtomicFile getFile() { 1153 File dataDir = Environment.getDataDirectory(); 1154 File systemDir = new File(dataDir, "system"); 1155 File fname = new File(systemDir, "package-usage.list"); 1156 return new AtomicFile(fname); 1157 } 1158 } 1159 1160 class PackageHandler extends Handler { 1161 private boolean mBound = false; 1162 final ArrayList<HandlerParams> mPendingInstalls = 1163 new ArrayList<HandlerParams>(); 1164 1165 private boolean connectToService() { 1166 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1167 " DefaultContainerService"); 1168 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1169 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1170 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1171 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1172 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1173 mBound = true; 1174 return true; 1175 } 1176 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1177 return false; 1178 } 1179 1180 private void disconnectService() { 1181 mContainerService = null; 1182 mBound = false; 1183 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1184 mContext.unbindService(mDefContainerConn); 1185 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1186 } 1187 1188 PackageHandler(Looper looper) { 1189 super(looper); 1190 } 1191 1192 public void handleMessage(Message msg) { 1193 try { 1194 doHandleMessage(msg); 1195 } finally { 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1197 } 1198 } 1199 1200 void doHandleMessage(Message msg) { 1201 switch (msg.what) { 1202 case INIT_COPY: { 1203 HandlerParams params = (HandlerParams) msg.obj; 1204 int idx = mPendingInstalls.size(); 1205 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1206 // If a bind was already initiated we dont really 1207 // need to do anything. The pending install 1208 // will be processed later on. 1209 if (!mBound) { 1210 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1211 System.identityHashCode(mHandler)); 1212 // If this is the only one pending we might 1213 // have to bind to the service again. 1214 if (!connectToService()) { 1215 Slog.e(TAG, "Failed to bind to media container service"); 1216 params.serviceError(); 1217 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1218 System.identityHashCode(mHandler)); 1219 if (params.traceMethod != null) { 1220 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1221 params.traceCookie); 1222 } 1223 return; 1224 } else { 1225 // Once we bind to the service, the first 1226 // pending request will be processed. 1227 mPendingInstalls.add(idx, params); 1228 } 1229 } else { 1230 mPendingInstalls.add(idx, params); 1231 // Already bound to the service. Just make 1232 // sure we trigger off processing the first request. 1233 if (idx == 0) { 1234 mHandler.sendEmptyMessage(MCS_BOUND); 1235 } 1236 } 1237 break; 1238 } 1239 case MCS_BOUND: { 1240 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1241 if (msg.obj != null) { 1242 mContainerService = (IMediaContainerService) msg.obj; 1243 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1244 System.identityHashCode(mHandler)); 1245 } 1246 if (mContainerService == null) { 1247 if (!mBound) { 1248 // Something seriously wrong since we are not bound and we are not 1249 // waiting for connection. Bail out. 1250 Slog.e(TAG, "Cannot bind to media container service"); 1251 for (HandlerParams params : mPendingInstalls) { 1252 // Indicate service bind error 1253 params.serviceError(); 1254 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1255 System.identityHashCode(params)); 1256 if (params.traceMethod != null) { 1257 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1258 params.traceMethod, params.traceCookie); 1259 } 1260 return; 1261 } 1262 mPendingInstalls.clear(); 1263 } else { 1264 Slog.w(TAG, "Waiting to connect to media container service"); 1265 } 1266 } else if (mPendingInstalls.size() > 0) { 1267 HandlerParams params = mPendingInstalls.get(0); 1268 if (params != null) { 1269 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1270 System.identityHashCode(params)); 1271 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1272 if (params.startCopy()) { 1273 // We are done... look for more work or to 1274 // go idle. 1275 if (DEBUG_SD_INSTALL) Log.i(TAG, 1276 "Checking for more work or unbind..."); 1277 // Delete pending install 1278 if (mPendingInstalls.size() > 0) { 1279 mPendingInstalls.remove(0); 1280 } 1281 if (mPendingInstalls.size() == 0) { 1282 if (mBound) { 1283 if (DEBUG_SD_INSTALL) Log.i(TAG, 1284 "Posting delayed MCS_UNBIND"); 1285 removeMessages(MCS_UNBIND); 1286 Message ubmsg = obtainMessage(MCS_UNBIND); 1287 // Unbind after a little delay, to avoid 1288 // continual thrashing. 1289 sendMessageDelayed(ubmsg, 10000); 1290 } 1291 } else { 1292 // There are more pending requests in queue. 1293 // Just post MCS_BOUND message to trigger processing 1294 // of next pending install. 1295 if (DEBUG_SD_INSTALL) Log.i(TAG, 1296 "Posting MCS_BOUND for next work"); 1297 mHandler.sendEmptyMessage(MCS_BOUND); 1298 } 1299 } 1300 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1301 } 1302 } else { 1303 // Should never happen ideally. 1304 Slog.w(TAG, "Empty queue"); 1305 } 1306 break; 1307 } 1308 case MCS_RECONNECT: { 1309 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1310 if (mPendingInstalls.size() > 0) { 1311 if (mBound) { 1312 disconnectService(); 1313 } 1314 if (!connectToService()) { 1315 Slog.e(TAG, "Failed to bind to media container service"); 1316 for (HandlerParams params : mPendingInstalls) { 1317 // Indicate service bind error 1318 params.serviceError(); 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 } 1322 mPendingInstalls.clear(); 1323 } 1324 } 1325 break; 1326 } 1327 case MCS_UNBIND: { 1328 // If there is no actual work left, then time to unbind. 1329 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1330 1331 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1332 if (mBound) { 1333 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1334 1335 disconnectService(); 1336 } 1337 } else if (mPendingInstalls.size() > 0) { 1338 // There are more pending requests in queue. 1339 // Just post MCS_BOUND message to trigger processing 1340 // of next pending install. 1341 mHandler.sendEmptyMessage(MCS_BOUND); 1342 } 1343 1344 break; 1345 } 1346 case MCS_GIVE_UP: { 1347 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1348 HandlerParams params = mPendingInstalls.remove(0); 1349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1350 System.identityHashCode(params)); 1351 break; 1352 } 1353 case SEND_PENDING_BROADCAST: { 1354 String packages[]; 1355 ArrayList<String> components[]; 1356 int size = 0; 1357 int uids[]; 1358 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1359 synchronized (mPackages) { 1360 if (mPendingBroadcasts == null) { 1361 return; 1362 } 1363 size = mPendingBroadcasts.size(); 1364 if (size <= 0) { 1365 // Nothing to be done. Just return 1366 return; 1367 } 1368 packages = new String[size]; 1369 components = new ArrayList[size]; 1370 uids = new int[size]; 1371 int i = 0; // filling out the above arrays 1372 1373 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1374 int packageUserId = mPendingBroadcasts.userIdAt(n); 1375 Iterator<Map.Entry<String, ArrayList<String>>> it 1376 = mPendingBroadcasts.packagesForUserId(packageUserId) 1377 .entrySet().iterator(); 1378 while (it.hasNext() && i < size) { 1379 Map.Entry<String, ArrayList<String>> ent = it.next(); 1380 packages[i] = ent.getKey(); 1381 components[i] = ent.getValue(); 1382 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1383 uids[i] = (ps != null) 1384 ? UserHandle.getUid(packageUserId, ps.appId) 1385 : -1; 1386 i++; 1387 } 1388 } 1389 size = i; 1390 mPendingBroadcasts.clear(); 1391 } 1392 // Send broadcasts 1393 for (int i = 0; i < size; i++) { 1394 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1395 } 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1397 break; 1398 } 1399 case START_CLEANING_PACKAGE: { 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1401 final String packageName = (String)msg.obj; 1402 final int userId = msg.arg1; 1403 final boolean andCode = msg.arg2 != 0; 1404 synchronized (mPackages) { 1405 if (userId == UserHandle.USER_ALL) { 1406 int[] users = sUserManager.getUserIds(); 1407 for (int user : users) { 1408 mSettings.addPackageToCleanLPw( 1409 new PackageCleanItem(user, packageName, andCode)); 1410 } 1411 } else { 1412 mSettings.addPackageToCleanLPw( 1413 new PackageCleanItem(userId, packageName, andCode)); 1414 } 1415 } 1416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1417 startCleaningPackages(); 1418 } break; 1419 case POST_INSTALL: { 1420 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1421 1422 PostInstallData data = mRunningInstalls.get(msg.arg1); 1423 mRunningInstalls.delete(msg.arg1); 1424 boolean deleteOld = false; 1425 1426 if (data != null) { 1427 InstallArgs args = data.args; 1428 PackageInstalledInfo res = data.res; 1429 1430 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1431 //TODO: Broadcast for child packages too 1432 final String packageName = res.pkg.applicationInfo.packageName; 1433 res.removedInfo.sendBroadcast(false, true, false); 1434 Bundle extras = new Bundle(1); 1435 extras.putInt(Intent.EXTRA_UID, res.uid); 1436 1437 // Now that we successfully installed the package, grant runtime 1438 // permissions if requested before broadcasting the install. 1439 if ((args.installFlags 1440 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 1441 && res.pkg.applicationInfo.targetSdkVersion 1442 >= Build.VERSION_CODES.M) { 1443 grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(), 1444 args.installGrantPermissions); 1445 } 1446 1447 synchronized (mPackages) { 1448 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1449 } 1450 1451 // Determine the set of users who are adding this 1452 // package for the first time vs. those who are seeing 1453 // an update. 1454 int[] firstUsers; 1455 int[] updateUsers = new int[0]; 1456 if (res.origUsers == null || res.origUsers.length == 0) { 1457 firstUsers = res.newUsers; 1458 } else { 1459 firstUsers = new int[0]; 1460 for (int i=0; i<res.newUsers.length; i++) { 1461 int user = res.newUsers[i]; 1462 boolean isNew = true; 1463 for (int j=0; j<res.origUsers.length; j++) { 1464 if (res.origUsers[j] == user) { 1465 isNew = false; 1466 break; 1467 } 1468 } 1469 if (isNew) { 1470 int[] newFirst = new int[firstUsers.length+1]; 1471 System.arraycopy(firstUsers, 0, newFirst, 0, 1472 firstUsers.length); 1473 newFirst[firstUsers.length] = user; 1474 firstUsers = newFirst; 1475 } else { 1476 int[] newUpdate = new int[updateUsers.length+1]; 1477 System.arraycopy(updateUsers, 0, newUpdate, 0, 1478 updateUsers.length); 1479 newUpdate[updateUsers.length] = user; 1480 updateUsers = newUpdate; 1481 } 1482 } 1483 } 1484 // don't broadcast for ephemeral installs/updates 1485 final boolean isEphemeral = isEphemeral(res.pkg); 1486 if (!isEphemeral) { 1487 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1488 extras, 0 /*flags*/, null /*targetPackage*/, 1489 null /*finishedReceiver*/, firstUsers); 1490 } 1491 final boolean update = res.removedInfo.removedPackage != null; 1492 if (update) { 1493 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1494 } 1495 if (!isEphemeral) { 1496 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1497 extras, 0 /*flags*/, null /*targetPackage*/, 1498 null /*finishedReceiver*/, updateUsers); 1499 } 1500 if (update) { 1501 if (!isEphemeral) { 1502 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1503 packageName, extras, 0 /*flags*/, 1504 null /*targetPackage*/, null /*finishedReceiver*/, 1505 updateUsers); 1506 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1507 null /*package*/, null /*extras*/, 0 /*flags*/, 1508 packageName /*targetPackage*/, 1509 null /*finishedReceiver*/, updateUsers); 1510 } 1511 1512 // treat asec-hosted packages like removable media on upgrade 1513 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1514 if (DEBUG_INSTALL) { 1515 Slog.i(TAG, "upgrading pkg " + res.pkg 1516 + " is ASEC-hosted -> AVAILABLE"); 1517 } 1518 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1519 ArrayList<String> pkgList = new ArrayList<String>(1); 1520 pkgList.add(packageName); 1521 sendResourcesChangedBroadcast(true, true, 1522 pkgList,uidArray, null); 1523 } 1524 } 1525 if (res.removedInfo.args != null) { 1526 // Remove the replaced package's older resources safely now 1527 deleteOld = true; 1528 } 1529 1530 1531 // Work that needs to happen on first install within each user 1532 if (firstUsers.length > 0) { 1533 for (int userId : firstUsers) { 1534 synchronized (mPackages) { 1535 // If this app is a browser and it's newly-installed for 1536 // some users, clear any default-browser state in those 1537 // users. The app's nature doesn't depend on the user, 1538 // so we can just check its browser nature in any user 1539 // and generalize. 1540 if (packageIsBrowser(packageName, firstUsers[0])) { 1541 mSettings.setDefaultBrowserPackageNameLPw( 1542 null, userId); 1543 } 1544 1545 // We may also need to apply pending (restored) runtime 1546 // permission grants within these users. 1547 mSettings.applyPendingPermissionGrantsLPw( 1548 packageName, userId); 1549 } 1550 } 1551 } 1552 // Log current value of "unknown sources" setting 1553 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1554 getUnknownSourcesSettings()); 1555 } 1556 // Force a gc to clear up things 1557 Runtime.getRuntime().gc(); 1558 // We delete after a gc for applications on sdcard. 1559 if (deleteOld) { 1560 synchronized (mInstallLock) { 1561 res.removedInfo.args.doPostDeleteLI(true); 1562 } 1563 } 1564 if (args.observer != null) { 1565 try { 1566 Bundle extras = extrasForInstallResult(res); 1567 args.observer.onPackageInstalled(res.name, res.returnCode, 1568 res.returnMsg, extras); 1569 } catch (RemoteException e) { 1570 Slog.i(TAG, "Observer no longer exists."); 1571 } 1572 } 1573 if (args.traceMethod != null) { 1574 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1575 args.traceCookie); 1576 } 1577 return; 1578 } else { 1579 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1580 } 1581 1582 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1583 } break; 1584 case UPDATED_MEDIA_STATUS: { 1585 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1586 boolean reportStatus = msg.arg1 == 1; 1587 boolean doGc = msg.arg2 == 1; 1588 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1589 if (doGc) { 1590 // Force a gc to clear up stale containers. 1591 Runtime.getRuntime().gc(); 1592 } 1593 if (msg.obj != null) { 1594 @SuppressWarnings("unchecked") 1595 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1596 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1597 // Unload containers 1598 unloadAllContainers(args); 1599 } 1600 if (reportStatus) { 1601 try { 1602 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1603 PackageHelper.getMountService().finishMediaUpdate(); 1604 } catch (RemoteException e) { 1605 Log.e(TAG, "MountService not running?"); 1606 } 1607 } 1608 } break; 1609 case WRITE_SETTINGS: { 1610 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1611 synchronized (mPackages) { 1612 removeMessages(WRITE_SETTINGS); 1613 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1614 mSettings.writeLPr(); 1615 mDirtyUsers.clear(); 1616 } 1617 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1618 } break; 1619 case WRITE_PACKAGE_RESTRICTIONS: { 1620 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1621 synchronized (mPackages) { 1622 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1623 for (int userId : mDirtyUsers) { 1624 mSettings.writePackageRestrictionsLPr(userId); 1625 } 1626 mDirtyUsers.clear(); 1627 } 1628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1629 } break; 1630 case CHECK_PENDING_VERIFICATION: { 1631 final int verificationId = msg.arg1; 1632 final PackageVerificationState state = mPendingVerification.get(verificationId); 1633 1634 if ((state != null) && !state.timeoutExtended()) { 1635 final InstallArgs args = state.getInstallArgs(); 1636 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1637 1638 Slog.i(TAG, "Verification timed out for " + originUri); 1639 mPendingVerification.remove(verificationId); 1640 1641 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1642 1643 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1644 Slog.i(TAG, "Continuing with installation of " + originUri); 1645 state.setVerifierResponse(Binder.getCallingUid(), 1646 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1647 broadcastPackageVerified(verificationId, originUri, 1648 PackageManager.VERIFICATION_ALLOW, 1649 state.getInstallArgs().getUser()); 1650 try { 1651 ret = args.copyApk(mContainerService, true); 1652 } catch (RemoteException e) { 1653 Slog.e(TAG, "Could not contact the ContainerService"); 1654 } 1655 } else { 1656 broadcastPackageVerified(verificationId, originUri, 1657 PackageManager.VERIFICATION_REJECT, 1658 state.getInstallArgs().getUser()); 1659 } 1660 1661 Trace.asyncTraceEnd( 1662 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1663 1664 processPendingInstall(args, ret); 1665 mHandler.sendEmptyMessage(MCS_UNBIND); 1666 } 1667 break; 1668 } 1669 case PACKAGE_VERIFIED: { 1670 final int verificationId = msg.arg1; 1671 1672 final PackageVerificationState state = mPendingVerification.get(verificationId); 1673 if (state == null) { 1674 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1675 break; 1676 } 1677 1678 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1679 1680 state.setVerifierResponse(response.callerUid, response.code); 1681 1682 if (state.isVerificationComplete()) { 1683 mPendingVerification.remove(verificationId); 1684 1685 final InstallArgs args = state.getInstallArgs(); 1686 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1687 1688 int ret; 1689 if (state.isInstallAllowed()) { 1690 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1691 broadcastPackageVerified(verificationId, originUri, 1692 response.code, state.getInstallArgs().getUser()); 1693 try { 1694 ret = args.copyApk(mContainerService, true); 1695 } catch (RemoteException e) { 1696 Slog.e(TAG, "Could not contact the ContainerService"); 1697 } 1698 } else { 1699 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1700 } 1701 1702 Trace.asyncTraceEnd( 1703 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1704 1705 processPendingInstall(args, ret); 1706 mHandler.sendEmptyMessage(MCS_UNBIND); 1707 } 1708 1709 break; 1710 } 1711 case START_INTENT_FILTER_VERIFICATIONS: { 1712 IFVerificationParams params = (IFVerificationParams) msg.obj; 1713 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1714 params.replacing, params.pkg); 1715 break; 1716 } 1717 case INTENT_FILTER_VERIFIED: { 1718 final int verificationId = msg.arg1; 1719 1720 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1721 verificationId); 1722 if (state == null) { 1723 Slog.w(TAG, "Invalid IntentFilter verification token " 1724 + verificationId + " received"); 1725 break; 1726 } 1727 1728 final int userId = state.getUserId(); 1729 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1731 "Processing IntentFilter verification with token:" 1732 + verificationId + " and userId:" + userId); 1733 1734 final IntentFilterVerificationResponse response = 1735 (IntentFilterVerificationResponse) msg.obj; 1736 1737 state.setVerifierResponse(response.callerUid, response.code); 1738 1739 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1740 "IntentFilter verification with token:" + verificationId 1741 + " and userId:" + userId 1742 + " is settings verifier response with response code:" 1743 + response.code); 1744 1745 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1746 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1747 + response.getFailedDomainsString()); 1748 } 1749 1750 if (state.isVerificationComplete()) { 1751 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1752 } else { 1753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1754 "IntentFilter verification with token:" + verificationId 1755 + " was not said to be complete"); 1756 } 1757 1758 break; 1759 } 1760 } 1761 } 1762 } 1763 1764 private StorageEventListener mStorageListener = new StorageEventListener() { 1765 @Override 1766 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1767 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1768 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1769 final String volumeUuid = vol.getFsUuid(); 1770 1771 // Clean up any users or apps that were removed or recreated 1772 // while this volume was missing 1773 reconcileUsers(volumeUuid); 1774 reconcileApps(volumeUuid); 1775 1776 // Clean up any install sessions that expired or were 1777 // cancelled while this volume was missing 1778 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1779 1780 loadPrivatePackages(vol); 1781 1782 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1783 unloadPrivatePackages(vol); 1784 } 1785 } 1786 1787 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1788 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1789 updateExternalMediaStatus(true, false); 1790 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1791 updateExternalMediaStatus(false, false); 1792 } 1793 } 1794 } 1795 1796 @Override 1797 public void onVolumeForgotten(String fsUuid) { 1798 if (TextUtils.isEmpty(fsUuid)) { 1799 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1800 return; 1801 } 1802 1803 // Remove any apps installed on the forgotten volume 1804 synchronized (mPackages) { 1805 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1806 for (PackageSetting ps : packages) { 1807 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1808 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1809 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1810 } 1811 1812 mSettings.onVolumeForgotten(fsUuid); 1813 mSettings.writeLPr(); 1814 } 1815 } 1816 }; 1817 1818 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId, 1819 String[] grantedPermissions) { 1820 if (userId >= UserHandle.USER_SYSTEM) { 1821 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1822 } else if (userId == UserHandle.USER_ALL) { 1823 final int[] userIds; 1824 synchronized (mPackages) { 1825 userIds = UserManagerService.getInstance().getUserIds(); 1826 } 1827 for (int someUserId : userIds) { 1828 grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions); 1829 } 1830 } 1831 1832 // We could have touched GID membership, so flush out packages.list 1833 synchronized (mPackages) { 1834 mSettings.writePackageListLPr(); 1835 } 1836 } 1837 1838 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1839 String[] grantedPermissions) { 1840 SettingBase sb = (SettingBase) pkg.mExtras; 1841 if (sb == null) { 1842 return; 1843 } 1844 1845 PermissionsState permissionsState = sb.getPermissionsState(); 1846 1847 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1848 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1849 1850 synchronized (mPackages) { 1851 for (String permission : pkg.requestedPermissions) { 1852 BasePermission bp = mSettings.mPermissions.get(permission); 1853 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1854 && (grantedPermissions == null 1855 || ArrayUtils.contains(grantedPermissions, permission))) { 1856 final int flags = permissionsState.getPermissionFlags(permission, userId); 1857 // Installer cannot change immutable permissions. 1858 if ((flags & immutableFlags) == 0) { 1859 grantRuntimePermission(pkg.packageName, permission, userId); 1860 } 1861 } 1862 } 1863 } 1864 } 1865 1866 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1867 Bundle extras = null; 1868 switch (res.returnCode) { 1869 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1870 extras = new Bundle(); 1871 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1872 res.origPermission); 1873 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1874 res.origPackage); 1875 break; 1876 } 1877 case PackageManager.INSTALL_SUCCEEDED: { 1878 extras = new Bundle(); 1879 extras.putBoolean(Intent.EXTRA_REPLACING, 1880 res.removedInfo != null && res.removedInfo.removedPackage != null); 1881 break; 1882 } 1883 } 1884 return extras; 1885 } 1886 1887 void scheduleWriteSettingsLocked() { 1888 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1889 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1890 } 1891 } 1892 1893 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1894 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1895 scheduleWritePackageRestrictionsLocked(userId); 1896 } 1897 1898 void scheduleWritePackageRestrictionsLocked(int userId) { 1899 final int[] userIds = (userId == UserHandle.USER_ALL) 1900 ? sUserManager.getUserIds() : new int[]{userId}; 1901 for (int nextUserId : userIds) { 1902 if (!sUserManager.exists(nextUserId)) return; 1903 mDirtyUsers.add(nextUserId); 1904 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1905 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1906 } 1907 } 1908 } 1909 1910 public static PackageManagerService main(Context context, Installer installer, 1911 boolean factoryTest, boolean onlyCore) { 1912 PackageManagerService m = new PackageManagerService(context, installer, 1913 factoryTest, onlyCore); 1914 m.enableSystemUserPackages(); 1915 ServiceManager.addService("package", m); 1916 return m; 1917 } 1918 1919 private void enableSystemUserPackages() { 1920 if (!UserManager.isSplitSystemUser()) { 1921 return; 1922 } 1923 // For system user, enable apps based on the following conditions: 1924 // - app is whitelisted or belong to one of these groups: 1925 // -- system app which has no launcher icons 1926 // -- system app which has INTERACT_ACROSS_USERS permission 1927 // -- system IME app 1928 // - app is not in the blacklist 1929 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1930 Set<String> enableApps = new ArraySet<>(); 1931 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1932 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1933 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1934 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1935 enableApps.addAll(wlApps); 1936 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1937 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1938 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1939 enableApps.removeAll(blApps); 1940 Log.i(TAG, "Applications installed for system user: " + enableApps); 1941 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1942 UserHandle.SYSTEM); 1943 final int allAppsSize = allAps.size(); 1944 synchronized (mPackages) { 1945 for (int i = 0; i < allAppsSize; i++) { 1946 String pName = allAps.get(i); 1947 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1948 // Should not happen, but we shouldn't be failing if it does 1949 if (pkgSetting == null) { 1950 continue; 1951 } 1952 boolean install = enableApps.contains(pName); 1953 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 1954 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 1955 + " for system user"); 1956 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 1957 } 1958 } 1959 } 1960 } 1961 1962 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1963 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1964 Context.DISPLAY_SERVICE); 1965 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1966 } 1967 1968 public PackageManagerService(Context context, Installer installer, 1969 boolean factoryTest, boolean onlyCore) { 1970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1971 SystemClock.uptimeMillis()); 1972 1973 if (mSdkVersion <= 0) { 1974 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1975 } 1976 1977 mContext = context; 1978 mFactoryTest = factoryTest; 1979 mOnlyCore = onlyCore; 1980 mMetrics = new DisplayMetrics(); 1981 mSettings = new Settings(mPackages); 1982 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1983 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1984 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1985 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1986 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1987 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1988 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1989 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1990 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1991 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1992 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1993 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1994 1995 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1996 if (separateProcesses != null && separateProcesses.length() > 0) { 1997 if ("*".equals(separateProcesses)) { 1998 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1999 mSeparateProcesses = null; 2000 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2001 } else { 2002 mDefParseFlags = 0; 2003 mSeparateProcesses = separateProcesses.split(","); 2004 Slog.w(TAG, "Running with debug.separate_processes: " 2005 + separateProcesses); 2006 } 2007 } else { 2008 mDefParseFlags = 0; 2009 mSeparateProcesses = null; 2010 } 2011 2012 mInstaller = installer; 2013 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2014 "*dexopt*"); 2015 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2016 2017 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2018 FgThread.get().getLooper()); 2019 2020 getDefaultDisplayMetrics(context, mMetrics); 2021 2022 SystemConfig systemConfig = SystemConfig.getInstance(); 2023 mGlobalGids = systemConfig.getGlobalGids(); 2024 mSystemPermissions = systemConfig.getSystemPermissions(); 2025 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2026 2027 synchronized (mInstallLock) { 2028 // writer 2029 synchronized (mPackages) { 2030 mHandlerThread = new ServiceThread(TAG, 2031 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2032 mHandlerThread.start(); 2033 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2034 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2035 2036 File dataDir = Environment.getDataDirectory(); 2037 mAppInstallDir = new File(dataDir, "app"); 2038 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2039 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2040 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2041 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2042 2043 sUserManager = new UserManagerService(context, this, mPackages); 2044 2045 // Propagate permission configuration in to package manager. 2046 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2047 = systemConfig.getPermissions(); 2048 for (int i=0; i<permConfig.size(); i++) { 2049 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2050 BasePermission bp = mSettings.mPermissions.get(perm.name); 2051 if (bp == null) { 2052 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2053 mSettings.mPermissions.put(perm.name, bp); 2054 } 2055 if (perm.gids != null) { 2056 bp.setGids(perm.gids, perm.perUser); 2057 } 2058 } 2059 2060 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2061 for (int i=0; i<libConfig.size(); i++) { 2062 mSharedLibraries.put(libConfig.keyAt(i), 2063 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2064 } 2065 2066 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2067 2068 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2069 2070 String customResolverActivity = Resources.getSystem().getString( 2071 R.string.config_customResolverActivity); 2072 if (TextUtils.isEmpty(customResolverActivity)) { 2073 customResolverActivity = null; 2074 } else { 2075 mCustomResolverComponentName = ComponentName.unflattenFromString( 2076 customResolverActivity); 2077 } 2078 2079 long startTime = SystemClock.uptimeMillis(); 2080 2081 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2082 startTime); 2083 2084 // Set flag to monitor and not change apk file paths when 2085 // scanning install directories. 2086 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2087 2088 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2089 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2090 2091 if (bootClassPath == null) { 2092 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2093 } 2094 2095 if (systemServerClassPath == null) { 2096 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2097 } 2098 2099 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2100 final String[] dexCodeInstructionSets = 2101 getDexCodeInstructionSets( 2102 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2103 2104 /** 2105 * Ensure all external libraries have had dexopt run on them. 2106 */ 2107 if (mSharedLibraries.size() > 0) { 2108 // NOTE: For now, we're compiling these system "shared libraries" 2109 // (and framework jars) into all available architectures. It's possible 2110 // to compile them only when we come across an app that uses them (there's 2111 // already logic for that in scanPackageLI) but that adds some complexity. 2112 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2113 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2114 final String lib = libEntry.path; 2115 if (lib == null) { 2116 continue; 2117 } 2118 2119 try { 2120 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 2121 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2122 // Shared libraries do not have profiles so we perform a full 2123 // AOT compilation. 2124 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2125 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2126 StorageManager.UUID_PRIVATE_INTERNAL, 2127 false /*useProfiles*/); 2128 } 2129 } catch (FileNotFoundException e) { 2130 Slog.w(TAG, "Library not found: " + lib); 2131 } catch (IOException | InstallerException e) { 2132 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2133 + e.getMessage()); 2134 } 2135 } 2136 } 2137 } 2138 2139 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2140 2141 final VersionInfo ver = mSettings.getInternalVersion(); 2142 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2143 // when upgrading from pre-M, promote system app permissions from install to runtime 2144 mPromoteSystemApps = 2145 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2146 2147 // save off the names of pre-existing system packages prior to scanning; we don't 2148 // want to automatically grant runtime permissions for new system apps 2149 if (mPromoteSystemApps) { 2150 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2151 while (pkgSettingIter.hasNext()) { 2152 PackageSetting ps = pkgSettingIter.next(); 2153 if (isSystemApp(ps)) { 2154 mExistingSystemPackages.add(ps.name); 2155 } 2156 } 2157 } 2158 2159 // Collect vendor overlay packages. 2160 // (Do this before scanning any apps.) 2161 // For security and version matching reason, only consider 2162 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2163 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2164 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2165 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2166 2167 // Find base frameworks (resource packages without code). 2168 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2169 | PackageParser.PARSE_IS_SYSTEM_DIR 2170 | PackageParser.PARSE_IS_PRIVILEGED, 2171 scanFlags | SCAN_NO_DEX, 0); 2172 2173 // Collected privileged system packages. 2174 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2175 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2176 | PackageParser.PARSE_IS_SYSTEM_DIR 2177 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2178 2179 // Collect ordinary system packages. 2180 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2181 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2182 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2183 2184 // Collect all vendor packages. 2185 File vendorAppDir = new File("/vendor/app"); 2186 try { 2187 vendorAppDir = vendorAppDir.getCanonicalFile(); 2188 } catch (IOException e) { 2189 // failed to look up canonical path, continue with original one 2190 } 2191 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2192 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2193 2194 // Collect all OEM packages. 2195 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2196 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2197 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2198 2199 // Prune any system packages that no longer exist. 2200 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2201 if (!mOnlyCore) { 2202 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2203 while (psit.hasNext()) { 2204 PackageSetting ps = psit.next(); 2205 2206 /* 2207 * If this is not a system app, it can't be a 2208 * disable system app. 2209 */ 2210 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2211 continue; 2212 } 2213 2214 /* 2215 * If the package is scanned, it's not erased. 2216 */ 2217 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2218 if (scannedPkg != null) { 2219 /* 2220 * If the system app is both scanned and in the 2221 * disabled packages list, then it must have been 2222 * added via OTA. Remove it from the currently 2223 * scanned package so the previously user-installed 2224 * application can be scanned. 2225 */ 2226 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2227 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2228 + ps.name + "; removing system app. Last known codePath=" 2229 + ps.codePathString + ", installStatus=" + ps.installStatus 2230 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2231 + scannedPkg.mVersionCode); 2232 removePackageSettingLI(scannedPkg, true); 2233 mExpectingBetter.put(ps.name, ps.codePath); 2234 } 2235 2236 continue; 2237 } 2238 2239 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2240 psit.remove(); 2241 logCriticalInfo(Log.WARN, "System package " + ps.name 2242 + " no longer exists; wiping its data"); 2243 removeDataDirsLI(null, ps.name); 2244 } else { 2245 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2246 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2247 possiblyDeletedUpdatedSystemApps.add(ps.name); 2248 } 2249 } 2250 } 2251 } 2252 2253 //look for any incomplete package installations 2254 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2255 //clean up list 2256 for(int i = 0; i < deletePkgsList.size(); i++) { 2257 //clean up here 2258 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2259 } 2260 //delete tmp files 2261 deleteTempPackageFiles(); 2262 2263 // Remove any shared userIDs that have no associated packages 2264 mSettings.pruneSharedUsersLPw(); 2265 2266 if (!mOnlyCore) { 2267 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2268 SystemClock.uptimeMillis()); 2269 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2270 2271 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2272 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2273 2274 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2275 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2276 2277 /** 2278 * Remove disable package settings for any updated system 2279 * apps that were removed via an OTA. If they're not a 2280 * previously-updated app, remove them completely. 2281 * Otherwise, just revoke their system-level permissions. 2282 */ 2283 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2284 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2285 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2286 2287 String msg; 2288 if (deletedPkg == null) { 2289 msg = "Updated system package " + deletedAppName 2290 + " no longer exists; wiping its data"; 2291 removeDataDirsLI(null, deletedAppName); 2292 } else { 2293 msg = "Updated system app + " + deletedAppName 2294 + " no longer present; removing system privileges for " 2295 + deletedAppName; 2296 2297 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2298 2299 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2300 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2301 } 2302 logCriticalInfo(Log.WARN, msg); 2303 } 2304 2305 /** 2306 * Make sure all system apps that we expected to appear on 2307 * the userdata partition actually showed up. If they never 2308 * appeared, crawl back and revive the system version. 2309 */ 2310 for (int i = 0; i < mExpectingBetter.size(); i++) { 2311 final String packageName = mExpectingBetter.keyAt(i); 2312 if (!mPackages.containsKey(packageName)) { 2313 final File scanFile = mExpectingBetter.valueAt(i); 2314 2315 logCriticalInfo(Log.WARN, "Expected better " + packageName 2316 + " but never showed up; reverting to system"); 2317 2318 final int reparseFlags; 2319 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2320 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2321 | PackageParser.PARSE_IS_SYSTEM_DIR 2322 | PackageParser.PARSE_IS_PRIVILEGED; 2323 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2324 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2325 | PackageParser.PARSE_IS_SYSTEM_DIR; 2326 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2327 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2328 | PackageParser.PARSE_IS_SYSTEM_DIR; 2329 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2330 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2331 | PackageParser.PARSE_IS_SYSTEM_DIR; 2332 } else { 2333 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2334 continue; 2335 } 2336 2337 mSettings.enableSystemPackageLPw(packageName); 2338 2339 try { 2340 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2341 } catch (PackageManagerException e) { 2342 Slog.e(TAG, "Failed to parse original system package: " 2343 + e.getMessage()); 2344 } 2345 } 2346 } 2347 } 2348 mExpectingBetter.clear(); 2349 2350 // Now that we know all of the shared libraries, update all clients to have 2351 // the correct library paths. 2352 updateAllSharedLibrariesLPw(); 2353 2354 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2355 // NOTE: We ignore potential failures here during a system scan (like 2356 // the rest of the commands above) because there's precious little we 2357 // can do about it. A settings error is reported, though. 2358 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2359 false /* boot complete */); 2360 } 2361 2362 // Now that we know all the packages we are keeping, 2363 // read and update their last usage times. 2364 mPackageUsage.readLP(); 2365 2366 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2367 SystemClock.uptimeMillis()); 2368 Slog.i(TAG, "Time to scan packages: " 2369 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2370 + " seconds"); 2371 2372 // If the platform SDK has changed since the last time we booted, 2373 // we need to re-grant app permission to catch any new ones that 2374 // appear. This is really a hack, and means that apps can in some 2375 // cases get permissions that the user didn't initially explicitly 2376 // allow... it would be nice to have some better way to handle 2377 // this situation. 2378 int updateFlags = UPDATE_PERMISSIONS_ALL; 2379 if (ver.sdkVersion != mSdkVersion) { 2380 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2381 + mSdkVersion + "; regranting permissions for internal storage"); 2382 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2383 } 2384 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2385 ver.sdkVersion = mSdkVersion; 2386 2387 // If this is the first boot or an update from pre-M, and it is a normal 2388 // boot, then we need to initialize the default preferred apps across 2389 // all defined users. 2390 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2391 for (UserInfo user : sUserManager.getUsers(true)) { 2392 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2393 applyFactoryDefaultBrowserLPw(user.id); 2394 primeDomainVerificationsLPw(user.id); 2395 } 2396 } 2397 2398 // Prepare storage for system user really early during boot, 2399 // since core system apps like SettingsProvider and SystemUI 2400 // can't wait for user to start 2401 final int storageFlags; 2402 if (StorageManager.isFileBasedEncryptionEnabled()) { 2403 storageFlags = StorageManager.FLAG_STORAGE_DE; 2404 } else { 2405 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2406 } 2407 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2408 storageFlags); 2409 2410 if (!StorageManager.isFileBasedEncryptionEnabled() 2411 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 2412 // When upgrading a non-FBE device, we might need to shuffle 2413 // around the default storage location of system apps 2414 final List<UserInfo> users = sUserManager.getUsers(true); 2415 for (PackageSetting ps : mSettings.mPackages.values()) { 2416 if (ps.pkg == null || !ps.isSystem()) continue; 2417 final int storageTarget = ps.pkg.applicationInfo.isForceDeviceEncrypted() 2418 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 2419 for (UserInfo user : users) { 2420 if (ps.getInstalled(user.id)) { 2421 try { 2422 mInstaller.migrateAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2423 ps.name, user.id, storageTarget); 2424 } catch (InstallerException e) { 2425 logCriticalInfo(Log.WARN, 2426 "Failed to migrate " + ps.name + ": " + e.getMessage()); 2427 } 2428 // We may have just shuffled around app data 2429 // directories, so prepare it one more time 2430 prepareAppData(StorageManager.UUID_PRIVATE_INTERNAL, user.id, 2431 storageFlags, ps.pkg, false); 2432 } 2433 } 2434 } 2435 } 2436 2437 // If this is first boot after an OTA, and a normal boot, then 2438 // we need to clear code cache directories. 2439 if (mIsUpgrade && !onlyCore) { 2440 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2441 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2442 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2443 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2444 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2445 } 2446 } 2447 ver.fingerprint = Build.FINGERPRINT; 2448 } 2449 2450 checkDefaultBrowser(); 2451 2452 // clear only after permissions and other defaults have been updated 2453 mExistingSystemPackages.clear(); 2454 mPromoteSystemApps = false; 2455 2456 // All the changes are done during package scanning. 2457 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2458 2459 // can downgrade to reader 2460 mSettings.writeLPr(); 2461 2462 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2463 SystemClock.uptimeMillis()); 2464 2465 if (!mOnlyCore) { 2466 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2467 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2468 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2469 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2470 mIntentFilterVerifierComponent); 2471 } else { 2472 mRequiredVerifierPackage = null; 2473 mRequiredInstallerPackage = null; 2474 mIntentFilterVerifierComponent = null; 2475 mIntentFilterVerifier = null; 2476 } 2477 2478 mInstallerService = new PackageInstallerService(context, this); 2479 2480 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2481 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2482 // both the installer and resolver must be present to enable ephemeral 2483 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2484 if (DEBUG_EPHEMERAL) { 2485 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2486 + " installer:" + ephemeralInstallerComponent); 2487 } 2488 mEphemeralResolverComponent = ephemeralResolverComponent; 2489 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2490 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2491 mEphemeralResolverConnection = 2492 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2493 } else { 2494 if (DEBUG_EPHEMERAL) { 2495 final String missingComponent = 2496 (ephemeralResolverComponent == null) 2497 ? (ephemeralInstallerComponent == null) 2498 ? "resolver and installer" 2499 : "resolver" 2500 : "installer"; 2501 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2502 } 2503 mEphemeralResolverComponent = null; 2504 mEphemeralInstallerComponent = null; 2505 mEphemeralResolverConnection = null; 2506 } 2507 2508 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2509 } // synchronized (mPackages) 2510 } // synchronized (mInstallLock) 2511 2512 // Now after opening every single application zip, make sure they 2513 // are all flushed. Not really needed, but keeps things nice and 2514 // tidy. 2515 Runtime.getRuntime().gc(); 2516 2517 // The initial scanning above does many calls into installd while 2518 // holding the mPackages lock, but we're mostly interested in yelling 2519 // once we have a booted system. 2520 mInstaller.setWarnIfHeld(mPackages); 2521 2522 // Expose private service for system components to use. 2523 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2524 } 2525 2526 @Override 2527 public boolean isFirstBoot() { 2528 return !mRestoredSettings; 2529 } 2530 2531 @Override 2532 public boolean isOnlyCoreApps() { 2533 return mOnlyCore; 2534 } 2535 2536 @Override 2537 public boolean isUpgrade() { 2538 return mIsUpgrade; 2539 } 2540 2541 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2542 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2543 2544 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2545 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2546 if (matches.size() == 1) { 2547 return matches.get(0).getComponentInfo().packageName; 2548 } else { 2549 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2550 return null; 2551 } 2552 } 2553 2554 private @NonNull String getRequiredInstallerLPr() { 2555 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2556 intent.addCategory(Intent.CATEGORY_DEFAULT); 2557 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2558 2559 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2560 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2561 if (matches.size() == 1) { 2562 return matches.get(0).getComponentInfo().packageName; 2563 } else { 2564 throw new RuntimeException("There must be exactly one installer; found " + matches); 2565 } 2566 } 2567 2568 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2569 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2570 2571 final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE, 2572 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2573 ResolveInfo best = null; 2574 final int N = matches.size(); 2575 for (int i = 0; i < N; i++) { 2576 final ResolveInfo cur = matches.get(i); 2577 final String packageName = cur.getComponentInfo().packageName; 2578 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2579 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2580 continue; 2581 } 2582 2583 if (best == null || cur.priority > best.priority) { 2584 best = cur; 2585 } 2586 } 2587 2588 if (best != null) { 2589 return best.getComponentInfo().getComponentName(); 2590 } else { 2591 throw new RuntimeException("There must be at least one intent filter verifier"); 2592 } 2593 } 2594 2595 private @Nullable ComponentName getEphemeralResolverLPr() { 2596 final String[] packageArray = 2597 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2598 if (packageArray.length == 0) { 2599 if (DEBUG_EPHEMERAL) { 2600 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2601 } 2602 return null; 2603 } 2604 2605 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2606 final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null, 2607 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2608 2609 final int N = resolvers.size(); 2610 if (N == 0) { 2611 if (DEBUG_EPHEMERAL) { 2612 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2613 } 2614 return null; 2615 } 2616 2617 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2618 for (int i = 0; i < N; i++) { 2619 final ResolveInfo info = resolvers.get(i); 2620 2621 if (info.serviceInfo == null) { 2622 continue; 2623 } 2624 2625 final String packageName = info.serviceInfo.packageName; 2626 if (!possiblePackages.contains(packageName)) { 2627 if (DEBUG_EPHEMERAL) { 2628 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2629 + " pkg: " + packageName + ", info:" + info); 2630 } 2631 continue; 2632 } 2633 2634 if (DEBUG_EPHEMERAL) { 2635 Slog.v(TAG, "Ephemeral resolver found;" 2636 + " pkg: " + packageName + ", info:" + info); 2637 } 2638 return new ComponentName(packageName, info.serviceInfo.name); 2639 } 2640 if (DEBUG_EPHEMERAL) { 2641 Slog.v(TAG, "Ephemeral resolver NOT found"); 2642 } 2643 return null; 2644 } 2645 2646 private @Nullable ComponentName getEphemeralInstallerLPr() { 2647 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2648 intent.addCategory(Intent.CATEGORY_DEFAULT); 2649 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2650 2651 final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE, 2652 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2653 if (matches.size() == 0) { 2654 return null; 2655 } else if (matches.size() == 1) { 2656 return matches.get(0).getComponentInfo().getComponentName(); 2657 } else { 2658 throw new RuntimeException( 2659 "There must be at most one ephemeral installer; found " + matches); 2660 } 2661 } 2662 2663 private void primeDomainVerificationsLPw(int userId) { 2664 if (DEBUG_DOMAIN_VERIFICATION) { 2665 Slog.d(TAG, "Priming domain verifications in user " + userId); 2666 } 2667 2668 SystemConfig systemConfig = SystemConfig.getInstance(); 2669 ArraySet<String> packages = systemConfig.getLinkedApps(); 2670 ArraySet<String> domains = new ArraySet<String>(); 2671 2672 for (String packageName : packages) { 2673 PackageParser.Package pkg = mPackages.get(packageName); 2674 if (pkg != null) { 2675 if (!pkg.isSystemApp()) { 2676 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2677 continue; 2678 } 2679 2680 domains.clear(); 2681 for (PackageParser.Activity a : pkg.activities) { 2682 for (ActivityIntentInfo filter : a.intents) { 2683 if (hasValidDomains(filter)) { 2684 domains.addAll(filter.getHostsList()); 2685 } 2686 } 2687 } 2688 2689 if (domains.size() > 0) { 2690 if (DEBUG_DOMAIN_VERIFICATION) { 2691 Slog.v(TAG, " + " + packageName); 2692 } 2693 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2694 // state w.r.t. the formal app-linkage "no verification attempted" state; 2695 // and then 'always' in the per-user state actually used for intent resolution. 2696 final IntentFilterVerificationInfo ivi; 2697 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2698 new ArrayList<String>(domains)); 2699 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2700 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2701 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2702 } else { 2703 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2704 + "' does not handle web links"); 2705 } 2706 } else { 2707 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2708 } 2709 } 2710 2711 scheduleWritePackageRestrictionsLocked(userId); 2712 scheduleWriteSettingsLocked(); 2713 } 2714 2715 private void applyFactoryDefaultBrowserLPw(int userId) { 2716 // The default browser app's package name is stored in a string resource, 2717 // with a product-specific overlay used for vendor customization. 2718 String browserPkg = mContext.getResources().getString( 2719 com.android.internal.R.string.default_browser); 2720 if (!TextUtils.isEmpty(browserPkg)) { 2721 // non-empty string => required to be a known package 2722 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2723 if (ps == null) { 2724 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2725 browserPkg = null; 2726 } else { 2727 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2728 } 2729 } 2730 2731 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2732 // default. If there's more than one, just leave everything alone. 2733 if (browserPkg == null) { 2734 calculateDefaultBrowserLPw(userId); 2735 } 2736 } 2737 2738 private void calculateDefaultBrowserLPw(int userId) { 2739 List<String> allBrowsers = resolveAllBrowserApps(userId); 2740 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2741 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2742 } 2743 2744 private List<String> resolveAllBrowserApps(int userId) { 2745 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2746 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2747 PackageManager.MATCH_ALL, userId); 2748 2749 final int count = list.size(); 2750 List<String> result = new ArrayList<String>(count); 2751 for (int i=0; i<count; i++) { 2752 ResolveInfo info = list.get(i); 2753 if (info.activityInfo == null 2754 || !info.handleAllWebDataURI 2755 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2756 || result.contains(info.activityInfo.packageName)) { 2757 continue; 2758 } 2759 result.add(info.activityInfo.packageName); 2760 } 2761 2762 return result; 2763 } 2764 2765 private boolean packageIsBrowser(String packageName, int userId) { 2766 List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null, 2767 PackageManager.MATCH_ALL, userId); 2768 final int N = list.size(); 2769 for (int i = 0; i < N; i++) { 2770 ResolveInfo info = list.get(i); 2771 if (packageName.equals(info.activityInfo.packageName)) { 2772 return true; 2773 } 2774 } 2775 return false; 2776 } 2777 2778 private void checkDefaultBrowser() { 2779 final int myUserId = UserHandle.myUserId(); 2780 final String packageName = getDefaultBrowserPackageName(myUserId); 2781 if (packageName != null) { 2782 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2783 if (info == null) { 2784 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2785 synchronized (mPackages) { 2786 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2787 } 2788 } 2789 } 2790 } 2791 2792 @Override 2793 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2794 throws RemoteException { 2795 try { 2796 return super.onTransact(code, data, reply, flags); 2797 } catch (RuntimeException e) { 2798 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2799 Slog.wtf(TAG, "Package Manager Crash", e); 2800 } 2801 throw e; 2802 } 2803 } 2804 2805 void cleanupInstallFailedPackage(PackageSetting ps) { 2806 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2807 2808 removeDataDirsLI(ps.volumeUuid, ps.name); 2809 if (ps.codePath != null) { 2810 removeCodePathLI(ps.codePath); 2811 } 2812 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2813 if (ps.resourcePath.isDirectory()) { 2814 FileUtils.deleteContents(ps.resourcePath); 2815 } 2816 ps.resourcePath.delete(); 2817 } 2818 mSettings.removePackageLPw(ps.name); 2819 } 2820 2821 static int[] appendInts(int[] cur, int[] add) { 2822 if (add == null) return cur; 2823 if (cur == null) return add; 2824 final int N = add.length; 2825 for (int i=0; i<N; i++) { 2826 cur = appendInt(cur, add[i]); 2827 } 2828 return cur; 2829 } 2830 2831 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2832 if (!sUserManager.exists(userId)) return null; 2833 final PackageSetting ps = (PackageSetting) p.mExtras; 2834 if (ps == null) { 2835 return null; 2836 } 2837 2838 final PermissionsState permissionsState = ps.getPermissionsState(); 2839 2840 final int[] gids = permissionsState.computeGids(userId); 2841 final Set<String> permissions = permissionsState.getPermissions(userId); 2842 final PackageUserState state = ps.readUserState(userId); 2843 2844 return PackageParser.generatePackageInfo(p, gids, flags, 2845 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2846 } 2847 2848 @Override 2849 public void checkPackageStartable(String packageName, int userId) { 2850 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2851 2852 synchronized (mPackages) { 2853 final PackageSetting ps = mSettings.mPackages.get(packageName); 2854 if (ps == null) { 2855 throw new SecurityException("Package " + packageName + " was not found!"); 2856 } 2857 2858 if (ps.frozen) { 2859 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2860 } 2861 2862 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2863 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2864 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2865 } 2866 } 2867 } 2868 2869 @Override 2870 public boolean isPackageAvailable(String packageName, int userId) { 2871 if (!sUserManager.exists(userId)) return false; 2872 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2873 synchronized (mPackages) { 2874 PackageParser.Package p = mPackages.get(packageName); 2875 if (p != null) { 2876 final PackageSetting ps = (PackageSetting) p.mExtras; 2877 if (ps != null) { 2878 final PackageUserState state = ps.readUserState(userId); 2879 if (state != null) { 2880 return PackageParser.isAvailable(state); 2881 } 2882 } 2883 } 2884 } 2885 return false; 2886 } 2887 2888 @Override 2889 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2890 if (!sUserManager.exists(userId)) return null; 2891 flags = updateFlagsForPackage(flags, userId, packageName); 2892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2893 // reader 2894 synchronized (mPackages) { 2895 PackageParser.Package p = mPackages.get(packageName); 2896 if (DEBUG_PACKAGE_INFO) 2897 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2898 if (p != null) { 2899 return generatePackageInfo(p, flags, userId); 2900 } 2901 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2902 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2903 } 2904 } 2905 return null; 2906 } 2907 2908 @Override 2909 public String[] currentToCanonicalPackageNames(String[] names) { 2910 String[] out = new String[names.length]; 2911 // reader 2912 synchronized (mPackages) { 2913 for (int i=names.length-1; i>=0; i--) { 2914 PackageSetting ps = mSettings.mPackages.get(names[i]); 2915 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2916 } 2917 } 2918 return out; 2919 } 2920 2921 @Override 2922 public String[] canonicalToCurrentPackageNames(String[] names) { 2923 String[] out = new String[names.length]; 2924 // reader 2925 synchronized (mPackages) { 2926 for (int i=names.length-1; i>=0; i--) { 2927 String cur = mSettings.mRenamedPackages.get(names[i]); 2928 out[i] = cur != null ? cur : names[i]; 2929 } 2930 } 2931 return out; 2932 } 2933 2934 @Override 2935 public int getPackageUid(String packageName, int flags, int userId) { 2936 if (!sUserManager.exists(userId)) return -1; 2937 flags = updateFlagsForPackage(flags, userId, packageName); 2938 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2939 2940 // reader 2941 synchronized (mPackages) { 2942 final PackageParser.Package p = mPackages.get(packageName); 2943 if (p != null && p.isMatch(flags)) { 2944 return UserHandle.getUid(userId, p.applicationInfo.uid); 2945 } 2946 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2947 final PackageSetting ps = mSettings.mPackages.get(packageName); 2948 if (ps != null && ps.isMatch(flags)) { 2949 return UserHandle.getUid(userId, ps.appId); 2950 } 2951 } 2952 } 2953 2954 return -1; 2955 } 2956 2957 @Override 2958 public int[] getPackageGids(String packageName, int flags, int userId) { 2959 if (!sUserManager.exists(userId)) return null; 2960 flags = updateFlagsForPackage(flags, userId, packageName); 2961 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2962 "getPackageGids"); 2963 2964 // reader 2965 synchronized (mPackages) { 2966 final PackageParser.Package p = mPackages.get(packageName); 2967 if (p != null && p.isMatch(flags)) { 2968 PackageSetting ps = (PackageSetting) p.mExtras; 2969 return ps.getPermissionsState().computeGids(userId); 2970 } 2971 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2972 final PackageSetting ps = mSettings.mPackages.get(packageName); 2973 if (ps != null && ps.isMatch(flags)) { 2974 return ps.getPermissionsState().computeGids(userId); 2975 } 2976 } 2977 } 2978 2979 return null; 2980 } 2981 2982 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 2983 if (bp.perm != null) { 2984 return PackageParser.generatePermissionInfo(bp.perm, flags); 2985 } 2986 PermissionInfo pi = new PermissionInfo(); 2987 pi.name = bp.name; 2988 pi.packageName = bp.sourcePackage; 2989 pi.nonLocalizedLabel = bp.name; 2990 pi.protectionLevel = bp.protectionLevel; 2991 return pi; 2992 } 2993 2994 @Override 2995 public PermissionInfo getPermissionInfo(String name, int flags) { 2996 // reader 2997 synchronized (mPackages) { 2998 final BasePermission p = mSettings.mPermissions.get(name); 2999 if (p != null) { 3000 return generatePermissionInfo(p, flags); 3001 } 3002 return null; 3003 } 3004 } 3005 3006 @Override 3007 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 3008 // reader 3009 synchronized (mPackages) { 3010 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3011 for (BasePermission p : mSettings.mPermissions.values()) { 3012 if (group == null) { 3013 if (p.perm == null || p.perm.info.group == null) { 3014 out.add(generatePermissionInfo(p, flags)); 3015 } 3016 } else { 3017 if (p.perm != null && group.equals(p.perm.info.group)) { 3018 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3019 } 3020 } 3021 } 3022 3023 if (out.size() > 0) { 3024 return out; 3025 } 3026 return mPermissionGroups.containsKey(group) ? out : null; 3027 } 3028 } 3029 3030 @Override 3031 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3032 // reader 3033 synchronized (mPackages) { 3034 return PackageParser.generatePermissionGroupInfo( 3035 mPermissionGroups.get(name), flags); 3036 } 3037 } 3038 3039 @Override 3040 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3041 // reader 3042 synchronized (mPackages) { 3043 final int N = mPermissionGroups.size(); 3044 ArrayList<PermissionGroupInfo> out 3045 = new ArrayList<PermissionGroupInfo>(N); 3046 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3047 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3048 } 3049 return out; 3050 } 3051 } 3052 3053 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3054 int userId) { 3055 if (!sUserManager.exists(userId)) return null; 3056 PackageSetting ps = mSettings.mPackages.get(packageName); 3057 if (ps != null) { 3058 if (ps.pkg == null) { 3059 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3060 flags, userId); 3061 if (pInfo != null) { 3062 return pInfo.applicationInfo; 3063 } 3064 return null; 3065 } 3066 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3067 ps.readUserState(userId), userId); 3068 } 3069 return null; 3070 } 3071 3072 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3073 int userId) { 3074 if (!sUserManager.exists(userId)) return null; 3075 PackageSetting ps = mSettings.mPackages.get(packageName); 3076 if (ps != null) { 3077 PackageParser.Package pkg = ps.pkg; 3078 if (pkg == null) { 3079 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3080 return null; 3081 } 3082 // Only data remains, so we aren't worried about code paths 3083 pkg = new PackageParser.Package(packageName); 3084 pkg.applicationInfo.packageName = packageName; 3085 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3086 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3087 pkg.applicationInfo.uid = ps.appId; 3088 pkg.applicationInfo.initForUser(userId); 3089 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3090 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3091 } 3092 return generatePackageInfo(pkg, flags, userId); 3093 } 3094 return null; 3095 } 3096 3097 @Override 3098 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3099 if (!sUserManager.exists(userId)) return null; 3100 flags = updateFlagsForApplication(flags, userId, packageName); 3101 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 3102 // writer 3103 synchronized (mPackages) { 3104 PackageParser.Package p = mPackages.get(packageName); 3105 if (DEBUG_PACKAGE_INFO) Log.v( 3106 TAG, "getApplicationInfo " + packageName 3107 + ": " + p); 3108 if (p != null) { 3109 PackageSetting ps = mSettings.mPackages.get(packageName); 3110 if (ps == null) return null; 3111 // Note: isEnabledLP() does not apply here - always return info 3112 return PackageParser.generateApplicationInfo( 3113 p, flags, ps.readUserState(userId), userId); 3114 } 3115 if ("android".equals(packageName)||"system".equals(packageName)) { 3116 return mAndroidApplication; 3117 } 3118 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3119 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3120 } 3121 } 3122 return null; 3123 } 3124 3125 @Override 3126 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3127 final IPackageDataObserver observer) { 3128 mContext.enforceCallingOrSelfPermission( 3129 android.Manifest.permission.CLEAR_APP_CACHE, null); 3130 // Queue up an async operation since clearing cache may take a little while. 3131 mHandler.post(new Runnable() { 3132 public void run() { 3133 mHandler.removeCallbacks(this); 3134 boolean success = true; 3135 synchronized (mInstallLock) { 3136 try { 3137 mInstaller.freeCache(volumeUuid, freeStorageSize); 3138 } catch (InstallerException e) { 3139 Slog.w(TAG, "Couldn't clear application caches: " + e); 3140 success = false; 3141 } 3142 } 3143 if (observer != null) { 3144 try { 3145 observer.onRemoveCompleted(null, success); 3146 } catch (RemoteException e) { 3147 Slog.w(TAG, "RemoveException when invoking call back"); 3148 } 3149 } 3150 } 3151 }); 3152 } 3153 3154 @Override 3155 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3156 final IntentSender pi) { 3157 mContext.enforceCallingOrSelfPermission( 3158 android.Manifest.permission.CLEAR_APP_CACHE, null); 3159 // Queue up an async operation since clearing cache may take a little while. 3160 mHandler.post(new Runnable() { 3161 public void run() { 3162 mHandler.removeCallbacks(this); 3163 boolean success = true; 3164 synchronized (mInstallLock) { 3165 try { 3166 mInstaller.freeCache(volumeUuid, freeStorageSize); 3167 } catch (InstallerException e) { 3168 Slog.w(TAG, "Couldn't clear application caches: " + e); 3169 success = false; 3170 } 3171 } 3172 if(pi != null) { 3173 try { 3174 // Callback via pending intent 3175 int code = success ? 1 : 0; 3176 pi.sendIntent(null, code, null, 3177 null, null); 3178 } catch (SendIntentException e1) { 3179 Slog.i(TAG, "Failed to send pending intent"); 3180 } 3181 } 3182 } 3183 }); 3184 } 3185 3186 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3187 synchronized (mInstallLock) { 3188 try { 3189 mInstaller.freeCache(volumeUuid, freeStorageSize); 3190 } catch (InstallerException e) { 3191 throw new IOException("Failed to free enough space", e); 3192 } 3193 } 3194 } 3195 3196 /** 3197 * Return if the user key is currently unlocked. 3198 */ 3199 private boolean isUserKeyUnlocked(int userId) { 3200 if (StorageManager.isFileBasedEncryptionEnabled()) { 3201 final IMountService mount = IMountService.Stub 3202 .asInterface(ServiceManager.getService("mount")); 3203 if (mount == null) { 3204 Slog.w(TAG, "Early during boot, assuming locked"); 3205 return false; 3206 } 3207 final long token = Binder.clearCallingIdentity(); 3208 try { 3209 return mount.isUserKeyUnlocked(userId); 3210 } catch (RemoteException e) { 3211 throw e.rethrowAsRuntimeException(); 3212 } finally { 3213 Binder.restoreCallingIdentity(token); 3214 } 3215 } else { 3216 return true; 3217 } 3218 } 3219 3220 /** 3221 * Update given flags based on encryption status of current user. 3222 */ 3223 private int updateFlags(int flags, int userId) { 3224 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3225 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3226 // Caller expressed an explicit opinion about what encryption 3227 // aware/unaware components they want to see, so fall through and 3228 // give them what they want 3229 } else { 3230 // Caller expressed no opinion, so match based on user state 3231 if (isUserKeyUnlocked(userId)) { 3232 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3233 } else { 3234 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3235 } 3236 } 3237 3238 // Safe mode means we should ignore any third-party apps 3239 if (mSafeMode) { 3240 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3241 } 3242 3243 return flags; 3244 } 3245 3246 /** 3247 * Update given flags when being used to request {@link PackageInfo}. 3248 */ 3249 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3250 boolean triaged = true; 3251 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3252 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3253 // Caller is asking for component details, so they'd better be 3254 // asking for specific encryption matching behavior, or be triaged 3255 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3256 | PackageManager.MATCH_ENCRYPTION_AWARE 3257 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3258 triaged = false; 3259 } 3260 } 3261 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3262 | PackageManager.MATCH_SYSTEM_ONLY 3263 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3264 triaged = false; 3265 } 3266 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3267 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3268 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3269 } 3270 return updateFlags(flags, userId); 3271 } 3272 3273 /** 3274 * Update given flags when being used to request {@link ApplicationInfo}. 3275 */ 3276 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3277 return updateFlagsForPackage(flags, userId, cookie); 3278 } 3279 3280 /** 3281 * Update given flags when being used to request {@link ComponentInfo}. 3282 */ 3283 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3284 if (cookie instanceof Intent) { 3285 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3286 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3287 } 3288 } 3289 3290 boolean triaged = true; 3291 // Caller is asking for component details, so they'd better be 3292 // asking for specific encryption matching behavior, or be triaged 3293 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3294 | PackageManager.MATCH_ENCRYPTION_AWARE 3295 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3296 triaged = false; 3297 } 3298 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3299 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3300 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3301 } 3302 return updateFlags(flags, userId); 3303 } 3304 3305 /** 3306 * Update given flags when being used to request {@link ResolveInfo}. 3307 */ 3308 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3309 return updateFlagsForComponent(flags, userId, cookie); 3310 } 3311 3312 @Override 3313 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3314 if (!sUserManager.exists(userId)) return null; 3315 flags = updateFlagsForComponent(flags, userId, component); 3316 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 3317 synchronized (mPackages) { 3318 PackageParser.Activity a = mActivities.mActivities.get(component); 3319 3320 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3321 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3322 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3323 if (ps == null) return null; 3324 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3325 userId); 3326 } 3327 if (mResolveComponentName.equals(component)) { 3328 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3329 new PackageUserState(), userId); 3330 } 3331 } 3332 return null; 3333 } 3334 3335 @Override 3336 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3337 String resolvedType) { 3338 synchronized (mPackages) { 3339 if (component.equals(mResolveComponentName)) { 3340 // The resolver supports EVERYTHING! 3341 return true; 3342 } 3343 PackageParser.Activity a = mActivities.mActivities.get(component); 3344 if (a == null) { 3345 return false; 3346 } 3347 for (int i=0; i<a.intents.size(); i++) { 3348 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3349 intent.getData(), intent.getCategories(), TAG) >= 0) { 3350 return true; 3351 } 3352 } 3353 return false; 3354 } 3355 } 3356 3357 @Override 3358 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 flags = updateFlagsForComponent(flags, userId, component); 3361 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 3362 synchronized (mPackages) { 3363 PackageParser.Activity a = mReceivers.mActivities.get(component); 3364 if (DEBUG_PACKAGE_INFO) Log.v( 3365 TAG, "getReceiverInfo " + component + ": " + a); 3366 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3367 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3368 if (ps == null) return null; 3369 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3370 userId); 3371 } 3372 } 3373 return null; 3374 } 3375 3376 @Override 3377 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3378 if (!sUserManager.exists(userId)) return null; 3379 flags = updateFlagsForComponent(flags, userId, component); 3380 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 3381 synchronized (mPackages) { 3382 PackageParser.Service s = mServices.mServices.get(component); 3383 if (DEBUG_PACKAGE_INFO) Log.v( 3384 TAG, "getServiceInfo " + component + ": " + s); 3385 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3386 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3387 if (ps == null) return null; 3388 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3389 userId); 3390 } 3391 } 3392 return null; 3393 } 3394 3395 @Override 3396 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3397 if (!sUserManager.exists(userId)) return null; 3398 flags = updateFlagsForComponent(flags, userId, component); 3399 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 3400 synchronized (mPackages) { 3401 PackageParser.Provider p = mProviders.mProviders.get(component); 3402 if (DEBUG_PACKAGE_INFO) Log.v( 3403 TAG, "getProviderInfo " + component + ": " + p); 3404 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3405 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3406 if (ps == null) return null; 3407 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3408 userId); 3409 } 3410 } 3411 return null; 3412 } 3413 3414 @Override 3415 public String[] getSystemSharedLibraryNames() { 3416 Set<String> libSet; 3417 synchronized (mPackages) { 3418 libSet = mSharedLibraries.keySet(); 3419 int size = libSet.size(); 3420 if (size > 0) { 3421 String[] libs = new String[size]; 3422 libSet.toArray(libs); 3423 return libs; 3424 } 3425 } 3426 return null; 3427 } 3428 3429 @Override 3430 public FeatureInfo[] getSystemAvailableFeatures() { 3431 Collection<FeatureInfo> featSet; 3432 synchronized (mPackages) { 3433 featSet = mAvailableFeatures.values(); 3434 int size = featSet.size(); 3435 if (size > 0) { 3436 FeatureInfo[] features = new FeatureInfo[size+1]; 3437 featSet.toArray(features); 3438 FeatureInfo fi = new FeatureInfo(); 3439 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3440 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3441 features[size] = fi; 3442 return features; 3443 } 3444 } 3445 return null; 3446 } 3447 3448 @Override 3449 public boolean hasSystemFeature(String name) { 3450 synchronized (mPackages) { 3451 return mAvailableFeatures.containsKey(name); 3452 } 3453 } 3454 3455 @Override 3456 public int checkPermission(String permName, String pkgName, int userId) { 3457 if (!sUserManager.exists(userId)) { 3458 return PackageManager.PERMISSION_DENIED; 3459 } 3460 3461 synchronized (mPackages) { 3462 final PackageParser.Package p = mPackages.get(pkgName); 3463 if (p != null && p.mExtras != null) { 3464 final PackageSetting ps = (PackageSetting) p.mExtras; 3465 final PermissionsState permissionsState = ps.getPermissionsState(); 3466 if (permissionsState.hasPermission(permName, userId)) { 3467 return PackageManager.PERMISSION_GRANTED; 3468 } 3469 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3470 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3471 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3472 return PackageManager.PERMISSION_GRANTED; 3473 } 3474 } 3475 } 3476 3477 return PackageManager.PERMISSION_DENIED; 3478 } 3479 3480 @Override 3481 public int checkUidPermission(String permName, int uid) { 3482 final int userId = UserHandle.getUserId(uid); 3483 3484 if (!sUserManager.exists(userId)) { 3485 return PackageManager.PERMISSION_DENIED; 3486 } 3487 3488 synchronized (mPackages) { 3489 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3490 if (obj != null) { 3491 final SettingBase ps = (SettingBase) obj; 3492 final PermissionsState permissionsState = ps.getPermissionsState(); 3493 if (permissionsState.hasPermission(permName, userId)) { 3494 return PackageManager.PERMISSION_GRANTED; 3495 } 3496 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3497 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3498 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3499 return PackageManager.PERMISSION_GRANTED; 3500 } 3501 } else { 3502 ArraySet<String> perms = mSystemPermissions.get(uid); 3503 if (perms != null) { 3504 if (perms.contains(permName)) { 3505 return PackageManager.PERMISSION_GRANTED; 3506 } 3507 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3508 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3509 return PackageManager.PERMISSION_GRANTED; 3510 } 3511 } 3512 } 3513 } 3514 3515 return PackageManager.PERMISSION_DENIED; 3516 } 3517 3518 @Override 3519 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3520 if (UserHandle.getCallingUserId() != userId) { 3521 mContext.enforceCallingPermission( 3522 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3523 "isPermissionRevokedByPolicy for user " + userId); 3524 } 3525 3526 if (checkPermission(permission, packageName, userId) 3527 == PackageManager.PERMISSION_GRANTED) { 3528 return false; 3529 } 3530 3531 final long identity = Binder.clearCallingIdentity(); 3532 try { 3533 final int flags = getPermissionFlags(permission, packageName, userId); 3534 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3535 } finally { 3536 Binder.restoreCallingIdentity(identity); 3537 } 3538 } 3539 3540 @Override 3541 public String getPermissionControllerPackageName() { 3542 synchronized (mPackages) { 3543 return mRequiredInstallerPackage; 3544 } 3545 } 3546 3547 /** 3548 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3549 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3550 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3551 * @param message the message to log on security exception 3552 */ 3553 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3554 boolean checkShell, String message) { 3555 if (userId < 0) { 3556 throw new IllegalArgumentException("Invalid userId " + userId); 3557 } 3558 if (checkShell) { 3559 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3560 } 3561 if (userId == UserHandle.getUserId(callingUid)) return; 3562 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3563 if (requireFullPermission) { 3564 mContext.enforceCallingOrSelfPermission( 3565 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3566 } else { 3567 try { 3568 mContext.enforceCallingOrSelfPermission( 3569 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3570 } catch (SecurityException se) { 3571 mContext.enforceCallingOrSelfPermission( 3572 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3573 } 3574 } 3575 } 3576 } 3577 3578 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3579 if (callingUid == Process.SHELL_UID) { 3580 if (userHandle >= 0 3581 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3582 throw new SecurityException("Shell does not have permission to access user " 3583 + userHandle); 3584 } else if (userHandle < 0) { 3585 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3586 + Debug.getCallers(3)); 3587 } 3588 } 3589 } 3590 3591 private BasePermission findPermissionTreeLP(String permName) { 3592 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3593 if (permName.startsWith(bp.name) && 3594 permName.length() > bp.name.length() && 3595 permName.charAt(bp.name.length()) == '.') { 3596 return bp; 3597 } 3598 } 3599 return null; 3600 } 3601 3602 private BasePermission checkPermissionTreeLP(String permName) { 3603 if (permName != null) { 3604 BasePermission bp = findPermissionTreeLP(permName); 3605 if (bp != null) { 3606 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3607 return bp; 3608 } 3609 throw new SecurityException("Calling uid " 3610 + Binder.getCallingUid() 3611 + " is not allowed to add to permission tree " 3612 + bp.name + " owned by uid " + bp.uid); 3613 } 3614 } 3615 throw new SecurityException("No permission tree found for " + permName); 3616 } 3617 3618 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3619 if (s1 == null) { 3620 return s2 == null; 3621 } 3622 if (s2 == null) { 3623 return false; 3624 } 3625 if (s1.getClass() != s2.getClass()) { 3626 return false; 3627 } 3628 return s1.equals(s2); 3629 } 3630 3631 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3632 if (pi1.icon != pi2.icon) return false; 3633 if (pi1.logo != pi2.logo) return false; 3634 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3635 if (!compareStrings(pi1.name, pi2.name)) return false; 3636 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3637 // We'll take care of setting this one. 3638 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3639 // These are not currently stored in settings. 3640 //if (!compareStrings(pi1.group, pi2.group)) return false; 3641 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3642 //if (pi1.labelRes != pi2.labelRes) return false; 3643 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3644 return true; 3645 } 3646 3647 int permissionInfoFootprint(PermissionInfo info) { 3648 int size = info.name.length(); 3649 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3650 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3651 return size; 3652 } 3653 3654 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3655 int size = 0; 3656 for (BasePermission perm : mSettings.mPermissions.values()) { 3657 if (perm.uid == tree.uid) { 3658 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3659 } 3660 } 3661 return size; 3662 } 3663 3664 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3665 // We calculate the max size of permissions defined by this uid and throw 3666 // if that plus the size of 'info' would exceed our stated maximum. 3667 if (tree.uid != Process.SYSTEM_UID) { 3668 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3669 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3670 throw new SecurityException("Permission tree size cap exceeded"); 3671 } 3672 } 3673 } 3674 3675 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3676 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3677 throw new SecurityException("Label must be specified in permission"); 3678 } 3679 BasePermission tree = checkPermissionTreeLP(info.name); 3680 BasePermission bp = mSettings.mPermissions.get(info.name); 3681 boolean added = bp == null; 3682 boolean changed = true; 3683 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3684 if (added) { 3685 enforcePermissionCapLocked(info, tree); 3686 bp = new BasePermission(info.name, tree.sourcePackage, 3687 BasePermission.TYPE_DYNAMIC); 3688 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3689 throw new SecurityException( 3690 "Not allowed to modify non-dynamic permission " 3691 + info.name); 3692 } else { 3693 if (bp.protectionLevel == fixedLevel 3694 && bp.perm.owner.equals(tree.perm.owner) 3695 && bp.uid == tree.uid 3696 && comparePermissionInfos(bp.perm.info, info)) { 3697 changed = false; 3698 } 3699 } 3700 bp.protectionLevel = fixedLevel; 3701 info = new PermissionInfo(info); 3702 info.protectionLevel = fixedLevel; 3703 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3704 bp.perm.info.packageName = tree.perm.info.packageName; 3705 bp.uid = tree.uid; 3706 if (added) { 3707 mSettings.mPermissions.put(info.name, bp); 3708 } 3709 if (changed) { 3710 if (!async) { 3711 mSettings.writeLPr(); 3712 } else { 3713 scheduleWriteSettingsLocked(); 3714 } 3715 } 3716 return added; 3717 } 3718 3719 @Override 3720 public boolean addPermission(PermissionInfo info) { 3721 synchronized (mPackages) { 3722 return addPermissionLocked(info, false); 3723 } 3724 } 3725 3726 @Override 3727 public boolean addPermissionAsync(PermissionInfo info) { 3728 synchronized (mPackages) { 3729 return addPermissionLocked(info, true); 3730 } 3731 } 3732 3733 @Override 3734 public void removePermission(String name) { 3735 synchronized (mPackages) { 3736 checkPermissionTreeLP(name); 3737 BasePermission bp = mSettings.mPermissions.get(name); 3738 if (bp != null) { 3739 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3740 throw new SecurityException( 3741 "Not allowed to modify non-dynamic permission " 3742 + name); 3743 } 3744 mSettings.mPermissions.remove(name); 3745 mSettings.writeLPr(); 3746 } 3747 } 3748 } 3749 3750 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3751 BasePermission bp) { 3752 int index = pkg.requestedPermissions.indexOf(bp.name); 3753 if (index == -1) { 3754 throw new SecurityException("Package " + pkg.packageName 3755 + " has not requested permission " + bp.name); 3756 } 3757 if (!bp.isRuntime() && !bp.isDevelopment()) { 3758 throw new SecurityException("Permission " + bp.name 3759 + " is not a changeable permission type"); 3760 } 3761 } 3762 3763 @Override 3764 public void grantRuntimePermission(String packageName, String name, final int userId) { 3765 if (!sUserManager.exists(userId)) { 3766 Log.e(TAG, "No such user:" + userId); 3767 return; 3768 } 3769 3770 mContext.enforceCallingOrSelfPermission( 3771 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3772 "grantRuntimePermission"); 3773 3774 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3775 "grantRuntimePermission"); 3776 3777 final int uid; 3778 final SettingBase sb; 3779 3780 synchronized (mPackages) { 3781 final PackageParser.Package pkg = mPackages.get(packageName); 3782 if (pkg == null) { 3783 throw new IllegalArgumentException("Unknown package: " + packageName); 3784 } 3785 3786 final BasePermission bp = mSettings.mPermissions.get(name); 3787 if (bp == null) { 3788 throw new IllegalArgumentException("Unknown permission: " + name); 3789 } 3790 3791 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3792 3793 // If a permission review is required for legacy apps we represent 3794 // their permissions as always granted runtime ones since we need 3795 // to keep the review required permission flag per user while an 3796 // install permission's state is shared across all users. 3797 if (Build.PERMISSIONS_REVIEW_REQUIRED 3798 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3799 && bp.isRuntime()) { 3800 return; 3801 } 3802 3803 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3804 sb = (SettingBase) pkg.mExtras; 3805 if (sb == null) { 3806 throw new IllegalArgumentException("Unknown package: " + packageName); 3807 } 3808 3809 final PermissionsState permissionsState = sb.getPermissionsState(); 3810 3811 final int flags = permissionsState.getPermissionFlags(name, userId); 3812 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3813 throw new SecurityException("Cannot grant system fixed permission " 3814 + name + " for package " + packageName); 3815 } 3816 3817 if (bp.isDevelopment()) { 3818 // Development permissions must be handled specially, since they are not 3819 // normal runtime permissions. For now they apply to all users. 3820 if (permissionsState.grantInstallPermission(bp) != 3821 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3822 scheduleWriteSettingsLocked(); 3823 } 3824 return; 3825 } 3826 3827 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3828 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3829 return; 3830 } 3831 3832 final int result = permissionsState.grantRuntimePermission(bp, userId); 3833 switch (result) { 3834 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3835 return; 3836 } 3837 3838 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3839 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3840 mHandler.post(new Runnable() { 3841 @Override 3842 public void run() { 3843 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3844 } 3845 }); 3846 } 3847 break; 3848 } 3849 3850 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3851 3852 // Not critical if that is lost - app has to request again. 3853 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3854 } 3855 3856 // Only need to do this if user is initialized. Otherwise it's a new user 3857 // and there are no processes running as the user yet and there's no need 3858 // to make an expensive call to remount processes for the changed permissions. 3859 if (READ_EXTERNAL_STORAGE.equals(name) 3860 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3861 final long token = Binder.clearCallingIdentity(); 3862 try { 3863 if (sUserManager.isInitialized(userId)) { 3864 MountServiceInternal mountServiceInternal = LocalServices.getService( 3865 MountServiceInternal.class); 3866 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3867 } 3868 } finally { 3869 Binder.restoreCallingIdentity(token); 3870 } 3871 } 3872 } 3873 3874 @Override 3875 public void revokeRuntimePermission(String packageName, String name, int userId) { 3876 if (!sUserManager.exists(userId)) { 3877 Log.e(TAG, "No such user:" + userId); 3878 return; 3879 } 3880 3881 mContext.enforceCallingOrSelfPermission( 3882 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3883 "revokeRuntimePermission"); 3884 3885 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3886 "revokeRuntimePermission"); 3887 3888 final int appId; 3889 3890 synchronized (mPackages) { 3891 final PackageParser.Package pkg = mPackages.get(packageName); 3892 if (pkg == null) { 3893 throw new IllegalArgumentException("Unknown package: " + packageName); 3894 } 3895 3896 final BasePermission bp = mSettings.mPermissions.get(name); 3897 if (bp == null) { 3898 throw new IllegalArgumentException("Unknown permission: " + name); 3899 } 3900 3901 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3902 3903 // If a permission review is required for legacy apps we represent 3904 // their permissions as always granted runtime ones since we need 3905 // to keep the review required permission flag per user while an 3906 // install permission's state is shared across all users. 3907 if (Build.PERMISSIONS_REVIEW_REQUIRED 3908 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3909 && bp.isRuntime()) { 3910 return; 3911 } 3912 3913 SettingBase sb = (SettingBase) pkg.mExtras; 3914 if (sb == null) { 3915 throw new IllegalArgumentException("Unknown package: " + packageName); 3916 } 3917 3918 final PermissionsState permissionsState = sb.getPermissionsState(); 3919 3920 final int flags = permissionsState.getPermissionFlags(name, userId); 3921 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3922 throw new SecurityException("Cannot revoke system fixed permission " 3923 + name + " for package " + packageName); 3924 } 3925 3926 if (bp.isDevelopment()) { 3927 // Development permissions must be handled specially, since they are not 3928 // normal runtime permissions. For now they apply to all users. 3929 if (permissionsState.revokeInstallPermission(bp) != 3930 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3931 scheduleWriteSettingsLocked(); 3932 } 3933 return; 3934 } 3935 3936 if (permissionsState.revokeRuntimePermission(bp, userId) == 3937 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3938 return; 3939 } 3940 3941 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3942 3943 // Critical, after this call app should never have the permission. 3944 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3945 3946 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3947 } 3948 3949 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3950 } 3951 3952 @Override 3953 public void resetRuntimePermissions() { 3954 mContext.enforceCallingOrSelfPermission( 3955 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3956 "revokeRuntimePermission"); 3957 3958 int callingUid = Binder.getCallingUid(); 3959 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3960 mContext.enforceCallingOrSelfPermission( 3961 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3962 "resetRuntimePermissions"); 3963 } 3964 3965 synchronized (mPackages) { 3966 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 3967 for (int userId : UserManagerService.getInstance().getUserIds()) { 3968 final int packageCount = mPackages.size(); 3969 for (int i = 0; i < packageCount; i++) { 3970 PackageParser.Package pkg = mPackages.valueAt(i); 3971 if (!(pkg.mExtras instanceof PackageSetting)) { 3972 continue; 3973 } 3974 PackageSetting ps = (PackageSetting) pkg.mExtras; 3975 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 3976 } 3977 } 3978 } 3979 } 3980 3981 @Override 3982 public int getPermissionFlags(String name, String packageName, int userId) { 3983 if (!sUserManager.exists(userId)) { 3984 return 0; 3985 } 3986 3987 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 3988 3989 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3990 "getPermissionFlags"); 3991 3992 synchronized (mPackages) { 3993 final PackageParser.Package pkg = mPackages.get(packageName); 3994 if (pkg == null) { 3995 throw new IllegalArgumentException("Unknown package: " + packageName); 3996 } 3997 3998 final BasePermission bp = mSettings.mPermissions.get(name); 3999 if (bp == null) { 4000 throw new IllegalArgumentException("Unknown permission: " + name); 4001 } 4002 4003 SettingBase sb = (SettingBase) pkg.mExtras; 4004 if (sb == null) { 4005 throw new IllegalArgumentException("Unknown package: " + packageName); 4006 } 4007 4008 PermissionsState permissionsState = sb.getPermissionsState(); 4009 return permissionsState.getPermissionFlags(name, userId); 4010 } 4011 } 4012 4013 @Override 4014 public void updatePermissionFlags(String name, String packageName, int flagMask, 4015 int flagValues, int userId) { 4016 if (!sUserManager.exists(userId)) { 4017 return; 4018 } 4019 4020 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4021 4022 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4023 "updatePermissionFlags"); 4024 4025 // Only the system can change these flags and nothing else. 4026 if (getCallingUid() != Process.SYSTEM_UID) { 4027 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4028 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4029 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4030 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4031 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4032 } 4033 4034 synchronized (mPackages) { 4035 final PackageParser.Package pkg = mPackages.get(packageName); 4036 if (pkg == null) { 4037 throw new IllegalArgumentException("Unknown package: " + packageName); 4038 } 4039 4040 final BasePermission bp = mSettings.mPermissions.get(name); 4041 if (bp == null) { 4042 throw new IllegalArgumentException("Unknown permission: " + name); 4043 } 4044 4045 SettingBase sb = (SettingBase) pkg.mExtras; 4046 if (sb == null) { 4047 throw new IllegalArgumentException("Unknown package: " + packageName); 4048 } 4049 4050 PermissionsState permissionsState = sb.getPermissionsState(); 4051 4052 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4053 4054 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4055 // Install and runtime permissions are stored in different places, 4056 // so figure out what permission changed and persist the change. 4057 if (permissionsState.getInstallPermissionState(name) != null) { 4058 scheduleWriteSettingsLocked(); 4059 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4060 || hadState) { 4061 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4062 } 4063 } 4064 } 4065 } 4066 4067 /** 4068 * Update the permission flags for all packages and runtime permissions of a user in order 4069 * to allow device or profile owner to remove POLICY_FIXED. 4070 */ 4071 @Override 4072 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4073 if (!sUserManager.exists(userId)) { 4074 return; 4075 } 4076 4077 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4078 4079 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 4080 "updatePermissionFlagsForAllApps"); 4081 4082 // Only the system can change system fixed flags. 4083 if (getCallingUid() != Process.SYSTEM_UID) { 4084 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4085 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4086 } 4087 4088 synchronized (mPackages) { 4089 boolean changed = false; 4090 final int packageCount = mPackages.size(); 4091 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4092 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4093 SettingBase sb = (SettingBase) pkg.mExtras; 4094 if (sb == null) { 4095 continue; 4096 } 4097 PermissionsState permissionsState = sb.getPermissionsState(); 4098 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4099 userId, flagMask, flagValues); 4100 } 4101 if (changed) { 4102 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4103 } 4104 } 4105 } 4106 4107 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4108 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4109 != PackageManager.PERMISSION_GRANTED 4110 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4111 != PackageManager.PERMISSION_GRANTED) { 4112 throw new SecurityException(message + " requires " 4113 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4114 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4115 } 4116 } 4117 4118 @Override 4119 public boolean shouldShowRequestPermissionRationale(String permissionName, 4120 String packageName, int userId) { 4121 if (UserHandle.getCallingUserId() != userId) { 4122 mContext.enforceCallingPermission( 4123 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4124 "canShowRequestPermissionRationale for user " + userId); 4125 } 4126 4127 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4128 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4129 return false; 4130 } 4131 4132 if (checkPermission(permissionName, packageName, userId) 4133 == PackageManager.PERMISSION_GRANTED) { 4134 return false; 4135 } 4136 4137 final int flags; 4138 4139 final long identity = Binder.clearCallingIdentity(); 4140 try { 4141 flags = getPermissionFlags(permissionName, 4142 packageName, userId); 4143 } finally { 4144 Binder.restoreCallingIdentity(identity); 4145 } 4146 4147 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4148 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4149 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4150 4151 if ((flags & fixedFlags) != 0) { 4152 return false; 4153 } 4154 4155 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4156 } 4157 4158 @Override 4159 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4160 mContext.enforceCallingOrSelfPermission( 4161 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4162 "addOnPermissionsChangeListener"); 4163 4164 synchronized (mPackages) { 4165 mOnPermissionChangeListeners.addListenerLocked(listener); 4166 } 4167 } 4168 4169 @Override 4170 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4171 synchronized (mPackages) { 4172 mOnPermissionChangeListeners.removeListenerLocked(listener); 4173 } 4174 } 4175 4176 @Override 4177 public boolean isProtectedBroadcast(String actionName) { 4178 synchronized (mPackages) { 4179 if (mProtectedBroadcasts.contains(actionName)) { 4180 return true; 4181 } else if (actionName != null) { 4182 // TODO: remove these terrible hacks 4183 if (actionName.startsWith("android.net.netmon.lingerExpired") 4184 || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) { 4185 return true; 4186 } 4187 } 4188 } 4189 return false; 4190 } 4191 4192 @Override 4193 public int checkSignatures(String pkg1, String pkg2) { 4194 synchronized (mPackages) { 4195 final PackageParser.Package p1 = mPackages.get(pkg1); 4196 final PackageParser.Package p2 = mPackages.get(pkg2); 4197 if (p1 == null || p1.mExtras == null 4198 || p2 == null || p2.mExtras == null) { 4199 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4200 } 4201 return compareSignatures(p1.mSignatures, p2.mSignatures); 4202 } 4203 } 4204 4205 @Override 4206 public int checkUidSignatures(int uid1, int uid2) { 4207 // Map to base uids. 4208 uid1 = UserHandle.getAppId(uid1); 4209 uid2 = UserHandle.getAppId(uid2); 4210 // reader 4211 synchronized (mPackages) { 4212 Signature[] s1; 4213 Signature[] s2; 4214 Object obj = mSettings.getUserIdLPr(uid1); 4215 if (obj != null) { 4216 if (obj instanceof SharedUserSetting) { 4217 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4218 } else if (obj instanceof PackageSetting) { 4219 s1 = ((PackageSetting)obj).signatures.mSignatures; 4220 } else { 4221 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4222 } 4223 } else { 4224 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4225 } 4226 obj = mSettings.getUserIdLPr(uid2); 4227 if (obj != null) { 4228 if (obj instanceof SharedUserSetting) { 4229 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4230 } else if (obj instanceof PackageSetting) { 4231 s2 = ((PackageSetting)obj).signatures.mSignatures; 4232 } else { 4233 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4234 } 4235 } else { 4236 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4237 } 4238 return compareSignatures(s1, s2); 4239 } 4240 } 4241 4242 private void killUid(int appId, int userId, String reason) { 4243 final long identity = Binder.clearCallingIdentity(); 4244 try { 4245 IActivityManager am = ActivityManagerNative.getDefault(); 4246 if (am != null) { 4247 try { 4248 am.killUid(appId, userId, reason); 4249 } catch (RemoteException e) { 4250 /* ignore - same process */ 4251 } 4252 } 4253 } finally { 4254 Binder.restoreCallingIdentity(identity); 4255 } 4256 } 4257 4258 /** 4259 * Compares two sets of signatures. Returns: 4260 * <br /> 4261 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4262 * <br /> 4263 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4264 * <br /> 4265 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4266 * <br /> 4267 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4268 * <br /> 4269 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4270 */ 4271 static int compareSignatures(Signature[] s1, Signature[] s2) { 4272 if (s1 == null) { 4273 return s2 == null 4274 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4275 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4276 } 4277 4278 if (s2 == null) { 4279 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4280 } 4281 4282 if (s1.length != s2.length) { 4283 return PackageManager.SIGNATURE_NO_MATCH; 4284 } 4285 4286 // Since both signature sets are of size 1, we can compare without HashSets. 4287 if (s1.length == 1) { 4288 return s1[0].equals(s2[0]) ? 4289 PackageManager.SIGNATURE_MATCH : 4290 PackageManager.SIGNATURE_NO_MATCH; 4291 } 4292 4293 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4294 for (Signature sig : s1) { 4295 set1.add(sig); 4296 } 4297 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4298 for (Signature sig : s2) { 4299 set2.add(sig); 4300 } 4301 // Make sure s2 contains all signatures in s1. 4302 if (set1.equals(set2)) { 4303 return PackageManager.SIGNATURE_MATCH; 4304 } 4305 return PackageManager.SIGNATURE_NO_MATCH; 4306 } 4307 4308 /** 4309 * If the database version for this type of package (internal storage or 4310 * external storage) is less than the version where package signatures 4311 * were updated, return true. 4312 */ 4313 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4314 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4315 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4316 } 4317 4318 /** 4319 * Used for backward compatibility to make sure any packages with 4320 * certificate chains get upgraded to the new style. {@code existingSigs} 4321 * will be in the old format (since they were stored on disk from before the 4322 * system upgrade) and {@code scannedSigs} will be in the newer format. 4323 */ 4324 private int compareSignaturesCompat(PackageSignatures existingSigs, 4325 PackageParser.Package scannedPkg) { 4326 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4327 return PackageManager.SIGNATURE_NO_MATCH; 4328 } 4329 4330 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4331 for (Signature sig : existingSigs.mSignatures) { 4332 existingSet.add(sig); 4333 } 4334 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4335 for (Signature sig : scannedPkg.mSignatures) { 4336 try { 4337 Signature[] chainSignatures = sig.getChainSignatures(); 4338 for (Signature chainSig : chainSignatures) { 4339 scannedCompatSet.add(chainSig); 4340 } 4341 } catch (CertificateEncodingException e) { 4342 scannedCompatSet.add(sig); 4343 } 4344 } 4345 /* 4346 * Make sure the expanded scanned set contains all signatures in the 4347 * existing one. 4348 */ 4349 if (scannedCompatSet.equals(existingSet)) { 4350 // Migrate the old signatures to the new scheme. 4351 existingSigs.assignSignatures(scannedPkg.mSignatures); 4352 // The new KeySets will be re-added later in the scanning process. 4353 synchronized (mPackages) { 4354 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4355 } 4356 return PackageManager.SIGNATURE_MATCH; 4357 } 4358 return PackageManager.SIGNATURE_NO_MATCH; 4359 } 4360 4361 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4362 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4363 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4364 } 4365 4366 private int compareSignaturesRecover(PackageSignatures existingSigs, 4367 PackageParser.Package scannedPkg) { 4368 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4369 return PackageManager.SIGNATURE_NO_MATCH; 4370 } 4371 4372 String msg = null; 4373 try { 4374 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4375 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4376 + scannedPkg.packageName); 4377 return PackageManager.SIGNATURE_MATCH; 4378 } 4379 } catch (CertificateException e) { 4380 msg = e.getMessage(); 4381 } 4382 4383 logCriticalInfo(Log.INFO, 4384 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4385 return PackageManager.SIGNATURE_NO_MATCH; 4386 } 4387 4388 @Override 4389 public String[] getPackagesForUid(int uid) { 4390 uid = UserHandle.getAppId(uid); 4391 // reader 4392 synchronized (mPackages) { 4393 Object obj = mSettings.getUserIdLPr(uid); 4394 if (obj instanceof SharedUserSetting) { 4395 final SharedUserSetting sus = (SharedUserSetting) obj; 4396 final int N = sus.packages.size(); 4397 final String[] res = new String[N]; 4398 final Iterator<PackageSetting> it = sus.packages.iterator(); 4399 int i = 0; 4400 while (it.hasNext()) { 4401 res[i++] = it.next().name; 4402 } 4403 return res; 4404 } else if (obj instanceof PackageSetting) { 4405 final PackageSetting ps = (PackageSetting) obj; 4406 return new String[] { ps.name }; 4407 } 4408 } 4409 return null; 4410 } 4411 4412 @Override 4413 public String getNameForUid(int uid) { 4414 // reader 4415 synchronized (mPackages) { 4416 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4417 if (obj instanceof SharedUserSetting) { 4418 final SharedUserSetting sus = (SharedUserSetting) obj; 4419 return sus.name + ":" + sus.userId; 4420 } else if (obj instanceof PackageSetting) { 4421 final PackageSetting ps = (PackageSetting) obj; 4422 return ps.name; 4423 } 4424 } 4425 return null; 4426 } 4427 4428 @Override 4429 public int getUidForSharedUser(String sharedUserName) { 4430 if(sharedUserName == null) { 4431 return -1; 4432 } 4433 // reader 4434 synchronized (mPackages) { 4435 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4436 if (suid == null) { 4437 return -1; 4438 } 4439 return suid.userId; 4440 } 4441 } 4442 4443 @Override 4444 public int getFlagsForUid(int uid) { 4445 synchronized (mPackages) { 4446 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4447 if (obj instanceof SharedUserSetting) { 4448 final SharedUserSetting sus = (SharedUserSetting) obj; 4449 return sus.pkgFlags; 4450 } else if (obj instanceof PackageSetting) { 4451 final PackageSetting ps = (PackageSetting) obj; 4452 return ps.pkgFlags; 4453 } 4454 } 4455 return 0; 4456 } 4457 4458 @Override 4459 public int getPrivateFlagsForUid(int uid) { 4460 synchronized (mPackages) { 4461 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4462 if (obj instanceof SharedUserSetting) { 4463 final SharedUserSetting sus = (SharedUserSetting) obj; 4464 return sus.pkgPrivateFlags; 4465 } else if (obj instanceof PackageSetting) { 4466 final PackageSetting ps = (PackageSetting) obj; 4467 return ps.pkgPrivateFlags; 4468 } 4469 } 4470 return 0; 4471 } 4472 4473 @Override 4474 public boolean isUidPrivileged(int uid) { 4475 uid = UserHandle.getAppId(uid); 4476 // reader 4477 synchronized (mPackages) { 4478 Object obj = mSettings.getUserIdLPr(uid); 4479 if (obj instanceof SharedUserSetting) { 4480 final SharedUserSetting sus = (SharedUserSetting) obj; 4481 final Iterator<PackageSetting> it = sus.packages.iterator(); 4482 while (it.hasNext()) { 4483 if (it.next().isPrivileged()) { 4484 return true; 4485 } 4486 } 4487 } else if (obj instanceof PackageSetting) { 4488 final PackageSetting ps = (PackageSetting) obj; 4489 return ps.isPrivileged(); 4490 } 4491 } 4492 return false; 4493 } 4494 4495 @Override 4496 public String[] getAppOpPermissionPackages(String permissionName) { 4497 synchronized (mPackages) { 4498 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4499 if (pkgs == null) { 4500 return null; 4501 } 4502 return pkgs.toArray(new String[pkgs.size()]); 4503 } 4504 } 4505 4506 @Override 4507 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4508 int flags, int userId) { 4509 if (!sUserManager.exists(userId)) return null; 4510 flags = updateFlagsForResolve(flags, userId, intent); 4511 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 4512 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4513 final ResolveInfo bestChoice = 4514 chooseBestActivity(intent, resolvedType, flags, query, userId); 4515 4516 if (isEphemeralAllowed(intent, query, userId)) { 4517 final EphemeralResolveInfo ai = 4518 getEphemeralResolveInfo(intent, resolvedType, userId); 4519 if (ai != null) { 4520 if (DEBUG_EPHEMERAL) { 4521 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4522 } 4523 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4524 bestChoice.ephemeralResolveInfo = ai; 4525 } 4526 } 4527 return bestChoice; 4528 } 4529 4530 @Override 4531 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4532 IntentFilter filter, int match, ComponentName activity) { 4533 final int userId = UserHandle.getCallingUserId(); 4534 if (DEBUG_PREFERRED) { 4535 Log.v(TAG, "setLastChosenActivity intent=" + intent 4536 + " resolvedType=" + resolvedType 4537 + " flags=" + flags 4538 + " filter=" + filter 4539 + " match=" + match 4540 + " activity=" + activity); 4541 filter.dump(new PrintStreamPrinter(System.out), " "); 4542 } 4543 intent.setComponent(null); 4544 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4545 // Find any earlier preferred or last chosen entries and nuke them 4546 findPreferredActivity(intent, resolvedType, 4547 flags, query, 0, false, true, false, userId); 4548 // Add the new activity as the last chosen for this filter 4549 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4550 "Setting last chosen"); 4551 } 4552 4553 @Override 4554 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4555 final int userId = UserHandle.getCallingUserId(); 4556 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4557 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 4558 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4559 false, false, false, userId); 4560 } 4561 4562 4563 private boolean isEphemeralAllowed( 4564 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4565 // Short circuit and return early if possible. 4566 if (DISABLE_EPHEMERAL_APPS) { 4567 return false; 4568 } 4569 final int callingUser = UserHandle.getCallingUserId(); 4570 if (callingUser != UserHandle.USER_SYSTEM) { 4571 return false; 4572 } 4573 if (mEphemeralResolverConnection == null) { 4574 return false; 4575 } 4576 if (intent.getComponent() != null) { 4577 return false; 4578 } 4579 if (intent.getPackage() != null) { 4580 return false; 4581 } 4582 final boolean isWebUri = hasWebURI(intent); 4583 if (!isWebUri) { 4584 return false; 4585 } 4586 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4587 synchronized (mPackages) { 4588 final int count = resolvedActivites.size(); 4589 for (int n = 0; n < count; n++) { 4590 ResolveInfo info = resolvedActivites.get(n); 4591 String packageName = info.activityInfo.packageName; 4592 PackageSetting ps = mSettings.mPackages.get(packageName); 4593 if (ps != null) { 4594 // Try to get the status from User settings first 4595 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4596 int status = (int) (packedStatus >> 32); 4597 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4598 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4599 if (DEBUG_EPHEMERAL) { 4600 Slog.v(TAG, "DENY ephemeral apps;" 4601 + " pkg: " + packageName + ", status: " + status); 4602 } 4603 return false; 4604 } 4605 } 4606 } 4607 } 4608 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4609 return true; 4610 } 4611 4612 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4613 int userId) { 4614 MessageDigest digest = null; 4615 try { 4616 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4617 } catch (NoSuchAlgorithmException e) { 4618 // If we can't create a digest, ignore ephemeral apps. 4619 return null; 4620 } 4621 4622 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4623 final byte[] digestBytes = digest.digest(hostBytes); 4624 int shaPrefix = 4625 digestBytes[0] << 24 4626 | digestBytes[1] << 16 4627 | digestBytes[2] << 8 4628 | digestBytes[3] << 0; 4629 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4630 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4631 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4632 // No hash prefix match; there are no ephemeral apps for this domain. 4633 return null; 4634 } 4635 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4636 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4637 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4638 continue; 4639 } 4640 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4641 // No filters; this should never happen. 4642 if (filters.isEmpty()) { 4643 continue; 4644 } 4645 // We have a domain match; resolve the filters to see if anything matches. 4646 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4647 for (int j = filters.size() - 1; j >= 0; --j) { 4648 final EphemeralResolveIntentInfo intentInfo = 4649 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4650 ephemeralResolver.addFilter(intentInfo); 4651 } 4652 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4653 intent, resolvedType, false /*defaultOnly*/, userId); 4654 if (!matchedResolveInfoList.isEmpty()) { 4655 return matchedResolveInfoList.get(0); 4656 } 4657 } 4658 // Hash or filter mis-match; no ephemeral apps for this domain. 4659 return null; 4660 } 4661 4662 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4663 int flags, List<ResolveInfo> query, int userId) { 4664 if (query != null) { 4665 final int N = query.size(); 4666 if (N == 1) { 4667 return query.get(0); 4668 } else if (N > 1) { 4669 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4670 // If there is more than one activity with the same priority, 4671 // then let the user decide between them. 4672 ResolveInfo r0 = query.get(0); 4673 ResolveInfo r1 = query.get(1); 4674 if (DEBUG_INTENT_MATCHING || debug) { 4675 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4676 + r1.activityInfo.name + "=" + r1.priority); 4677 } 4678 // If the first activity has a higher priority, or a different 4679 // default, then it is always desirable to pick it. 4680 if (r0.priority != r1.priority 4681 || r0.preferredOrder != r1.preferredOrder 4682 || r0.isDefault != r1.isDefault) { 4683 return query.get(0); 4684 } 4685 // If we have saved a preference for a preferred activity for 4686 // this Intent, use that. 4687 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4688 flags, query, r0.priority, true, false, debug, userId); 4689 if (ri != null) { 4690 return ri; 4691 } 4692 ri = new ResolveInfo(mResolveInfo); 4693 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4694 ri.activityInfo.applicationInfo = new ApplicationInfo( 4695 ri.activityInfo.applicationInfo); 4696 if (userId != 0) { 4697 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4698 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4699 } 4700 // Make sure that the resolver is displayable in car mode 4701 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4702 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4703 return ri; 4704 } 4705 } 4706 return null; 4707 } 4708 4709 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4710 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4711 final int N = query.size(); 4712 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4713 .get(userId); 4714 // Get the list of persistent preferred activities that handle the intent 4715 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4716 List<PersistentPreferredActivity> pprefs = ppir != null 4717 ? ppir.queryIntent(intent, resolvedType, 4718 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4719 : null; 4720 if (pprefs != null && pprefs.size() > 0) { 4721 final int M = pprefs.size(); 4722 for (int i=0; i<M; i++) { 4723 final PersistentPreferredActivity ppa = pprefs.get(i); 4724 if (DEBUG_PREFERRED || debug) { 4725 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4726 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4727 + "\n component=" + ppa.mComponent); 4728 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4729 } 4730 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4731 flags | MATCH_DISABLED_COMPONENTS, userId); 4732 if (DEBUG_PREFERRED || debug) { 4733 Slog.v(TAG, "Found persistent preferred activity:"); 4734 if (ai != null) { 4735 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4736 } else { 4737 Slog.v(TAG, " null"); 4738 } 4739 } 4740 if (ai == null) { 4741 // This previously registered persistent preferred activity 4742 // component is no longer known. Ignore it and do NOT remove it. 4743 continue; 4744 } 4745 for (int j=0; j<N; j++) { 4746 final ResolveInfo ri = query.get(j); 4747 if (!ri.activityInfo.applicationInfo.packageName 4748 .equals(ai.applicationInfo.packageName)) { 4749 continue; 4750 } 4751 if (!ri.activityInfo.name.equals(ai.name)) { 4752 continue; 4753 } 4754 // Found a persistent preference that can handle the intent. 4755 if (DEBUG_PREFERRED || debug) { 4756 Slog.v(TAG, "Returning persistent preferred activity: " + 4757 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4758 } 4759 return ri; 4760 } 4761 } 4762 } 4763 return null; 4764 } 4765 4766 // TODO: handle preferred activities missing while user has amnesia 4767 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4768 List<ResolveInfo> query, int priority, boolean always, 4769 boolean removeMatches, boolean debug, int userId) { 4770 if (!sUserManager.exists(userId)) return null; 4771 flags = updateFlagsForResolve(flags, userId, intent); 4772 // writer 4773 synchronized (mPackages) { 4774 if (intent.getSelector() != null) { 4775 intent = intent.getSelector(); 4776 } 4777 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4778 4779 // Try to find a matching persistent preferred activity. 4780 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4781 debug, userId); 4782 4783 // If a persistent preferred activity matched, use it. 4784 if (pri != null) { 4785 return pri; 4786 } 4787 4788 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4789 // Get the list of preferred activities that handle the intent 4790 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4791 List<PreferredActivity> prefs = pir != null 4792 ? pir.queryIntent(intent, resolvedType, 4793 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4794 : null; 4795 if (prefs != null && prefs.size() > 0) { 4796 boolean changed = false; 4797 try { 4798 // First figure out how good the original match set is. 4799 // We will only allow preferred activities that came 4800 // from the same match quality. 4801 int match = 0; 4802 4803 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4804 4805 final int N = query.size(); 4806 for (int j=0; j<N; j++) { 4807 final ResolveInfo ri = query.get(j); 4808 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4809 + ": 0x" + Integer.toHexString(match)); 4810 if (ri.match > match) { 4811 match = ri.match; 4812 } 4813 } 4814 4815 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4816 + Integer.toHexString(match)); 4817 4818 match &= IntentFilter.MATCH_CATEGORY_MASK; 4819 final int M = prefs.size(); 4820 for (int i=0; i<M; i++) { 4821 final PreferredActivity pa = prefs.get(i); 4822 if (DEBUG_PREFERRED || debug) { 4823 Slog.v(TAG, "Checking PreferredActivity ds=" 4824 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4825 + "\n component=" + pa.mPref.mComponent); 4826 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4827 } 4828 if (pa.mPref.mMatch != match) { 4829 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4830 + Integer.toHexString(pa.mPref.mMatch)); 4831 continue; 4832 } 4833 // If it's not an "always" type preferred activity and that's what we're 4834 // looking for, skip it. 4835 if (always && !pa.mPref.mAlways) { 4836 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4837 continue; 4838 } 4839 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4840 flags | MATCH_DISABLED_COMPONENTS, userId); 4841 if (DEBUG_PREFERRED || debug) { 4842 Slog.v(TAG, "Found preferred activity:"); 4843 if (ai != null) { 4844 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4845 } else { 4846 Slog.v(TAG, " null"); 4847 } 4848 } 4849 if (ai == null) { 4850 // This previously registered preferred activity 4851 // component is no longer known. Most likely an update 4852 // to the app was installed and in the new version this 4853 // component no longer exists. Clean it up by removing 4854 // it from the preferred activities list, and skip it. 4855 Slog.w(TAG, "Removing dangling preferred activity: " 4856 + pa.mPref.mComponent); 4857 pir.removeFilter(pa); 4858 changed = true; 4859 continue; 4860 } 4861 for (int j=0; j<N; j++) { 4862 final ResolveInfo ri = query.get(j); 4863 if (!ri.activityInfo.applicationInfo.packageName 4864 .equals(ai.applicationInfo.packageName)) { 4865 continue; 4866 } 4867 if (!ri.activityInfo.name.equals(ai.name)) { 4868 continue; 4869 } 4870 4871 if (removeMatches) { 4872 pir.removeFilter(pa); 4873 changed = true; 4874 if (DEBUG_PREFERRED) { 4875 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4876 } 4877 break; 4878 } 4879 4880 // Okay we found a previously set preferred or last chosen app. 4881 // If the result set is different from when this 4882 // was created, we need to clear it and re-ask the 4883 // user their preference, if we're looking for an "always" type entry. 4884 if (always && !pa.mPref.sameSet(query)) { 4885 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4886 + intent + " type " + resolvedType); 4887 if (DEBUG_PREFERRED) { 4888 Slog.v(TAG, "Removing preferred activity since set changed " 4889 + pa.mPref.mComponent); 4890 } 4891 pir.removeFilter(pa); 4892 // Re-add the filter as a "last chosen" entry (!always) 4893 PreferredActivity lastChosen = new PreferredActivity( 4894 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4895 pir.addFilter(lastChosen); 4896 changed = true; 4897 return null; 4898 } 4899 4900 // Yay! Either the set matched or we're looking for the last chosen 4901 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4902 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4903 return ri; 4904 } 4905 } 4906 } finally { 4907 if (changed) { 4908 if (DEBUG_PREFERRED) { 4909 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4910 } 4911 scheduleWritePackageRestrictionsLocked(userId); 4912 } 4913 } 4914 } 4915 } 4916 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4917 return null; 4918 } 4919 4920 /* 4921 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4922 */ 4923 @Override 4924 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4925 int targetUserId) { 4926 mContext.enforceCallingOrSelfPermission( 4927 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4928 List<CrossProfileIntentFilter> matches = 4929 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4930 if (matches != null) { 4931 int size = matches.size(); 4932 for (int i = 0; i < size; i++) { 4933 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4934 } 4935 } 4936 if (hasWebURI(intent)) { 4937 // cross-profile app linking works only towards the parent. 4938 final UserInfo parent = getProfileParent(sourceUserId); 4939 synchronized(mPackages) { 4940 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 4941 intent, resolvedType, 0, sourceUserId, parent.id); 4942 return xpDomainInfo != null; 4943 } 4944 } 4945 return false; 4946 } 4947 4948 private UserInfo getProfileParent(int userId) { 4949 final long identity = Binder.clearCallingIdentity(); 4950 try { 4951 return sUserManager.getProfileParent(userId); 4952 } finally { 4953 Binder.restoreCallingIdentity(identity); 4954 } 4955 } 4956 4957 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4958 String resolvedType, int userId) { 4959 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4960 if (resolver != null) { 4961 return resolver.queryIntent(intent, resolvedType, false, userId); 4962 } 4963 return null; 4964 } 4965 4966 @Override 4967 public List<ResolveInfo> queryIntentActivities(Intent intent, 4968 String resolvedType, int flags, int userId) { 4969 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4970 flags = updateFlagsForResolve(flags, userId, intent); 4971 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4972 ComponentName comp = intent.getComponent(); 4973 if (comp == null) { 4974 if (intent.getSelector() != null) { 4975 intent = intent.getSelector(); 4976 comp = intent.getComponent(); 4977 } 4978 } 4979 4980 if (comp != null) { 4981 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4982 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4983 if (ai != null) { 4984 final ResolveInfo ri = new ResolveInfo(); 4985 ri.activityInfo = ai; 4986 list.add(ri); 4987 } 4988 return list; 4989 } 4990 4991 // reader 4992 synchronized (mPackages) { 4993 final String pkgName = intent.getPackage(); 4994 if (pkgName == null) { 4995 List<CrossProfileIntentFilter> matchingFilters = 4996 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4997 // Check for results that need to skip the current profile. 4998 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4999 resolvedType, flags, userId); 5000 if (xpResolveInfo != null) { 5001 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5002 result.add(xpResolveInfo); 5003 return filterIfNotSystemUser(result, userId); 5004 } 5005 5006 // Check for results in the current profile. 5007 List<ResolveInfo> result = mActivities.queryIntent( 5008 intent, resolvedType, flags, userId); 5009 result = filterIfNotSystemUser(result, userId); 5010 5011 // Check for cross profile results. 5012 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5013 xpResolveInfo = queryCrossProfileIntents( 5014 matchingFilters, intent, resolvedType, flags, userId, 5015 hasNonNegativePriorityResult); 5016 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5017 boolean isVisibleToUser = filterIfNotSystemUser( 5018 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5019 if (isVisibleToUser) { 5020 result.add(xpResolveInfo); 5021 Collections.sort(result, mResolvePrioritySorter); 5022 } 5023 } 5024 if (hasWebURI(intent)) { 5025 CrossProfileDomainInfo xpDomainInfo = null; 5026 final UserInfo parent = getProfileParent(userId); 5027 if (parent != null) { 5028 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5029 flags, userId, parent.id); 5030 } 5031 if (xpDomainInfo != null) { 5032 if (xpResolveInfo != null) { 5033 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5034 // in the result. 5035 result.remove(xpResolveInfo); 5036 } 5037 if (result.size() == 0) { 5038 result.add(xpDomainInfo.resolveInfo); 5039 return result; 5040 } 5041 } else if (result.size() <= 1) { 5042 return result; 5043 } 5044 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5045 xpDomainInfo, userId); 5046 Collections.sort(result, mResolvePrioritySorter); 5047 } 5048 return result; 5049 } 5050 final PackageParser.Package pkg = mPackages.get(pkgName); 5051 if (pkg != null) { 5052 return filterIfNotSystemUser( 5053 mActivities.queryIntentForPackage( 5054 intent, resolvedType, flags, pkg.activities, userId), 5055 userId); 5056 } 5057 return new ArrayList<ResolveInfo>(); 5058 } 5059 } 5060 5061 private static class CrossProfileDomainInfo { 5062 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5063 ResolveInfo resolveInfo; 5064 /* Best domain verification status of the activities found in the other profile */ 5065 int bestDomainVerificationStatus; 5066 } 5067 5068 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5069 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5070 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5071 sourceUserId)) { 5072 return null; 5073 } 5074 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5075 resolvedType, flags, parentUserId); 5076 5077 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5078 return null; 5079 } 5080 CrossProfileDomainInfo result = null; 5081 int size = resultTargetUser.size(); 5082 for (int i = 0; i < size; i++) { 5083 ResolveInfo riTargetUser = resultTargetUser.get(i); 5084 // Intent filter verification is only for filters that specify a host. So don't return 5085 // those that handle all web uris. 5086 if (riTargetUser.handleAllWebDataURI) { 5087 continue; 5088 } 5089 String packageName = riTargetUser.activityInfo.packageName; 5090 PackageSetting ps = mSettings.mPackages.get(packageName); 5091 if (ps == null) { 5092 continue; 5093 } 5094 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5095 int status = (int)(verificationState >> 32); 5096 if (result == null) { 5097 result = new CrossProfileDomainInfo(); 5098 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5099 sourceUserId, parentUserId); 5100 result.bestDomainVerificationStatus = status; 5101 } else { 5102 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5103 result.bestDomainVerificationStatus); 5104 } 5105 } 5106 // Don't consider matches with status NEVER across profiles. 5107 if (result != null && result.bestDomainVerificationStatus 5108 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5109 return null; 5110 } 5111 return result; 5112 } 5113 5114 /** 5115 * Verification statuses are ordered from the worse to the best, except for 5116 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5117 */ 5118 private int bestDomainVerificationStatus(int status1, int status2) { 5119 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5120 return status2; 5121 } 5122 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5123 return status1; 5124 } 5125 return (int) MathUtils.max(status1, status2); 5126 } 5127 5128 private boolean isUserEnabled(int userId) { 5129 long callingId = Binder.clearCallingIdentity(); 5130 try { 5131 UserInfo userInfo = sUserManager.getUserInfo(userId); 5132 return userInfo != null && userInfo.isEnabled(); 5133 } finally { 5134 Binder.restoreCallingIdentity(callingId); 5135 } 5136 } 5137 5138 /** 5139 * Filter out activities with systemUserOnly flag set, when current user is not System. 5140 * 5141 * @return filtered list 5142 */ 5143 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5144 if (userId == UserHandle.USER_SYSTEM) { 5145 return resolveInfos; 5146 } 5147 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5148 ResolveInfo info = resolveInfos.get(i); 5149 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5150 resolveInfos.remove(i); 5151 } 5152 } 5153 return resolveInfos; 5154 } 5155 5156 /** 5157 * @param resolveInfos list of resolve infos in descending priority order 5158 * @return if the list contains a resolve info with non-negative priority 5159 */ 5160 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5161 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5162 } 5163 5164 private static boolean hasWebURI(Intent intent) { 5165 if (intent.getData() == null) { 5166 return false; 5167 } 5168 final String scheme = intent.getScheme(); 5169 if (TextUtils.isEmpty(scheme)) { 5170 return false; 5171 } 5172 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5173 } 5174 5175 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5176 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5177 int userId) { 5178 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5179 5180 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5181 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5182 candidates.size()); 5183 } 5184 5185 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5186 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5187 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5188 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5189 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5190 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5191 5192 synchronized (mPackages) { 5193 final int count = candidates.size(); 5194 // First, try to use linked apps. Partition the candidates into four lists: 5195 // one for the final results, one for the "do not use ever", one for "undefined status" 5196 // and finally one for "browser app type". 5197 for (int n=0; n<count; n++) { 5198 ResolveInfo info = candidates.get(n); 5199 String packageName = info.activityInfo.packageName; 5200 PackageSetting ps = mSettings.mPackages.get(packageName); 5201 if (ps != null) { 5202 // Add to the special match all list (Browser use case) 5203 if (info.handleAllWebDataURI) { 5204 matchAllList.add(info); 5205 continue; 5206 } 5207 // Try to get the status from User settings first 5208 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5209 int status = (int)(packedStatus >> 32); 5210 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5211 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5212 if (DEBUG_DOMAIN_VERIFICATION) { 5213 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5214 + " : linkgen=" + linkGeneration); 5215 } 5216 // Use link-enabled generation as preferredOrder, i.e. 5217 // prefer newly-enabled over earlier-enabled. 5218 info.preferredOrder = linkGeneration; 5219 alwaysList.add(info); 5220 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5221 if (DEBUG_DOMAIN_VERIFICATION) { 5222 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5223 } 5224 neverList.add(info); 5225 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5226 if (DEBUG_DOMAIN_VERIFICATION) { 5227 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5228 } 5229 alwaysAskList.add(info); 5230 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5231 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5232 if (DEBUG_DOMAIN_VERIFICATION) { 5233 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5234 } 5235 undefinedList.add(info); 5236 } 5237 } 5238 } 5239 5240 // We'll want to include browser possibilities in a few cases 5241 boolean includeBrowser = false; 5242 5243 // First try to add the "always" resolution(s) for the current user, if any 5244 if (alwaysList.size() > 0) { 5245 result.addAll(alwaysList); 5246 } else { 5247 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5248 result.addAll(undefinedList); 5249 // Maybe add one for the other profile. 5250 if (xpDomainInfo != null && ( 5251 xpDomainInfo.bestDomainVerificationStatus 5252 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5253 result.add(xpDomainInfo.resolveInfo); 5254 } 5255 includeBrowser = true; 5256 } 5257 5258 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5259 // If there were 'always' entries their preferred order has been set, so we also 5260 // back that off to make the alternatives equivalent 5261 if (alwaysAskList.size() > 0) { 5262 for (ResolveInfo i : result) { 5263 i.preferredOrder = 0; 5264 } 5265 result.addAll(alwaysAskList); 5266 includeBrowser = true; 5267 } 5268 5269 if (includeBrowser) { 5270 // Also add browsers (all of them or only the default one) 5271 if (DEBUG_DOMAIN_VERIFICATION) { 5272 Slog.v(TAG, " ...including browsers in candidate set"); 5273 } 5274 if ((matchFlags & MATCH_ALL) != 0) { 5275 result.addAll(matchAllList); 5276 } else { 5277 // Browser/generic handling case. If there's a default browser, go straight 5278 // to that (but only if there is no other higher-priority match). 5279 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5280 int maxMatchPrio = 0; 5281 ResolveInfo defaultBrowserMatch = null; 5282 final int numCandidates = matchAllList.size(); 5283 for (int n = 0; n < numCandidates; n++) { 5284 ResolveInfo info = matchAllList.get(n); 5285 // track the highest overall match priority... 5286 if (info.priority > maxMatchPrio) { 5287 maxMatchPrio = info.priority; 5288 } 5289 // ...and the highest-priority default browser match 5290 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5291 if (defaultBrowserMatch == null 5292 || (defaultBrowserMatch.priority < info.priority)) { 5293 if (debug) { 5294 Slog.v(TAG, "Considering default browser match " + info); 5295 } 5296 defaultBrowserMatch = info; 5297 } 5298 } 5299 } 5300 if (defaultBrowserMatch != null 5301 && defaultBrowserMatch.priority >= maxMatchPrio 5302 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5303 { 5304 if (debug) { 5305 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5306 } 5307 result.add(defaultBrowserMatch); 5308 } else { 5309 result.addAll(matchAllList); 5310 } 5311 } 5312 5313 // If there is nothing selected, add all candidates and remove the ones that the user 5314 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5315 if (result.size() == 0) { 5316 result.addAll(candidates); 5317 result.removeAll(neverList); 5318 } 5319 } 5320 } 5321 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5322 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5323 result.size()); 5324 for (ResolveInfo info : result) { 5325 Slog.v(TAG, " + " + info.activityInfo); 5326 } 5327 } 5328 return result; 5329 } 5330 5331 // Returns a packed value as a long: 5332 // 5333 // high 'int'-sized word: link status: undefined/ask/never/always. 5334 // low 'int'-sized word: relative priority among 'always' results. 5335 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5336 long result = ps.getDomainVerificationStatusForUser(userId); 5337 // if none available, get the master status 5338 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5339 if (ps.getIntentFilterVerificationInfo() != null) { 5340 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5341 } 5342 } 5343 return result; 5344 } 5345 5346 private ResolveInfo querySkipCurrentProfileIntents( 5347 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5348 int flags, int sourceUserId) { 5349 if (matchingFilters != null) { 5350 int size = matchingFilters.size(); 5351 for (int i = 0; i < size; i ++) { 5352 CrossProfileIntentFilter filter = matchingFilters.get(i); 5353 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5354 // Checking if there are activities in the target user that can handle the 5355 // intent. 5356 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5357 resolvedType, flags, sourceUserId); 5358 if (resolveInfo != null) { 5359 return resolveInfo; 5360 } 5361 } 5362 } 5363 } 5364 return null; 5365 } 5366 5367 // Return matching ResolveInfo in target user if any. 5368 private ResolveInfo queryCrossProfileIntents( 5369 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5370 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5371 if (matchingFilters != null) { 5372 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5373 // match the same intent. For performance reasons, it is better not to 5374 // run queryIntent twice for the same userId 5375 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5376 int size = matchingFilters.size(); 5377 for (int i = 0; i < size; i++) { 5378 CrossProfileIntentFilter filter = matchingFilters.get(i); 5379 int targetUserId = filter.getTargetUserId(); 5380 boolean skipCurrentProfile = 5381 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5382 boolean skipCurrentProfileIfNoMatchFound = 5383 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5384 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5385 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5386 // Checking if there are activities in the target user that can handle the 5387 // intent. 5388 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5389 resolvedType, flags, sourceUserId); 5390 if (resolveInfo != null) return resolveInfo; 5391 alreadyTriedUserIds.put(targetUserId, true); 5392 } 5393 } 5394 } 5395 return null; 5396 } 5397 5398 /** 5399 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5400 * will forward the intent to the filter's target user. 5401 * Otherwise, returns null. 5402 */ 5403 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5404 String resolvedType, int flags, int sourceUserId) { 5405 int targetUserId = filter.getTargetUserId(); 5406 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5407 resolvedType, flags, targetUserId); 5408 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5409 // If all the matches in the target profile are suspended, return null. 5410 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5411 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5412 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5413 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5414 targetUserId); 5415 } 5416 } 5417 } 5418 return null; 5419 } 5420 5421 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5422 int sourceUserId, int targetUserId) { 5423 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5424 long ident = Binder.clearCallingIdentity(); 5425 boolean targetIsProfile; 5426 try { 5427 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5428 } finally { 5429 Binder.restoreCallingIdentity(ident); 5430 } 5431 String className; 5432 if (targetIsProfile) { 5433 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5434 } else { 5435 className = FORWARD_INTENT_TO_PARENT; 5436 } 5437 ComponentName forwardingActivityComponentName = new ComponentName( 5438 mAndroidApplication.packageName, className); 5439 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5440 sourceUserId); 5441 if (!targetIsProfile) { 5442 forwardingActivityInfo.showUserIcon = targetUserId; 5443 forwardingResolveInfo.noResourceId = true; 5444 } 5445 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5446 forwardingResolveInfo.priority = 0; 5447 forwardingResolveInfo.preferredOrder = 0; 5448 forwardingResolveInfo.match = 0; 5449 forwardingResolveInfo.isDefault = true; 5450 forwardingResolveInfo.filter = filter; 5451 forwardingResolveInfo.targetUserId = targetUserId; 5452 return forwardingResolveInfo; 5453 } 5454 5455 @Override 5456 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5457 Intent[] specifics, String[] specificTypes, Intent intent, 5458 String resolvedType, int flags, int userId) { 5459 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5460 flags = updateFlagsForResolve(flags, userId, intent); 5461 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 5462 false, "query intent activity options"); 5463 final String resultsAction = intent.getAction(); 5464 5465 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 5466 | PackageManager.GET_RESOLVED_FILTER, userId); 5467 5468 if (DEBUG_INTENT_MATCHING) { 5469 Log.v(TAG, "Query " + intent + ": " + results); 5470 } 5471 5472 int specificsPos = 0; 5473 int N; 5474 5475 // todo: note that the algorithm used here is O(N^2). This 5476 // isn't a problem in our current environment, but if we start running 5477 // into situations where we have more than 5 or 10 matches then this 5478 // should probably be changed to something smarter... 5479 5480 // First we go through and resolve each of the specific items 5481 // that were supplied, taking care of removing any corresponding 5482 // duplicate items in the generic resolve list. 5483 if (specifics != null) { 5484 for (int i=0; i<specifics.length; i++) { 5485 final Intent sintent = specifics[i]; 5486 if (sintent == null) { 5487 continue; 5488 } 5489 5490 if (DEBUG_INTENT_MATCHING) { 5491 Log.v(TAG, "Specific #" + i + ": " + sintent); 5492 } 5493 5494 String action = sintent.getAction(); 5495 if (resultsAction != null && resultsAction.equals(action)) { 5496 // If this action was explicitly requested, then don't 5497 // remove things that have it. 5498 action = null; 5499 } 5500 5501 ResolveInfo ri = null; 5502 ActivityInfo ai = null; 5503 5504 ComponentName comp = sintent.getComponent(); 5505 if (comp == null) { 5506 ri = resolveIntent( 5507 sintent, 5508 specificTypes != null ? specificTypes[i] : null, 5509 flags, userId); 5510 if (ri == null) { 5511 continue; 5512 } 5513 if (ri == mResolveInfo) { 5514 // ACK! Must do something better with this. 5515 } 5516 ai = ri.activityInfo; 5517 comp = new ComponentName(ai.applicationInfo.packageName, 5518 ai.name); 5519 } else { 5520 ai = getActivityInfo(comp, flags, userId); 5521 if (ai == null) { 5522 continue; 5523 } 5524 } 5525 5526 // Look for any generic query activities that are duplicates 5527 // of this specific one, and remove them from the results. 5528 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5529 N = results.size(); 5530 int j; 5531 for (j=specificsPos; j<N; j++) { 5532 ResolveInfo sri = results.get(j); 5533 if ((sri.activityInfo.name.equals(comp.getClassName()) 5534 && sri.activityInfo.applicationInfo.packageName.equals( 5535 comp.getPackageName())) 5536 || (action != null && sri.filter.matchAction(action))) { 5537 results.remove(j); 5538 if (DEBUG_INTENT_MATCHING) Log.v( 5539 TAG, "Removing duplicate item from " + j 5540 + " due to specific " + specificsPos); 5541 if (ri == null) { 5542 ri = sri; 5543 } 5544 j--; 5545 N--; 5546 } 5547 } 5548 5549 // Add this specific item to its proper place. 5550 if (ri == null) { 5551 ri = new ResolveInfo(); 5552 ri.activityInfo = ai; 5553 } 5554 results.add(specificsPos, ri); 5555 ri.specificIndex = i; 5556 specificsPos++; 5557 } 5558 } 5559 5560 // Now we go through the remaining generic results and remove any 5561 // duplicate actions that are found here. 5562 N = results.size(); 5563 for (int i=specificsPos; i<N-1; i++) { 5564 final ResolveInfo rii = results.get(i); 5565 if (rii.filter == null) { 5566 continue; 5567 } 5568 5569 // Iterate over all of the actions of this result's intent 5570 // filter... typically this should be just one. 5571 final Iterator<String> it = rii.filter.actionsIterator(); 5572 if (it == null) { 5573 continue; 5574 } 5575 while (it.hasNext()) { 5576 final String action = it.next(); 5577 if (resultsAction != null && resultsAction.equals(action)) { 5578 // If this action was explicitly requested, then don't 5579 // remove things that have it. 5580 continue; 5581 } 5582 for (int j=i+1; j<N; j++) { 5583 final ResolveInfo rij = results.get(j); 5584 if (rij.filter != null && rij.filter.hasAction(action)) { 5585 results.remove(j); 5586 if (DEBUG_INTENT_MATCHING) Log.v( 5587 TAG, "Removing duplicate item from " + j 5588 + " due to action " + action + " at " + i); 5589 j--; 5590 N--; 5591 } 5592 } 5593 } 5594 5595 // If the caller didn't request filter information, drop it now 5596 // so we don't have to marshall/unmarshall it. 5597 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5598 rii.filter = null; 5599 } 5600 } 5601 5602 // Filter out the caller activity if so requested. 5603 if (caller != null) { 5604 N = results.size(); 5605 for (int i=0; i<N; i++) { 5606 ActivityInfo ainfo = results.get(i).activityInfo; 5607 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5608 && caller.getClassName().equals(ainfo.name)) { 5609 results.remove(i); 5610 break; 5611 } 5612 } 5613 } 5614 5615 // If the caller didn't request filter information, 5616 // drop them now so we don't have to 5617 // marshall/unmarshall it. 5618 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5619 N = results.size(); 5620 for (int i=0; i<N; i++) { 5621 results.get(i).filter = null; 5622 } 5623 } 5624 5625 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5626 return results; 5627 } 5628 5629 @Override 5630 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 5631 int userId) { 5632 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5633 flags = updateFlagsForResolve(flags, userId, intent); 5634 ComponentName comp = intent.getComponent(); 5635 if (comp == null) { 5636 if (intent.getSelector() != null) { 5637 intent = intent.getSelector(); 5638 comp = intent.getComponent(); 5639 } 5640 } 5641 if (comp != null) { 5642 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5643 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5644 if (ai != null) { 5645 ResolveInfo ri = new ResolveInfo(); 5646 ri.activityInfo = ai; 5647 list.add(ri); 5648 } 5649 return list; 5650 } 5651 5652 // reader 5653 synchronized (mPackages) { 5654 String pkgName = intent.getPackage(); 5655 if (pkgName == null) { 5656 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5657 } 5658 final PackageParser.Package pkg = mPackages.get(pkgName); 5659 if (pkg != null) { 5660 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5661 userId); 5662 } 5663 return null; 5664 } 5665 } 5666 5667 @Override 5668 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5669 if (!sUserManager.exists(userId)) return null; 5670 flags = updateFlagsForResolve(flags, userId, intent); 5671 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 5672 if (query != null) { 5673 if (query.size() >= 1) { 5674 // If there is more than one service with the same priority, 5675 // just arbitrarily pick the first one. 5676 return query.get(0); 5677 } 5678 } 5679 return null; 5680 } 5681 5682 @Override 5683 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 5684 int userId) { 5685 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5686 flags = updateFlagsForResolve(flags, userId, intent); 5687 ComponentName comp = intent.getComponent(); 5688 if (comp == null) { 5689 if (intent.getSelector() != null) { 5690 intent = intent.getSelector(); 5691 comp = intent.getComponent(); 5692 } 5693 } 5694 if (comp != null) { 5695 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5696 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5697 if (si != null) { 5698 final ResolveInfo ri = new ResolveInfo(); 5699 ri.serviceInfo = si; 5700 list.add(ri); 5701 } 5702 return list; 5703 } 5704 5705 // reader 5706 synchronized (mPackages) { 5707 String pkgName = intent.getPackage(); 5708 if (pkgName == null) { 5709 return mServices.queryIntent(intent, resolvedType, flags, userId); 5710 } 5711 final PackageParser.Package pkg = mPackages.get(pkgName); 5712 if (pkg != null) { 5713 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5714 userId); 5715 } 5716 return null; 5717 } 5718 } 5719 5720 @Override 5721 public List<ResolveInfo> queryIntentContentProviders( 5722 Intent intent, String resolvedType, int flags, int userId) { 5723 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5724 flags = updateFlagsForResolve(flags, userId, intent); 5725 ComponentName comp = intent.getComponent(); 5726 if (comp == null) { 5727 if (intent.getSelector() != null) { 5728 intent = intent.getSelector(); 5729 comp = intent.getComponent(); 5730 } 5731 } 5732 if (comp != null) { 5733 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5734 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5735 if (pi != null) { 5736 final ResolveInfo ri = new ResolveInfo(); 5737 ri.providerInfo = pi; 5738 list.add(ri); 5739 } 5740 return list; 5741 } 5742 5743 // reader 5744 synchronized (mPackages) { 5745 String pkgName = intent.getPackage(); 5746 if (pkgName == null) { 5747 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5748 } 5749 final PackageParser.Package pkg = mPackages.get(pkgName); 5750 if (pkg != null) { 5751 return mProviders.queryIntentForPackage( 5752 intent, resolvedType, flags, pkg.providers, userId); 5753 } 5754 return null; 5755 } 5756 } 5757 5758 @Override 5759 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5760 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5761 flags = updateFlagsForPackage(flags, userId, null); 5762 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5763 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 5764 5765 // writer 5766 synchronized (mPackages) { 5767 ArrayList<PackageInfo> list; 5768 if (listUninstalled) { 5769 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5770 for (PackageSetting ps : mSettings.mPackages.values()) { 5771 PackageInfo pi; 5772 if (ps.pkg != null) { 5773 pi = generatePackageInfo(ps.pkg, flags, userId); 5774 } else { 5775 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5776 } 5777 if (pi != null) { 5778 list.add(pi); 5779 } 5780 } 5781 } else { 5782 list = new ArrayList<PackageInfo>(mPackages.size()); 5783 for (PackageParser.Package p : mPackages.values()) { 5784 PackageInfo pi = generatePackageInfo(p, flags, userId); 5785 if (pi != null) { 5786 list.add(pi); 5787 } 5788 } 5789 } 5790 5791 return new ParceledListSlice<PackageInfo>(list); 5792 } 5793 } 5794 5795 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5796 String[] permissions, boolean[] tmp, int flags, int userId) { 5797 int numMatch = 0; 5798 final PermissionsState permissionsState = ps.getPermissionsState(); 5799 for (int i=0; i<permissions.length; i++) { 5800 final String permission = permissions[i]; 5801 if (permissionsState.hasPermission(permission, userId)) { 5802 tmp[i] = true; 5803 numMatch++; 5804 } else { 5805 tmp[i] = false; 5806 } 5807 } 5808 if (numMatch == 0) { 5809 return; 5810 } 5811 PackageInfo pi; 5812 if (ps.pkg != null) { 5813 pi = generatePackageInfo(ps.pkg, flags, userId); 5814 } else { 5815 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5816 } 5817 // The above might return null in cases of uninstalled apps or install-state 5818 // skew across users/profiles. 5819 if (pi != null) { 5820 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5821 if (numMatch == permissions.length) { 5822 pi.requestedPermissions = permissions; 5823 } else { 5824 pi.requestedPermissions = new String[numMatch]; 5825 numMatch = 0; 5826 for (int i=0; i<permissions.length; i++) { 5827 if (tmp[i]) { 5828 pi.requestedPermissions[numMatch] = permissions[i]; 5829 numMatch++; 5830 } 5831 } 5832 } 5833 } 5834 list.add(pi); 5835 } 5836 } 5837 5838 @Override 5839 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5840 String[] permissions, int flags, int userId) { 5841 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5842 flags = updateFlagsForPackage(flags, userId, permissions); 5843 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5844 5845 // writer 5846 synchronized (mPackages) { 5847 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5848 boolean[] tmpBools = new boolean[permissions.length]; 5849 if (listUninstalled) { 5850 for (PackageSetting ps : mSettings.mPackages.values()) { 5851 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5852 } 5853 } else { 5854 for (PackageParser.Package pkg : mPackages.values()) { 5855 PackageSetting ps = (PackageSetting)pkg.mExtras; 5856 if (ps != null) { 5857 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5858 userId); 5859 } 5860 } 5861 } 5862 5863 return new ParceledListSlice<PackageInfo>(list); 5864 } 5865 } 5866 5867 @Override 5868 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5869 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5870 flags = updateFlagsForApplication(flags, userId, null); 5871 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5872 5873 // writer 5874 synchronized (mPackages) { 5875 ArrayList<ApplicationInfo> list; 5876 if (listUninstalled) { 5877 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5878 for (PackageSetting ps : mSettings.mPackages.values()) { 5879 ApplicationInfo ai; 5880 if (ps.pkg != null) { 5881 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5882 ps.readUserState(userId), userId); 5883 } else { 5884 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5885 } 5886 if (ai != null) { 5887 list.add(ai); 5888 } 5889 } 5890 } else { 5891 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5892 for (PackageParser.Package p : mPackages.values()) { 5893 if (p.mExtras != null) { 5894 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5895 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5896 if (ai != null) { 5897 list.add(ai); 5898 } 5899 } 5900 } 5901 } 5902 5903 return new ParceledListSlice<ApplicationInfo>(list); 5904 } 5905 } 5906 5907 @Override 5908 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 5909 if (DISABLE_EPHEMERAL_APPS) { 5910 return null; 5911 } 5912 5913 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5914 "getEphemeralApplications"); 5915 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5916 "getEphemeralApplications"); 5917 synchronized (mPackages) { 5918 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 5919 .getEphemeralApplicationsLPw(userId); 5920 if (ephemeralApps != null) { 5921 return new ParceledListSlice<>(ephemeralApps); 5922 } 5923 } 5924 return null; 5925 } 5926 5927 @Override 5928 public boolean isEphemeralApplication(String packageName, int userId) { 5929 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5930 "isEphemeral"); 5931 if (DISABLE_EPHEMERAL_APPS) { 5932 return false; 5933 } 5934 5935 if (!isCallerSameApp(packageName)) { 5936 return false; 5937 } 5938 synchronized (mPackages) { 5939 PackageParser.Package pkg = mPackages.get(packageName); 5940 if (pkg != null) { 5941 return pkg.applicationInfo.isEphemeralApp(); 5942 } 5943 } 5944 return false; 5945 } 5946 5947 @Override 5948 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 5949 if (DISABLE_EPHEMERAL_APPS) { 5950 return null; 5951 } 5952 5953 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5954 "getCookie"); 5955 if (!isCallerSameApp(packageName)) { 5956 return null; 5957 } 5958 synchronized (mPackages) { 5959 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 5960 packageName, userId); 5961 } 5962 } 5963 5964 @Override 5965 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 5966 if (DISABLE_EPHEMERAL_APPS) { 5967 return true; 5968 } 5969 5970 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5971 "setCookie"); 5972 if (!isCallerSameApp(packageName)) { 5973 return false; 5974 } 5975 synchronized (mPackages) { 5976 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 5977 packageName, cookie, userId); 5978 } 5979 } 5980 5981 @Override 5982 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 5983 if (DISABLE_EPHEMERAL_APPS) { 5984 return null; 5985 } 5986 5987 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 5988 "getEphemeralApplicationIcon"); 5989 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 5990 "getEphemeralApplicationIcon"); 5991 synchronized (mPackages) { 5992 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 5993 packageName, userId); 5994 } 5995 } 5996 5997 private boolean isCallerSameApp(String packageName) { 5998 PackageParser.Package pkg = mPackages.get(packageName); 5999 return pkg != null 6000 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6001 } 6002 6003 public List<ApplicationInfo> getPersistentApplications(int flags) { 6004 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6005 6006 // reader 6007 synchronized (mPackages) { 6008 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6009 final int userId = UserHandle.getCallingUserId(); 6010 while (i.hasNext()) { 6011 final PackageParser.Package p = i.next(); 6012 if (p.applicationInfo != null 6013 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 6014 && (!mSafeMode || isSystemApp(p))) { 6015 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6016 if (ps != null) { 6017 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6018 ps.readUserState(userId), userId); 6019 if (ai != null) { 6020 finalList.add(ai); 6021 } 6022 } 6023 } 6024 } 6025 } 6026 6027 return finalList; 6028 } 6029 6030 @Override 6031 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6032 if (!sUserManager.exists(userId)) return null; 6033 flags = updateFlagsForComponent(flags, userId, name); 6034 // reader 6035 synchronized (mPackages) { 6036 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6037 PackageSetting ps = provider != null 6038 ? mSettings.mPackages.get(provider.owner.packageName) 6039 : null; 6040 return ps != null 6041 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6042 ? PackageParser.generateProviderInfo(provider, flags, 6043 ps.readUserState(userId), userId) 6044 : null; 6045 } 6046 } 6047 6048 /** 6049 * @deprecated 6050 */ 6051 @Deprecated 6052 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6053 // reader 6054 synchronized (mPackages) { 6055 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6056 .entrySet().iterator(); 6057 final int userId = UserHandle.getCallingUserId(); 6058 while (i.hasNext()) { 6059 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6060 PackageParser.Provider p = entry.getValue(); 6061 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6062 6063 if (ps != null && p.syncable 6064 && (!mSafeMode || (p.info.applicationInfo.flags 6065 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6066 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6067 ps.readUserState(userId), userId); 6068 if (info != null) { 6069 outNames.add(entry.getKey()); 6070 outInfo.add(info); 6071 } 6072 } 6073 } 6074 } 6075 } 6076 6077 @Override 6078 public ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6079 int uid, int flags) { 6080 final int userId = processName != null ? UserHandle.getUserId(uid) 6081 : UserHandle.getCallingUserId(); 6082 if (!sUserManager.exists(userId)) return null; 6083 flags = updateFlagsForComponent(flags, userId, processName); 6084 6085 ArrayList<ProviderInfo> finalList = null; 6086 // reader 6087 synchronized (mPackages) { 6088 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6089 while (i.hasNext()) { 6090 final PackageParser.Provider p = i.next(); 6091 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6092 if (ps != null && p.info.authority != null 6093 && (processName == null 6094 || (p.info.processName.equals(processName) 6095 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6096 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6097 if (finalList == null) { 6098 finalList = new ArrayList<ProviderInfo>(3); 6099 } 6100 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6101 ps.readUserState(userId), userId); 6102 if (info != null) { 6103 finalList.add(info); 6104 } 6105 } 6106 } 6107 } 6108 6109 if (finalList != null) { 6110 Collections.sort(finalList, mProviderInitOrderSorter); 6111 return new ParceledListSlice<ProviderInfo>(finalList); 6112 } 6113 6114 return null; 6115 } 6116 6117 @Override 6118 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6119 // reader 6120 synchronized (mPackages) { 6121 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6122 return PackageParser.generateInstrumentationInfo(i, flags); 6123 } 6124 } 6125 6126 @Override 6127 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 6128 int flags) { 6129 ArrayList<InstrumentationInfo> finalList = 6130 new ArrayList<InstrumentationInfo>(); 6131 6132 // reader 6133 synchronized (mPackages) { 6134 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6135 while (i.hasNext()) { 6136 final PackageParser.Instrumentation p = i.next(); 6137 if (targetPackage == null 6138 || targetPackage.equals(p.info.targetPackage)) { 6139 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6140 flags); 6141 if (ii != null) { 6142 finalList.add(ii); 6143 } 6144 } 6145 } 6146 } 6147 6148 return finalList; 6149 } 6150 6151 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6152 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6153 if (overlays == null) { 6154 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6155 return; 6156 } 6157 for (PackageParser.Package opkg : overlays.values()) { 6158 // Not much to do if idmap fails: we already logged the error 6159 // and we certainly don't want to abort installation of pkg simply 6160 // because an overlay didn't fit properly. For these reasons, 6161 // ignore the return value of createIdmapForPackagePairLI. 6162 createIdmapForPackagePairLI(pkg, opkg); 6163 } 6164 } 6165 6166 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6167 PackageParser.Package opkg) { 6168 if (!opkg.mTrustedOverlay) { 6169 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6170 opkg.baseCodePath + ": overlay not trusted"); 6171 return false; 6172 } 6173 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6174 if (overlaySet == null) { 6175 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6176 opkg.baseCodePath + " but target package has no known overlays"); 6177 return false; 6178 } 6179 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6180 // TODO: generate idmap for split APKs 6181 try { 6182 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6183 } catch (InstallerException e) { 6184 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6185 + opkg.baseCodePath); 6186 return false; 6187 } 6188 PackageParser.Package[] overlayArray = 6189 overlaySet.values().toArray(new PackageParser.Package[0]); 6190 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6191 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6192 return p1.mOverlayPriority - p2.mOverlayPriority; 6193 } 6194 }; 6195 Arrays.sort(overlayArray, cmp); 6196 6197 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6198 int i = 0; 6199 for (PackageParser.Package p : overlayArray) { 6200 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6201 } 6202 return true; 6203 } 6204 6205 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6207 try { 6208 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6209 } finally { 6210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6211 } 6212 } 6213 6214 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6215 final File[] files = dir.listFiles(); 6216 if (ArrayUtils.isEmpty(files)) { 6217 Log.d(TAG, "No files in app dir " + dir); 6218 return; 6219 } 6220 6221 if (DEBUG_PACKAGE_SCANNING) { 6222 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6223 + " flags=0x" + Integer.toHexString(parseFlags)); 6224 } 6225 6226 for (File file : files) { 6227 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6228 && !PackageInstallerService.isStageName(file.getName()); 6229 if (!isPackage) { 6230 // Ignore entries which are not packages 6231 continue; 6232 } 6233 try { 6234 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6235 scanFlags, currentTime, null); 6236 } catch (PackageManagerException e) { 6237 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6238 6239 // Delete invalid userdata apps 6240 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6241 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6242 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6243 removeCodePathLI(file); 6244 } 6245 } 6246 } 6247 } 6248 6249 private static File getSettingsProblemFile() { 6250 File dataDir = Environment.getDataDirectory(); 6251 File systemDir = new File(dataDir, "system"); 6252 File fname = new File(systemDir, "uiderrors.txt"); 6253 return fname; 6254 } 6255 6256 static void reportSettingsProblem(int priority, String msg) { 6257 logCriticalInfo(priority, msg); 6258 } 6259 6260 static void logCriticalInfo(int priority, String msg) { 6261 Slog.println(priority, TAG, msg); 6262 EventLogTags.writePmCriticalInfo(msg); 6263 try { 6264 File fname = getSettingsProblemFile(); 6265 FileOutputStream out = new FileOutputStream(fname, true); 6266 PrintWriter pw = new FastPrintWriter(out); 6267 SimpleDateFormat formatter = new SimpleDateFormat(); 6268 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6269 pw.println(dateString + ": " + msg); 6270 pw.close(); 6271 FileUtils.setPermissions( 6272 fname.toString(), 6273 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6274 -1, -1); 6275 } catch (java.io.IOException e) { 6276 } 6277 } 6278 6279 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6280 int parseFlags) throws PackageManagerException { 6281 if (ps != null 6282 && ps.codePath.equals(srcFile) 6283 && ps.timeStamp == srcFile.lastModified() 6284 && !isCompatSignatureUpdateNeeded(pkg) 6285 && !isRecoverSignatureUpdateNeeded(pkg)) { 6286 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6287 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6288 ArraySet<PublicKey> signingKs; 6289 synchronized (mPackages) { 6290 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6291 } 6292 if (ps.signatures.mSignatures != null 6293 && ps.signatures.mSignatures.length != 0 6294 && signingKs != null) { 6295 // Optimization: reuse the existing cached certificates 6296 // if the package appears to be unchanged. 6297 pkg.mSignatures = ps.signatures.mSignatures; 6298 pkg.mSigningKeys = signingKs; 6299 return; 6300 } 6301 6302 Slog.w(TAG, "PackageSetting for " + ps.name 6303 + " is missing signatures. Collecting certs again to recover them."); 6304 } else { 6305 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6306 } 6307 6308 try { 6309 PackageParser.collectCertificates(pkg, parseFlags); 6310 } catch (PackageParserException e) { 6311 throw PackageManagerException.from(e); 6312 } 6313 } 6314 6315 /** 6316 * Traces a package scan. 6317 * @see #scanPackageLI(File, int, int, long, UserHandle) 6318 */ 6319 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6320 long currentTime, UserHandle user) throws PackageManagerException { 6321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6322 try { 6323 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6324 } finally { 6325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6326 } 6327 } 6328 6329 /** 6330 * Scans a package and returns the newly parsed package. 6331 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6332 */ 6333 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6334 long currentTime, UserHandle user) throws PackageManagerException { 6335 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6336 parseFlags |= mDefParseFlags; 6337 PackageParser pp = new PackageParser(); 6338 pp.setSeparateProcesses(mSeparateProcesses); 6339 pp.setOnlyCoreApps(mOnlyCore); 6340 pp.setDisplayMetrics(mMetrics); 6341 6342 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6343 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6344 } 6345 6346 final PackageParser.Package pkg; 6347 try { 6348 pkg = pp.parsePackage(scanFile, parseFlags); 6349 } catch (PackageParserException e) { 6350 throw PackageManagerException.from(e); 6351 } 6352 6353 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6354 } 6355 6356 /** 6357 * Scans a package and returns the newly parsed package. 6358 * @throws PackageManagerException on a parse error. 6359 */ 6360 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6361 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6362 throws PackageManagerException { 6363 // If the package has children and this is the first dive in the function 6364 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6365 // packages (parent and children) would be successfully scanned before the 6366 // actual scan since scanning mutates internal state and we want to atomically 6367 // install the package and its children. 6368 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6369 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6370 scanFlags |= SCAN_CHECK_ONLY; 6371 } 6372 } else { 6373 scanFlags &= ~SCAN_CHECK_ONLY; 6374 } 6375 6376 // Scan the parent 6377 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6378 scanFlags, currentTime, user); 6379 6380 // Scan the children 6381 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6382 for (int i = 0; i < childCount; i++) { 6383 PackageParser.Package childPackage = pkg.childPackages.get(i); 6384 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6385 currentTime, user); 6386 } 6387 6388 6389 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6390 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6391 } 6392 6393 return scannedPkg; 6394 } 6395 6396 /** 6397 * Scans a package and returns the newly parsed package. 6398 * @throws PackageManagerException on a parse error. 6399 */ 6400 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6401 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6402 throws PackageManagerException { 6403 PackageSetting ps = null; 6404 PackageSetting updatedPkg; 6405 // reader 6406 synchronized (mPackages) { 6407 // Look to see if we already know about this package. 6408 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6409 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6410 // This package has been renamed to its original name. Let's 6411 // use that. 6412 ps = mSettings.peekPackageLPr(oldName); 6413 } 6414 // If there was no original package, see one for the real package name. 6415 if (ps == null) { 6416 ps = mSettings.peekPackageLPr(pkg.packageName); 6417 } 6418 // Check to see if this package could be hiding/updating a system 6419 // package. Must look for it either under the original or real 6420 // package name depending on our state. 6421 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6422 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6423 6424 // If this is a package we don't know about on the system partition, we 6425 // may need to remove disabled child packages on the system partition 6426 // or may need to not add child packages if the parent apk is updated 6427 // on the data partition and no longer defines this child package. 6428 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6429 // If this is a parent package for an updated system app and this system 6430 // app got an OTA update which no longer defines some of the child packages 6431 // we have to prune them from the disabled system packages. 6432 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6433 if (disabledPs != null) { 6434 final int scannedChildCount = (pkg.childPackages != null) 6435 ? pkg.childPackages.size() : 0; 6436 final int disabledChildCount = disabledPs.childPackageNames != null 6437 ? disabledPs.childPackageNames.size() : 0; 6438 for (int i = 0; i < disabledChildCount; i++) { 6439 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6440 boolean disabledPackageAvailable = false; 6441 for (int j = 0; j < scannedChildCount; j++) { 6442 PackageParser.Package childPkg = pkg.childPackages.get(j); 6443 if (childPkg.packageName.equals(disabledChildPackageName)) { 6444 disabledPackageAvailable = true; 6445 break; 6446 } 6447 } 6448 if (!disabledPackageAvailable) { 6449 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6450 } 6451 } 6452 } 6453 } 6454 } 6455 6456 boolean updatedPkgBetter = false; 6457 // First check if this is a system package that may involve an update 6458 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6459 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6460 // it needs to drop FLAG_PRIVILEGED. 6461 if (locationIsPrivileged(scanFile)) { 6462 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6463 } else { 6464 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6465 } 6466 6467 if (ps != null && !ps.codePath.equals(scanFile)) { 6468 // The path has changed from what was last scanned... check the 6469 // version of the new path against what we have stored to determine 6470 // what to do. 6471 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6472 if (pkg.mVersionCode <= ps.versionCode) { 6473 // The system package has been updated and the code path does not match 6474 // Ignore entry. Skip it. 6475 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6476 + " ignored: updated version " + ps.versionCode 6477 + " better than this " + pkg.mVersionCode); 6478 if (!updatedPkg.codePath.equals(scanFile)) { 6479 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6480 + ps.name + " changing from " + updatedPkg.codePathString 6481 + " to " + scanFile); 6482 updatedPkg.codePath = scanFile; 6483 updatedPkg.codePathString = scanFile.toString(); 6484 updatedPkg.resourcePath = scanFile; 6485 updatedPkg.resourcePathString = scanFile.toString(); 6486 } 6487 updatedPkg.pkg = pkg; 6488 updatedPkg.versionCode = pkg.mVersionCode; 6489 6490 // Update the disabled system child packages to point to the package too. 6491 final int childCount = updatedPkg.childPackageNames != null 6492 ? updatedPkg.childPackageNames.size() : 0; 6493 for (int i = 0; i < childCount; i++) { 6494 String childPackageName = updatedPkg.childPackageNames.get(i); 6495 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6496 childPackageName); 6497 if (updatedChildPkg != null) { 6498 updatedChildPkg.pkg = pkg; 6499 updatedChildPkg.versionCode = pkg.mVersionCode; 6500 } 6501 } 6502 6503 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6504 + scanFile + " ignored: updated version " + ps.versionCode 6505 + " better than this " + pkg.mVersionCode); 6506 } else { 6507 // The current app on the system partition is better than 6508 // what we have updated to on the data partition; switch 6509 // back to the system partition version. 6510 // At this point, its safely assumed that package installation for 6511 // apps in system partition will go through. If not there won't be a working 6512 // version of the app 6513 // writer 6514 synchronized (mPackages) { 6515 // Just remove the loaded entries from package lists. 6516 mPackages.remove(ps.name); 6517 } 6518 6519 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6520 + " reverting from " + ps.codePathString 6521 + ": new version " + pkg.mVersionCode 6522 + " better than installed " + ps.versionCode); 6523 6524 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6525 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6526 synchronized (mInstallLock) { 6527 args.cleanUpResourcesLI(); 6528 } 6529 synchronized (mPackages) { 6530 mSettings.enableSystemPackageLPw(ps.name); 6531 } 6532 updatedPkgBetter = true; 6533 } 6534 } 6535 } 6536 6537 if (updatedPkg != null) { 6538 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6539 // initially 6540 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6541 6542 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6543 // flag set initially 6544 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6545 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6546 } 6547 } 6548 6549 // Verify certificates against what was last scanned 6550 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6551 6552 /* 6553 * A new system app appeared, but we already had a non-system one of the 6554 * same name installed earlier. 6555 */ 6556 boolean shouldHideSystemApp = false; 6557 if (updatedPkg == null && ps != null 6558 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6559 /* 6560 * Check to make sure the signatures match first. If they don't, 6561 * wipe the installed application and its data. 6562 */ 6563 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6564 != PackageManager.SIGNATURE_MATCH) { 6565 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6566 + " signatures don't match existing userdata copy; removing"); 6567 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false, null); 6568 ps = null; 6569 } else { 6570 /* 6571 * If the newly-added system app is an older version than the 6572 * already installed version, hide it. It will be scanned later 6573 * and re-added like an update. 6574 */ 6575 if (pkg.mVersionCode <= ps.versionCode) { 6576 shouldHideSystemApp = true; 6577 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6578 + " but new version " + pkg.mVersionCode + " better than installed " 6579 + ps.versionCode + "; hiding system"); 6580 } else { 6581 /* 6582 * The newly found system app is a newer version that the 6583 * one previously installed. Simply remove the 6584 * already-installed application and replace it with our own 6585 * while keeping the application data. 6586 */ 6587 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6588 + " reverting from " + ps.codePathString + ": new version " 6589 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6590 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6591 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6592 synchronized (mInstallLock) { 6593 args.cleanUpResourcesLI(); 6594 } 6595 } 6596 } 6597 } 6598 6599 // The apk is forward locked (not public) if its code and resources 6600 // are kept in different files. (except for app in either system or 6601 // vendor path). 6602 // TODO grab this value from PackageSettings 6603 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6604 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6605 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6606 } 6607 } 6608 6609 // TODO: extend to support forward-locked splits 6610 String resourcePath = null; 6611 String baseResourcePath = null; 6612 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6613 if (ps != null && ps.resourcePathString != null) { 6614 resourcePath = ps.resourcePathString; 6615 baseResourcePath = ps.resourcePathString; 6616 } else { 6617 // Should not happen at all. Just log an error. 6618 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6619 } 6620 } else { 6621 resourcePath = pkg.codePath; 6622 baseResourcePath = pkg.baseCodePath; 6623 } 6624 6625 // Set application objects path explicitly. 6626 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6627 pkg.setApplicationInfoCodePath(pkg.codePath); 6628 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6629 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6630 pkg.setApplicationInfoResourcePath(resourcePath); 6631 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6632 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6633 6634 // Note that we invoke the following method only if we are about to unpack an application 6635 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6636 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6637 6638 /* 6639 * If the system app should be overridden by a previously installed 6640 * data, hide the system app now and let the /data/app scan pick it up 6641 * again. 6642 */ 6643 if (shouldHideSystemApp) { 6644 synchronized (mPackages) { 6645 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6646 } 6647 } 6648 6649 return scannedPkg; 6650 } 6651 6652 private static String fixProcessName(String defProcessName, 6653 String processName, int uid) { 6654 if (processName == null) { 6655 return defProcessName; 6656 } 6657 return processName; 6658 } 6659 6660 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6661 throws PackageManagerException { 6662 if (pkgSetting.signatures.mSignatures != null) { 6663 // Already existing package. Make sure signatures match 6664 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6665 == PackageManager.SIGNATURE_MATCH; 6666 if (!match) { 6667 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6668 == PackageManager.SIGNATURE_MATCH; 6669 } 6670 if (!match) { 6671 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6672 == PackageManager.SIGNATURE_MATCH; 6673 } 6674 if (!match) { 6675 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6676 + pkg.packageName + " signatures do not match the " 6677 + "previously installed version; ignoring!"); 6678 } 6679 } 6680 6681 // Check for shared user signatures 6682 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6683 // Already existing package. Make sure signatures match 6684 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6685 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6686 if (!match) { 6687 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6688 == PackageManager.SIGNATURE_MATCH; 6689 } 6690 if (!match) { 6691 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6692 == PackageManager.SIGNATURE_MATCH; 6693 } 6694 if (!match) { 6695 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6696 "Package " + pkg.packageName 6697 + " has no signatures that match those in shared user " 6698 + pkgSetting.sharedUser.name + "; ignoring!"); 6699 } 6700 } 6701 } 6702 6703 /** 6704 * Enforces that only the system UID or root's UID can call a method exposed 6705 * via Binder. 6706 * 6707 * @param message used as message if SecurityException is thrown 6708 * @throws SecurityException if the caller is not system or root 6709 */ 6710 private static final void enforceSystemOrRoot(String message) { 6711 final int uid = Binder.getCallingUid(); 6712 if (uid != Process.SYSTEM_UID && uid != 0) { 6713 throw new SecurityException(message); 6714 } 6715 } 6716 6717 @Override 6718 public void performFstrimIfNeeded() { 6719 enforceSystemOrRoot("Only the system can request fstrim"); 6720 6721 // Before everything else, see whether we need to fstrim. 6722 try { 6723 IMountService ms = PackageHelper.getMountService(); 6724 if (ms != null) { 6725 final boolean isUpgrade = isUpgrade(); 6726 boolean doTrim = isUpgrade; 6727 if (doTrim) { 6728 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6729 } else { 6730 final long interval = android.provider.Settings.Global.getLong( 6731 mContext.getContentResolver(), 6732 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6733 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6734 if (interval > 0) { 6735 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6736 if (timeSinceLast > interval) { 6737 doTrim = true; 6738 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6739 + "; running immediately"); 6740 } 6741 } 6742 } 6743 if (doTrim) { 6744 if (!isFirstBoot()) { 6745 try { 6746 ActivityManagerNative.getDefault().showBootMessage( 6747 mContext.getResources().getString( 6748 R.string.android_upgrading_fstrim), true); 6749 } catch (RemoteException e) { 6750 } 6751 } 6752 ms.runMaintenance(); 6753 } 6754 } else { 6755 Slog.e(TAG, "Mount service unavailable!"); 6756 } 6757 } catch (RemoteException e) { 6758 // Can't happen; MountService is local 6759 } 6760 } 6761 6762 @Override 6763 public void extractPackagesIfNeeded() { 6764 enforceSystemOrRoot("Only the system can request package extraction"); 6765 6766 // Extract pacakges only if profile-guided compilation is enabled because 6767 // otherwise BackgroundDexOptService will not dexopt them later. 6768 if (mUseJitProfiles) { 6769 ArraySet<String> pkgs = getOptimizablePackages(); 6770 if (pkgs != null) { 6771 for (String pkg : pkgs) { 6772 performDexOpt(pkg, null /* instructionSet */, false /* useProfiles */, 6773 true /* extractOnly */, false /* force */); 6774 } 6775 } 6776 } 6777 } 6778 6779 private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) { 6780 List<ResolveInfo> ris = null; 6781 try { 6782 ris = AppGlobals.getPackageManager().queryIntentReceivers( 6783 intent, null, 0, userId); 6784 } catch (RemoteException e) { 6785 } 6786 ArraySet<String> pkgNames = new ArraySet<String>(); 6787 if (ris != null) { 6788 for (ResolveInfo ri : ris) { 6789 pkgNames.add(ri.activityInfo.packageName); 6790 } 6791 } 6792 return pkgNames; 6793 } 6794 6795 @Override 6796 public void notifyPackageUse(String packageName) { 6797 synchronized (mPackages) { 6798 PackageParser.Package p = mPackages.get(packageName); 6799 if (p == null) { 6800 return; 6801 } 6802 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6803 } 6804 } 6805 6806 // TODO: this is not used nor needed. Delete it. 6807 @Override 6808 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6809 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6810 false /* extractOnly */, false /* force */); 6811 } 6812 6813 @Override 6814 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6815 boolean extractOnly, boolean force) { 6816 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6817 } 6818 6819 private boolean performDexOptTraced(String packageName, String instructionSet, 6820 boolean useProfiles, boolean extractOnly, boolean force) { 6821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6822 try { 6823 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6824 force); 6825 } finally { 6826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6827 } 6828 } 6829 6830 private boolean performDexOptInternal(String packageName, String instructionSet, 6831 boolean useProfiles, boolean extractOnly, boolean force) { 6832 PackageParser.Package p; 6833 final String targetInstructionSet; 6834 synchronized (mPackages) { 6835 p = mPackages.get(packageName); 6836 if (p == null) { 6837 return false; 6838 } 6839 mPackageUsage.write(false); 6840 6841 targetInstructionSet = instructionSet != null ? instructionSet : 6842 getPrimaryInstructionSet(p.applicationInfo); 6843 if (!force && !useProfiles && p.mDexOptPerformed.contains(targetInstructionSet)) { 6844 // Skip only if we do not use profiles since they might trigger a recompilation. 6845 return false; 6846 } 6847 } 6848 long callingId = Binder.clearCallingIdentity(); 6849 try { 6850 synchronized (mInstallLock) { 6851 final String[] instructionSets = new String[] { targetInstructionSet }; 6852 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6853 useProfiles, extractOnly, force); 6854 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6855 } 6856 } finally { 6857 Binder.restoreCallingIdentity(callingId); 6858 } 6859 } 6860 6861 public ArraySet<String> getOptimizablePackages() { 6862 ArraySet<String> pkgs = new ArraySet<String>(); 6863 synchronized (mPackages) { 6864 for (PackageParser.Package p : mPackages.values()) { 6865 if (PackageDexOptimizer.canOptimizePackage(p)) { 6866 pkgs.add(p.packageName); 6867 } 6868 } 6869 } 6870 return pkgs; 6871 } 6872 6873 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6874 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6875 // Select the dex optimizer based on the force parameter. 6876 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6877 // allocate an object here. 6878 PackageDexOptimizer pdo = force 6879 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 6880 : mPackageDexOptimizer; 6881 6882 // Optimize all dependencies first. Note: we ignore the return value and march on 6883 // on errors. 6884 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 6885 if (!deps.isEmpty()) { 6886 for (PackageParser.Package depPackage : deps) { 6887 // TODO: Analyze and investigate if we (should) profile libraries. 6888 // Currently this will do a full compilation of the library. 6889 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 6890 false /* extractOnly */); 6891 } 6892 } 6893 6894 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 6895 } 6896 6897 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 6898 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 6899 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 6900 Set<String> collectedNames = new HashSet<>(); 6901 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 6902 6903 retValue.remove(p); 6904 6905 return retValue; 6906 } else { 6907 return Collections.emptyList(); 6908 } 6909 } 6910 6911 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 6912 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6913 if (!collectedNames.contains(p.packageName)) { 6914 collectedNames.add(p.packageName); 6915 collected.add(p); 6916 6917 if (p.usesLibraries != null) { 6918 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 6919 } 6920 if (p.usesOptionalLibraries != null) { 6921 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 6922 collectedNames); 6923 } 6924 } 6925 } 6926 6927 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 6928 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 6929 for (String libName : libs) { 6930 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 6931 if (libPkg != null) { 6932 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 6933 } 6934 } 6935 } 6936 6937 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 6938 synchronized (mPackages) { 6939 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 6940 if (lib != null && lib.apk != null) { 6941 return mPackages.get(lib.apk); 6942 } 6943 } 6944 return null; 6945 } 6946 6947 public void shutdown() { 6948 mPackageUsage.write(true); 6949 } 6950 6951 @Override 6952 public void forceDexOpt(String packageName) { 6953 enforceSystemOrRoot("forceDexOpt"); 6954 6955 PackageParser.Package pkg; 6956 synchronized (mPackages) { 6957 pkg = mPackages.get(packageName); 6958 if (pkg == null) { 6959 throw new IllegalArgumentException("Unknown package: " + packageName); 6960 } 6961 } 6962 6963 synchronized (mInstallLock) { 6964 final String[] instructionSets = new String[] { 6965 getPrimaryInstructionSet(pkg.applicationInfo) }; 6966 6967 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6968 6969 // Whoever is calling forceDexOpt wants a fully compiled package. 6970 // Don't use profiles since that may cause compilation to be skipped. 6971 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 6972 false /* useProfiles */, false /* extractOnly */, true /* force */); 6973 6974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6975 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 6976 throw new IllegalStateException("Failed to dexopt: " + res); 6977 } 6978 } 6979 } 6980 6981 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 6982 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 6983 Slog.w(TAG, "Unable to update from " + oldPkg.name 6984 + " to " + newPkg.packageName 6985 + ": old package not in system partition"); 6986 return false; 6987 } else if (mPackages.get(oldPkg.name) != null) { 6988 Slog.w(TAG, "Unable to update from " + oldPkg.name 6989 + " to " + newPkg.packageName 6990 + ": old package still exists"); 6991 return false; 6992 } 6993 return true; 6994 } 6995 6996 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 6997 // TODO: triage flags as part of 26466827 6998 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 6999 7000 boolean res = true; 7001 final int[] users = sUserManager.getUserIds(); 7002 for (int user : users) { 7003 try { 7004 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7005 } catch (InstallerException e) { 7006 Slog.w(TAG, "Failed to delete data directory", e); 7007 res = false; 7008 } 7009 } 7010 return res; 7011 } 7012 7013 void removeCodePathLI(File codePath) { 7014 if (codePath.isDirectory()) { 7015 try { 7016 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7017 } catch (InstallerException e) { 7018 Slog.w(TAG, "Failed to remove code path", e); 7019 } 7020 } else { 7021 codePath.delete(); 7022 } 7023 } 7024 7025 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7026 try { 7027 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7028 } catch (InstallerException e) { 7029 Slog.w(TAG, "Failed to destroy app data", e); 7030 } 7031 } 7032 7033 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7034 int appId, String seinfo) { 7035 try { 7036 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7037 } catch (InstallerException e) { 7038 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7039 } 7040 } 7041 7042 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7043 final PackageParser.Package pkg; 7044 synchronized (mPackages) { 7045 pkg = mPackages.get(packageName); 7046 } 7047 if (pkg == null) { 7048 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7049 return; 7050 } 7051 deleteCodeCacheDirsLI(pkg); 7052 } 7053 7054 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7055 // TODO: triage flags as part of 26466827 7056 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7057 7058 int[] users = sUserManager.getUserIds(); 7059 int res = 0; 7060 for (int user : users) { 7061 // Remove the parent code cache 7062 try { 7063 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7064 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7065 } catch (InstallerException e) { 7066 Slog.w(TAG, "Failed to delete code cache directory", e); 7067 } 7068 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7069 for (int i = 0; i < childCount; i++) { 7070 PackageParser.Package childPkg = pkg.childPackages.get(i); 7071 // Remove the child code cache 7072 try { 7073 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7074 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7075 } catch (InstallerException e) { 7076 Slog.w(TAG, "Failed to delete code cache directory", e); 7077 } 7078 } 7079 } 7080 } 7081 7082 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7083 long lastUpdateTime) { 7084 // Set parent install/update time 7085 PackageSetting ps = (PackageSetting) pkg.mExtras; 7086 if (ps != null) { 7087 ps.firstInstallTime = firstInstallTime; 7088 ps.lastUpdateTime = lastUpdateTime; 7089 } 7090 // Set children install/update time 7091 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7092 for (int i = 0; i < childCount; i++) { 7093 PackageParser.Package childPkg = pkg.childPackages.get(i); 7094 ps = (PackageSetting) childPkg.mExtras; 7095 if (ps != null) { 7096 ps.firstInstallTime = firstInstallTime; 7097 ps.lastUpdateTime = lastUpdateTime; 7098 } 7099 } 7100 } 7101 7102 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7103 PackageParser.Package changingLib) { 7104 if (file.path != null) { 7105 usesLibraryFiles.add(file.path); 7106 return; 7107 } 7108 PackageParser.Package p = mPackages.get(file.apk); 7109 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7110 // If we are doing this while in the middle of updating a library apk, 7111 // then we need to make sure to use that new apk for determining the 7112 // dependencies here. (We haven't yet finished committing the new apk 7113 // to the package manager state.) 7114 if (p == null || p.packageName.equals(changingLib.packageName)) { 7115 p = changingLib; 7116 } 7117 } 7118 if (p != null) { 7119 usesLibraryFiles.addAll(p.getAllCodePaths()); 7120 } 7121 } 7122 7123 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7124 PackageParser.Package changingLib) throws PackageManagerException { 7125 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7126 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7127 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7128 for (int i=0; i<N; i++) { 7129 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7130 if (file == null) { 7131 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7132 "Package " + pkg.packageName + " requires unavailable shared library " 7133 + pkg.usesLibraries.get(i) + "; failing!"); 7134 } 7135 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7136 } 7137 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7138 for (int i=0; i<N; i++) { 7139 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7140 if (file == null) { 7141 Slog.w(TAG, "Package " + pkg.packageName 7142 + " desires unavailable shared library " 7143 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7144 } else { 7145 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7146 } 7147 } 7148 N = usesLibraryFiles.size(); 7149 if (N > 0) { 7150 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7151 } else { 7152 pkg.usesLibraryFiles = null; 7153 } 7154 } 7155 } 7156 7157 private static boolean hasString(List<String> list, List<String> which) { 7158 if (list == null) { 7159 return false; 7160 } 7161 for (int i=list.size()-1; i>=0; i--) { 7162 for (int j=which.size()-1; j>=0; j--) { 7163 if (which.get(j).equals(list.get(i))) { 7164 return true; 7165 } 7166 } 7167 } 7168 return false; 7169 } 7170 7171 private void updateAllSharedLibrariesLPw() { 7172 for (PackageParser.Package pkg : mPackages.values()) { 7173 try { 7174 updateSharedLibrariesLPw(pkg, null); 7175 } catch (PackageManagerException e) { 7176 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7177 } 7178 } 7179 } 7180 7181 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7182 PackageParser.Package changingPkg) { 7183 ArrayList<PackageParser.Package> res = null; 7184 for (PackageParser.Package pkg : mPackages.values()) { 7185 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7186 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7187 if (res == null) { 7188 res = new ArrayList<PackageParser.Package>(); 7189 } 7190 res.add(pkg); 7191 try { 7192 updateSharedLibrariesLPw(pkg, changingPkg); 7193 } catch (PackageManagerException e) { 7194 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7195 } 7196 } 7197 } 7198 return res; 7199 } 7200 7201 /** 7202 * Derive the value of the {@code cpuAbiOverride} based on the provided 7203 * value and an optional stored value from the package settings. 7204 */ 7205 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7206 String cpuAbiOverride = null; 7207 7208 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7209 cpuAbiOverride = null; 7210 } else if (abiOverride != null) { 7211 cpuAbiOverride = abiOverride; 7212 } else if (settings != null) { 7213 cpuAbiOverride = settings.cpuAbiOverrideString; 7214 } 7215 7216 return cpuAbiOverride; 7217 } 7218 7219 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7220 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7221 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7222 // If the package has children and this is the first dive in the function 7223 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7224 // whether all packages (parent and children) would be successfully scanned 7225 // before the actual scan since scanning mutates internal state and we want 7226 // to atomically install the package and its children. 7227 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7228 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7229 scanFlags |= SCAN_CHECK_ONLY; 7230 } 7231 } else { 7232 scanFlags &= ~SCAN_CHECK_ONLY; 7233 } 7234 7235 final PackageParser.Package scannedPkg; 7236 try { 7237 // Scan the parent 7238 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7239 // Scan the children 7240 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7241 for (int i = 0; i < childCount; i++) { 7242 PackageParser.Package childPkg = pkg.childPackages.get(i); 7243 scanPackageLI(childPkg, parseFlags, 7244 scanFlags, currentTime, user); 7245 } 7246 } finally { 7247 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7248 } 7249 7250 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7251 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7252 } 7253 7254 return scannedPkg; 7255 } 7256 7257 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7258 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7259 boolean success = false; 7260 try { 7261 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7262 currentTime, user); 7263 success = true; 7264 return res; 7265 } finally { 7266 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7267 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7268 } 7269 } 7270 } 7271 7272 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7273 int scanFlags, long currentTime, UserHandle user) 7274 throws PackageManagerException { 7275 final File scanFile = new File(pkg.codePath); 7276 if (pkg.applicationInfo.getCodePath() == null || 7277 pkg.applicationInfo.getResourcePath() == null) { 7278 // Bail out. The resource and code paths haven't been set. 7279 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7280 "Code and resource paths haven't been set correctly"); 7281 } 7282 7283 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7284 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7285 } else { 7286 // Only allow system apps to be flagged as core apps. 7287 pkg.coreApp = false; 7288 } 7289 7290 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7291 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7292 } 7293 7294 if (mCustomResolverComponentName != null && 7295 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7296 setUpCustomResolverActivity(pkg); 7297 } 7298 7299 if (pkg.packageName.equals("android")) { 7300 synchronized (mPackages) { 7301 if (mAndroidApplication != null) { 7302 Slog.w(TAG, "*************************************************"); 7303 Slog.w(TAG, "Core android package being redefined. Skipping."); 7304 Slog.w(TAG, " file=" + scanFile); 7305 Slog.w(TAG, "*************************************************"); 7306 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7307 "Core android package being redefined. Skipping."); 7308 } 7309 7310 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7311 // Set up information for our fall-back user intent resolution activity. 7312 mPlatformPackage = pkg; 7313 pkg.mVersionCode = mSdkVersion; 7314 mAndroidApplication = pkg.applicationInfo; 7315 7316 if (!mResolverReplaced) { 7317 mResolveActivity.applicationInfo = mAndroidApplication; 7318 mResolveActivity.name = ResolverActivity.class.getName(); 7319 mResolveActivity.packageName = mAndroidApplication.packageName; 7320 mResolveActivity.processName = "system:ui"; 7321 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7322 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7323 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7324 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7325 mResolveActivity.exported = true; 7326 mResolveActivity.enabled = true; 7327 mResolveInfo.activityInfo = mResolveActivity; 7328 mResolveInfo.priority = 0; 7329 mResolveInfo.preferredOrder = 0; 7330 mResolveInfo.match = 0; 7331 mResolveComponentName = new ComponentName( 7332 mAndroidApplication.packageName, mResolveActivity.name); 7333 } 7334 } 7335 } 7336 } 7337 7338 if (DEBUG_PACKAGE_SCANNING) { 7339 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7340 Log.d(TAG, "Scanning package " + pkg.packageName); 7341 } 7342 7343 synchronized (mPackages) { 7344 if (mPackages.containsKey(pkg.packageName) 7345 || mSharedLibraries.containsKey(pkg.packageName)) { 7346 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7347 "Application package " + pkg.packageName 7348 + " already installed. Skipping duplicate."); 7349 } 7350 7351 // If we're only installing presumed-existing packages, require that the 7352 // scanned APK is both already known and at the path previously established 7353 // for it. Previously unknown packages we pick up normally, but if we have an 7354 // a priori expectation about this package's install presence, enforce it. 7355 // With a singular exception for new system packages. When an OTA contains 7356 // a new system package, we allow the codepath to change from a system location 7357 // to the user-installed location. If we don't allow this change, any newer, 7358 // user-installed version of the application will be ignored. 7359 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7360 if (mExpectingBetter.containsKey(pkg.packageName)) { 7361 logCriticalInfo(Log.WARN, 7362 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7363 } else { 7364 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7365 if (known != null) { 7366 if (DEBUG_PACKAGE_SCANNING) { 7367 Log.d(TAG, "Examining " + pkg.codePath 7368 + " and requiring known paths " + known.codePathString 7369 + " & " + known.resourcePathString); 7370 } 7371 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7372 || !pkg.applicationInfo.getResourcePath().equals( 7373 known.resourcePathString)) { 7374 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7375 "Application package " + pkg.packageName 7376 + " found at " + pkg.applicationInfo.getCodePath() 7377 + " but expected at " + known.codePathString 7378 + "; ignoring."); 7379 } 7380 } 7381 } 7382 } 7383 } 7384 7385 // Initialize package source and resource directories 7386 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7387 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7388 7389 SharedUserSetting suid = null; 7390 PackageSetting pkgSetting = null; 7391 7392 if (!isSystemApp(pkg)) { 7393 // Only system apps can use these features. 7394 pkg.mOriginalPackages = null; 7395 pkg.mRealPackage = null; 7396 pkg.mAdoptPermissions = null; 7397 } 7398 7399 // Getting the package setting may have a side-effect, so if we 7400 // are only checking if scan would succeed, stash a copy of the 7401 // old setting to restore at the end. 7402 PackageSetting nonMutatedPs = null; 7403 7404 // writer 7405 synchronized (mPackages) { 7406 if (pkg.mSharedUserId != null) { 7407 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7408 if (suid == null) { 7409 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7410 "Creating application package " + pkg.packageName 7411 + " for shared user failed"); 7412 } 7413 if (DEBUG_PACKAGE_SCANNING) { 7414 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7415 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7416 + "): packages=" + suid.packages); 7417 } 7418 } 7419 7420 // Check if we are renaming from an original package name. 7421 PackageSetting origPackage = null; 7422 String realName = null; 7423 if (pkg.mOriginalPackages != null) { 7424 // This package may need to be renamed to a previously 7425 // installed name. Let's check on that... 7426 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7427 if (pkg.mOriginalPackages.contains(renamed)) { 7428 // This package had originally been installed as the 7429 // original name, and we have already taken care of 7430 // transitioning to the new one. Just update the new 7431 // one to continue using the old name. 7432 realName = pkg.mRealPackage; 7433 if (!pkg.packageName.equals(renamed)) { 7434 // Callers into this function may have already taken 7435 // care of renaming the package; only do it here if 7436 // it is not already done. 7437 pkg.setPackageName(renamed); 7438 } 7439 7440 } else { 7441 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7442 if ((origPackage = mSettings.peekPackageLPr( 7443 pkg.mOriginalPackages.get(i))) != null) { 7444 // We do have the package already installed under its 7445 // original name... should we use it? 7446 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7447 // New package is not compatible with original. 7448 origPackage = null; 7449 continue; 7450 } else if (origPackage.sharedUser != null) { 7451 // Make sure uid is compatible between packages. 7452 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7453 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7454 + " to " + pkg.packageName + ": old uid " 7455 + origPackage.sharedUser.name 7456 + " differs from " + pkg.mSharedUserId); 7457 origPackage = null; 7458 continue; 7459 } 7460 } else { 7461 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7462 + pkg.packageName + " to old name " + origPackage.name); 7463 } 7464 break; 7465 } 7466 } 7467 } 7468 } 7469 7470 if (mTransferedPackages.contains(pkg.packageName)) { 7471 Slog.w(TAG, "Package " + pkg.packageName 7472 + " was transferred to another, but its .apk remains"); 7473 } 7474 7475 // See comments in nonMutatedPs declaration 7476 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7477 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7478 if (foundPs != null) { 7479 nonMutatedPs = new PackageSetting(foundPs); 7480 } 7481 } 7482 7483 // Just create the setting, don't add it yet. For already existing packages 7484 // the PkgSetting exists already and doesn't have to be created. 7485 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7486 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7487 pkg.applicationInfo.primaryCpuAbi, 7488 pkg.applicationInfo.secondaryCpuAbi, 7489 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7490 user, false); 7491 if (pkgSetting == null) { 7492 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7493 "Creating application package " + pkg.packageName + " failed"); 7494 } 7495 7496 if (pkgSetting.origPackage != null) { 7497 // If we are first transitioning from an original package, 7498 // fix up the new package's name now. We need to do this after 7499 // looking up the package under its new name, so getPackageLP 7500 // can take care of fiddling things correctly. 7501 pkg.setPackageName(origPackage.name); 7502 7503 // File a report about this. 7504 String msg = "New package " + pkgSetting.realName 7505 + " renamed to replace old package " + pkgSetting.name; 7506 reportSettingsProblem(Log.WARN, msg); 7507 7508 // Make a note of it. 7509 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7510 mTransferedPackages.add(origPackage.name); 7511 } 7512 7513 // No longer need to retain this. 7514 pkgSetting.origPackage = null; 7515 } 7516 7517 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7518 // Make a note of it. 7519 mTransferedPackages.add(pkg.packageName); 7520 } 7521 7522 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7523 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7524 } 7525 7526 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7527 // Check all shared libraries and map to their actual file path. 7528 // We only do this here for apps not on a system dir, because those 7529 // are the only ones that can fail an install due to this. We 7530 // will take care of the system apps by updating all of their 7531 // library paths after the scan is done. 7532 updateSharedLibrariesLPw(pkg, null); 7533 } 7534 7535 if (mFoundPolicyFile) { 7536 SELinuxMMAC.assignSeinfoValue(pkg); 7537 } 7538 7539 pkg.applicationInfo.uid = pkgSetting.appId; 7540 pkg.mExtras = pkgSetting; 7541 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7542 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7543 // We just determined the app is signed correctly, so bring 7544 // over the latest parsed certs. 7545 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7546 } else { 7547 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7548 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7549 "Package " + pkg.packageName + " upgrade keys do not match the " 7550 + "previously installed version"); 7551 } else { 7552 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7553 String msg = "System package " + pkg.packageName 7554 + " signature changed; retaining data."; 7555 reportSettingsProblem(Log.WARN, msg); 7556 } 7557 } 7558 } else { 7559 try { 7560 verifySignaturesLP(pkgSetting, pkg); 7561 // We just determined the app is signed correctly, so bring 7562 // over the latest parsed certs. 7563 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7564 } catch (PackageManagerException e) { 7565 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7566 throw e; 7567 } 7568 // The signature has changed, but this package is in the system 7569 // image... let's recover! 7570 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7571 // However... if this package is part of a shared user, but it 7572 // doesn't match the signature of the shared user, let's fail. 7573 // What this means is that you can't change the signatures 7574 // associated with an overall shared user, which doesn't seem all 7575 // that unreasonable. 7576 if (pkgSetting.sharedUser != null) { 7577 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7578 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7579 throw new PackageManagerException( 7580 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7581 "Signature mismatch for shared user: " 7582 + pkgSetting.sharedUser); 7583 } 7584 } 7585 // File a report about this. 7586 String msg = "System package " + pkg.packageName 7587 + " signature changed; retaining data."; 7588 reportSettingsProblem(Log.WARN, msg); 7589 } 7590 } 7591 // Verify that this new package doesn't have any content providers 7592 // that conflict with existing packages. Only do this if the 7593 // package isn't already installed, since we don't want to break 7594 // things that are installed. 7595 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7596 final int N = pkg.providers.size(); 7597 int i; 7598 for (i=0; i<N; i++) { 7599 PackageParser.Provider p = pkg.providers.get(i); 7600 if (p.info.authority != null) { 7601 String names[] = p.info.authority.split(";"); 7602 for (int j = 0; j < names.length; j++) { 7603 if (mProvidersByAuthority.containsKey(names[j])) { 7604 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7605 final String otherPackageName = 7606 ((other != null && other.getComponentName() != null) ? 7607 other.getComponentName().getPackageName() : "?"); 7608 throw new PackageManagerException( 7609 INSTALL_FAILED_CONFLICTING_PROVIDER, 7610 "Can't install because provider name " + names[j] 7611 + " (in package " + pkg.applicationInfo.packageName 7612 + ") is already used by " + otherPackageName); 7613 } 7614 } 7615 } 7616 } 7617 } 7618 7619 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7620 // This package wants to adopt ownership of permissions from 7621 // another package. 7622 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7623 final String origName = pkg.mAdoptPermissions.get(i); 7624 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7625 if (orig != null) { 7626 if (verifyPackageUpdateLPr(orig, pkg)) { 7627 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7628 + pkg.packageName); 7629 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7630 } 7631 } 7632 } 7633 } 7634 } 7635 7636 final String pkgName = pkg.packageName; 7637 7638 final long scanFileTime = scanFile.lastModified(); 7639 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7640 pkg.applicationInfo.processName = fixProcessName( 7641 pkg.applicationInfo.packageName, 7642 pkg.applicationInfo.processName, 7643 pkg.applicationInfo.uid); 7644 7645 if (pkg != mPlatformPackage) { 7646 // Get all of our default paths setup 7647 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7648 } 7649 7650 final String path = scanFile.getPath(); 7651 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7652 7653 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7654 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7655 7656 // Some system apps still use directory structure for native libraries 7657 // in which case we might end up not detecting abi solely based on apk 7658 // structure. Try to detect abi based on directory structure. 7659 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7660 pkg.applicationInfo.primaryCpuAbi == null) { 7661 setBundledAppAbisAndRoots(pkg, pkgSetting); 7662 setNativeLibraryPaths(pkg); 7663 } 7664 7665 } else { 7666 if ((scanFlags & SCAN_MOVE) != 0) { 7667 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7668 // but we already have this packages package info in the PackageSetting. We just 7669 // use that and derive the native library path based on the new codepath. 7670 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7671 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7672 } 7673 7674 // Set native library paths again. For moves, the path will be updated based on the 7675 // ABIs we've determined above. For non-moves, the path will be updated based on the 7676 // ABIs we determined during compilation, but the path will depend on the final 7677 // package path (after the rename away from the stage path). 7678 setNativeLibraryPaths(pkg); 7679 } 7680 7681 // This is a special case for the "system" package, where the ABI is 7682 // dictated by the zygote configuration (and init.rc). We should keep track 7683 // of this ABI so that we can deal with "normal" applications that run under 7684 // the same UID correctly. 7685 if (mPlatformPackage == pkg) { 7686 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7687 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7688 } 7689 7690 // If there's a mismatch between the abi-override in the package setting 7691 // and the abiOverride specified for the install. Warn about this because we 7692 // would've already compiled the app without taking the package setting into 7693 // account. 7694 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7695 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7696 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7697 " for package " + pkg.packageName); 7698 } 7699 } 7700 7701 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7702 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7703 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7704 7705 // Copy the derived override back to the parsed package, so that we can 7706 // update the package settings accordingly. 7707 pkg.cpuAbiOverride = cpuAbiOverride; 7708 7709 if (DEBUG_ABI_SELECTION) { 7710 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7711 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7712 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7713 } 7714 7715 // Push the derived path down into PackageSettings so we know what to 7716 // clean up at uninstall time. 7717 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7718 7719 if (DEBUG_ABI_SELECTION) { 7720 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7721 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7722 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7723 } 7724 7725 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7726 // We don't do this here during boot because we can do it all 7727 // at once after scanning all existing packages. 7728 // 7729 // We also do this *before* we perform dexopt on this package, so that 7730 // we can avoid redundant dexopts, and also to make sure we've got the 7731 // code and package path correct. 7732 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7733 pkg, true /* boot complete */); 7734 } 7735 7736 if (mFactoryTest && pkg.requestedPermissions.contains( 7737 android.Manifest.permission.FACTORY_TEST)) { 7738 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7739 } 7740 7741 ArrayList<PackageParser.Package> clientLibPkgs = null; 7742 7743 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7744 if (nonMutatedPs != null) { 7745 synchronized (mPackages) { 7746 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7747 } 7748 } 7749 return pkg; 7750 } 7751 7752 // Only privileged apps and updated privileged apps can add child packages. 7753 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7754 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7755 throw new PackageManagerException("Only privileged apps and updated " 7756 + "privileged apps can add child packages. Ignoring package " 7757 + pkg.packageName); 7758 } 7759 final int childCount = pkg.childPackages.size(); 7760 for (int i = 0; i < childCount; i++) { 7761 PackageParser.Package childPkg = pkg.childPackages.get(i); 7762 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7763 childPkg.packageName)) { 7764 throw new PackageManagerException("Cannot override a child package of " 7765 + "another disabled system app. Ignoring package " + pkg.packageName); 7766 } 7767 } 7768 } 7769 7770 // writer 7771 synchronized (mPackages) { 7772 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7773 // Only system apps can add new shared libraries. 7774 if (pkg.libraryNames != null) { 7775 for (int i=0; i<pkg.libraryNames.size(); i++) { 7776 String name = pkg.libraryNames.get(i); 7777 boolean allowed = false; 7778 if (pkg.isUpdatedSystemApp()) { 7779 // New library entries can only be added through the 7780 // system image. This is important to get rid of a lot 7781 // of nasty edge cases: for example if we allowed a non- 7782 // system update of the app to add a library, then uninstalling 7783 // the update would make the library go away, and assumptions 7784 // we made such as through app install filtering would now 7785 // have allowed apps on the device which aren't compatible 7786 // with it. Better to just have the restriction here, be 7787 // conservative, and create many fewer cases that can negatively 7788 // impact the user experience. 7789 final PackageSetting sysPs = mSettings 7790 .getDisabledSystemPkgLPr(pkg.packageName); 7791 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7792 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7793 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7794 allowed = true; 7795 break; 7796 } 7797 } 7798 } 7799 } else { 7800 allowed = true; 7801 } 7802 if (allowed) { 7803 if (!mSharedLibraries.containsKey(name)) { 7804 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7805 } else if (!name.equals(pkg.packageName)) { 7806 Slog.w(TAG, "Package " + pkg.packageName + " library " 7807 + name + " already exists; skipping"); 7808 } 7809 } else { 7810 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7811 + name + " that is not declared on system image; skipping"); 7812 } 7813 } 7814 if ((scanFlags & SCAN_BOOTING) == 0) { 7815 // If we are not booting, we need to update any applications 7816 // that are clients of our shared library. If we are booting, 7817 // this will all be done once the scan is complete. 7818 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7819 } 7820 } 7821 } 7822 } 7823 7824 // Request the ActivityManager to kill the process(only for existing packages) 7825 // so that we do not end up in a confused state while the user is still using the older 7826 // version of the application while the new one gets installed. 7827 if ((scanFlags & SCAN_REPLACING) != 0) { 7828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7829 7830 killApplication(pkg.applicationInfo.packageName, 7831 pkg.applicationInfo.uid, "replace pkg"); 7832 7833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7834 } 7835 7836 // Also need to kill any apps that are dependent on the library. 7837 if (clientLibPkgs != null) { 7838 for (int i=0; i<clientLibPkgs.size(); i++) { 7839 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7840 killApplication(clientPkg.applicationInfo.packageName, 7841 clientPkg.applicationInfo.uid, "update lib"); 7842 } 7843 } 7844 7845 // Make sure we're not adding any bogus keyset info 7846 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7847 ksms.assertScannedPackageValid(pkg); 7848 7849 // writer 7850 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7851 7852 boolean createIdmapFailed = false; 7853 synchronized (mPackages) { 7854 // We don't expect installation to fail beyond this point 7855 7856 // Add the new setting to mSettings 7857 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7858 // Add the new setting to mPackages 7859 mPackages.put(pkg.applicationInfo.packageName, pkg); 7860 // Make sure we don't accidentally delete its data. 7861 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7862 while (iter.hasNext()) { 7863 PackageCleanItem item = iter.next(); 7864 if (pkgName.equals(item.packageName)) { 7865 iter.remove(); 7866 } 7867 } 7868 7869 // Take care of first install / last update times. 7870 if (currentTime != 0) { 7871 if (pkgSetting.firstInstallTime == 0) { 7872 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7873 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7874 pkgSetting.lastUpdateTime = currentTime; 7875 } 7876 } else if (pkgSetting.firstInstallTime == 0) { 7877 // We need *something*. Take time time stamp of the file. 7878 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 7879 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 7880 if (scanFileTime != pkgSetting.timeStamp) { 7881 // A package on the system image has changed; consider this 7882 // to be an update. 7883 pkgSetting.lastUpdateTime = scanFileTime; 7884 } 7885 } 7886 7887 // Add the package's KeySets to the global KeySetManagerService 7888 ksms.addScannedPackageLPw(pkg); 7889 7890 int N = pkg.providers.size(); 7891 StringBuilder r = null; 7892 int i; 7893 for (i=0; i<N; i++) { 7894 PackageParser.Provider p = pkg.providers.get(i); 7895 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 7896 p.info.processName, pkg.applicationInfo.uid); 7897 mProviders.addProvider(p); 7898 p.syncable = p.info.isSyncable; 7899 if (p.info.authority != null) { 7900 String names[] = p.info.authority.split(";"); 7901 p.info.authority = null; 7902 for (int j = 0; j < names.length; j++) { 7903 if (j == 1 && p.syncable) { 7904 // We only want the first authority for a provider to possibly be 7905 // syncable, so if we already added this provider using a different 7906 // authority clear the syncable flag. We copy the provider before 7907 // changing it because the mProviders object contains a reference 7908 // to a provider that we don't want to change. 7909 // Only do this for the second authority since the resulting provider 7910 // object can be the same for all future authorities for this provider. 7911 p = new PackageParser.Provider(p); 7912 p.syncable = false; 7913 } 7914 if (!mProvidersByAuthority.containsKey(names[j])) { 7915 mProvidersByAuthority.put(names[j], p); 7916 if (p.info.authority == null) { 7917 p.info.authority = names[j]; 7918 } else { 7919 p.info.authority = p.info.authority + ";" + names[j]; 7920 } 7921 if (DEBUG_PACKAGE_SCANNING) { 7922 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7923 Log.d(TAG, "Registered content provider: " + names[j] 7924 + ", className = " + p.info.name + ", isSyncable = " 7925 + p.info.isSyncable); 7926 } 7927 } else { 7928 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7929 Slog.w(TAG, "Skipping provider name " + names[j] + 7930 " (in package " + pkg.applicationInfo.packageName + 7931 "): name already used by " 7932 + ((other != null && other.getComponentName() != null) 7933 ? other.getComponentName().getPackageName() : "?")); 7934 } 7935 } 7936 } 7937 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7938 if (r == null) { 7939 r = new StringBuilder(256); 7940 } else { 7941 r.append(' '); 7942 } 7943 r.append(p.info.name); 7944 } 7945 } 7946 if (r != null) { 7947 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 7948 } 7949 7950 N = pkg.services.size(); 7951 r = null; 7952 for (i=0; i<N; i++) { 7953 PackageParser.Service s = pkg.services.get(i); 7954 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 7955 s.info.processName, pkg.applicationInfo.uid); 7956 mServices.addService(s); 7957 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7958 if (r == null) { 7959 r = new StringBuilder(256); 7960 } else { 7961 r.append(' '); 7962 } 7963 r.append(s.info.name); 7964 } 7965 } 7966 if (r != null) { 7967 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 7968 } 7969 7970 N = pkg.receivers.size(); 7971 r = null; 7972 for (i=0; i<N; i++) { 7973 PackageParser.Activity a = pkg.receivers.get(i); 7974 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7975 a.info.processName, pkg.applicationInfo.uid); 7976 mReceivers.addActivity(a, "receiver"); 7977 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7978 if (r == null) { 7979 r = new StringBuilder(256); 7980 } else { 7981 r.append(' '); 7982 } 7983 r.append(a.info.name); 7984 } 7985 } 7986 if (r != null) { 7987 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 7988 } 7989 7990 N = pkg.activities.size(); 7991 r = null; 7992 for (i=0; i<N; i++) { 7993 PackageParser.Activity a = pkg.activities.get(i); 7994 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 7995 a.info.processName, pkg.applicationInfo.uid); 7996 mActivities.addActivity(a, "activity"); 7997 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7998 if (r == null) { 7999 r = new StringBuilder(256); 8000 } else { 8001 r.append(' '); 8002 } 8003 r.append(a.info.name); 8004 } 8005 } 8006 if (r != null) { 8007 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8008 } 8009 8010 N = pkg.permissionGroups.size(); 8011 r = null; 8012 for (i=0; i<N; i++) { 8013 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8014 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8015 if (cur == null) { 8016 mPermissionGroups.put(pg.info.name, pg); 8017 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8018 if (r == null) { 8019 r = new StringBuilder(256); 8020 } else { 8021 r.append(' '); 8022 } 8023 r.append(pg.info.name); 8024 } 8025 } else { 8026 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8027 + pg.info.packageName + " ignored: original from " 8028 + cur.info.packageName); 8029 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8030 if (r == null) { 8031 r = new StringBuilder(256); 8032 } else { 8033 r.append(' '); 8034 } 8035 r.append("DUP:"); 8036 r.append(pg.info.name); 8037 } 8038 } 8039 } 8040 if (r != null) { 8041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8042 } 8043 8044 N = pkg.permissions.size(); 8045 r = null; 8046 for (i=0; i<N; i++) { 8047 PackageParser.Permission p = pkg.permissions.get(i); 8048 8049 // Assume by default that we did not install this permission into the system. 8050 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8051 8052 // Now that permission groups have a special meaning, we ignore permission 8053 // groups for legacy apps to prevent unexpected behavior. In particular, 8054 // permissions for one app being granted to someone just becase they happen 8055 // to be in a group defined by another app (before this had no implications). 8056 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8057 p.group = mPermissionGroups.get(p.info.group); 8058 // Warn for a permission in an unknown group. 8059 if (p.info.group != null && p.group == null) { 8060 Slog.w(TAG, "Permission " + p.info.name + " from package " 8061 + p.info.packageName + " in an unknown group " + p.info.group); 8062 } 8063 } 8064 8065 ArrayMap<String, BasePermission> permissionMap = 8066 p.tree ? mSettings.mPermissionTrees 8067 : mSettings.mPermissions; 8068 BasePermission bp = permissionMap.get(p.info.name); 8069 8070 // Allow system apps to redefine non-system permissions 8071 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8072 final boolean currentOwnerIsSystem = (bp.perm != null 8073 && isSystemApp(bp.perm.owner)); 8074 if (isSystemApp(p.owner)) { 8075 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8076 // It's a built-in permission and no owner, take ownership now 8077 bp.packageSetting = pkgSetting; 8078 bp.perm = p; 8079 bp.uid = pkg.applicationInfo.uid; 8080 bp.sourcePackage = p.info.packageName; 8081 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8082 } else if (!currentOwnerIsSystem) { 8083 String msg = "New decl " + p.owner + " of permission " 8084 + p.info.name + " is system; overriding " + bp.sourcePackage; 8085 reportSettingsProblem(Log.WARN, msg); 8086 bp = null; 8087 } 8088 } 8089 } 8090 8091 if (bp == null) { 8092 bp = new BasePermission(p.info.name, p.info.packageName, 8093 BasePermission.TYPE_NORMAL); 8094 permissionMap.put(p.info.name, bp); 8095 } 8096 8097 if (bp.perm == null) { 8098 if (bp.sourcePackage == null 8099 || bp.sourcePackage.equals(p.info.packageName)) { 8100 BasePermission tree = findPermissionTreeLP(p.info.name); 8101 if (tree == null 8102 || tree.sourcePackage.equals(p.info.packageName)) { 8103 bp.packageSetting = pkgSetting; 8104 bp.perm = p; 8105 bp.uid = pkg.applicationInfo.uid; 8106 bp.sourcePackage = p.info.packageName; 8107 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8108 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8109 if (r == null) { 8110 r = new StringBuilder(256); 8111 } else { 8112 r.append(' '); 8113 } 8114 r.append(p.info.name); 8115 } 8116 } else { 8117 Slog.w(TAG, "Permission " + p.info.name + " from package " 8118 + p.info.packageName + " ignored: base tree " 8119 + tree.name + " is from package " 8120 + tree.sourcePackage); 8121 } 8122 } else { 8123 Slog.w(TAG, "Permission " + p.info.name + " from package " 8124 + p.info.packageName + " ignored: original from " 8125 + bp.sourcePackage); 8126 } 8127 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8128 if (r == null) { 8129 r = new StringBuilder(256); 8130 } else { 8131 r.append(' '); 8132 } 8133 r.append("DUP:"); 8134 r.append(p.info.name); 8135 } 8136 if (bp.perm == p) { 8137 bp.protectionLevel = p.info.protectionLevel; 8138 } 8139 } 8140 8141 if (r != null) { 8142 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8143 } 8144 8145 N = pkg.instrumentation.size(); 8146 r = null; 8147 for (i=0; i<N; i++) { 8148 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8149 a.info.packageName = pkg.applicationInfo.packageName; 8150 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8151 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8152 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8153 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8154 a.info.dataDir = pkg.applicationInfo.dataDir; 8155 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8156 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8157 8158 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8159 // need other information about the application, like the ABI and what not ? 8160 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8161 mInstrumentation.put(a.getComponentName(), a); 8162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8163 if (r == null) { 8164 r = new StringBuilder(256); 8165 } else { 8166 r.append(' '); 8167 } 8168 r.append(a.info.name); 8169 } 8170 } 8171 if (r != null) { 8172 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8173 } 8174 8175 if (pkg.protectedBroadcasts != null) { 8176 N = pkg.protectedBroadcasts.size(); 8177 for (i=0; i<N; i++) { 8178 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8179 } 8180 } 8181 8182 pkgSetting.setTimeStamp(scanFileTime); 8183 8184 // Create idmap files for pairs of (packages, overlay packages). 8185 // Note: "android", ie framework-res.apk, is handled by native layers. 8186 if (pkg.mOverlayTarget != null) { 8187 // This is an overlay package. 8188 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8189 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8190 mOverlays.put(pkg.mOverlayTarget, 8191 new ArrayMap<String, PackageParser.Package>()); 8192 } 8193 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8194 map.put(pkg.packageName, pkg); 8195 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8196 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8197 createIdmapFailed = true; 8198 } 8199 } 8200 } else if (mOverlays.containsKey(pkg.packageName) && 8201 !pkg.packageName.equals("android")) { 8202 // This is a regular package, with one or more known overlay packages. 8203 createIdmapsForPackageLI(pkg); 8204 } 8205 } 8206 8207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8208 8209 if (createIdmapFailed) { 8210 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8211 "scanPackageLI failed to createIdmap"); 8212 } 8213 return pkg; 8214 } 8215 8216 /** 8217 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8218 * is derived purely on the basis of the contents of {@code scanFile} and 8219 * {@code cpuAbiOverride}. 8220 * 8221 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8222 */ 8223 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8224 String cpuAbiOverride, boolean extractLibs) 8225 throws PackageManagerException { 8226 // TODO: We can probably be smarter about this stuff. For installed apps, 8227 // we can calculate this information at install time once and for all. For 8228 // system apps, we can probably assume that this information doesn't change 8229 // after the first boot scan. As things stand, we do lots of unnecessary work. 8230 8231 // Give ourselves some initial paths; we'll come back for another 8232 // pass once we've determined ABI below. 8233 setNativeLibraryPaths(pkg); 8234 8235 // We would never need to extract libs for forward-locked and external packages, 8236 // since the container service will do it for us. We shouldn't attempt to 8237 // extract libs from system app when it was not updated. 8238 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8239 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8240 extractLibs = false; 8241 } 8242 8243 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8244 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8245 8246 NativeLibraryHelper.Handle handle = null; 8247 try { 8248 handle = NativeLibraryHelper.Handle.create(pkg); 8249 // TODO(multiArch): This can be null for apps that didn't go through the 8250 // usual installation process. We can calculate it again, like we 8251 // do during install time. 8252 // 8253 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8254 // unnecessary. 8255 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8256 8257 // Null out the abis so that they can be recalculated. 8258 pkg.applicationInfo.primaryCpuAbi = null; 8259 pkg.applicationInfo.secondaryCpuAbi = null; 8260 if (isMultiArch(pkg.applicationInfo)) { 8261 // Warn if we've set an abiOverride for multi-lib packages.. 8262 // By definition, we need to copy both 32 and 64 bit libraries for 8263 // such packages. 8264 if (pkg.cpuAbiOverride != null 8265 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8266 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8267 } 8268 8269 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8270 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8271 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8272 if (extractLibs) { 8273 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8274 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8275 useIsaSpecificSubdirs); 8276 } else { 8277 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8278 } 8279 } 8280 8281 maybeThrowExceptionForMultiArchCopy( 8282 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8283 8284 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8285 if (extractLibs) { 8286 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8287 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8288 useIsaSpecificSubdirs); 8289 } else { 8290 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8291 } 8292 } 8293 8294 maybeThrowExceptionForMultiArchCopy( 8295 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8296 8297 if (abi64 >= 0) { 8298 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8299 } 8300 8301 if (abi32 >= 0) { 8302 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8303 if (abi64 >= 0) { 8304 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8305 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8306 pkg.applicationInfo.primaryCpuAbi = abi; 8307 } else { 8308 pkg.applicationInfo.secondaryCpuAbi = abi; 8309 } 8310 } else { 8311 pkg.applicationInfo.primaryCpuAbi = abi; 8312 } 8313 } 8314 8315 } else { 8316 String[] abiList = (cpuAbiOverride != null) ? 8317 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8318 8319 // Enable gross and lame hacks for apps that are built with old 8320 // SDK tools. We must scan their APKs for renderscript bitcode and 8321 // not launch them if it's present. Don't bother checking on devices 8322 // that don't have 64 bit support. 8323 boolean needsRenderScriptOverride = false; 8324 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8325 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8326 abiList = Build.SUPPORTED_32_BIT_ABIS; 8327 needsRenderScriptOverride = true; 8328 } 8329 8330 final int copyRet; 8331 if (extractLibs) { 8332 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8333 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8334 } else { 8335 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8336 } 8337 8338 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8339 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8340 "Error unpackaging native libs for app, errorCode=" + copyRet); 8341 } 8342 8343 if (copyRet >= 0) { 8344 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8345 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8346 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8347 } else if (needsRenderScriptOverride) { 8348 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8349 } 8350 } 8351 } catch (IOException ioe) { 8352 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8353 } finally { 8354 IoUtils.closeQuietly(handle); 8355 } 8356 8357 // Now that we've calculated the ABIs and determined if it's an internal app, 8358 // we will go ahead and populate the nativeLibraryPath. 8359 setNativeLibraryPaths(pkg); 8360 } 8361 8362 /** 8363 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8364 * i.e, so that all packages can be run inside a single process if required. 8365 * 8366 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8367 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8368 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8369 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8370 * updating a package that belongs to a shared user. 8371 * 8372 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8373 * adds unnecessary complexity. 8374 */ 8375 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8376 PackageParser.Package scannedPackage, boolean bootComplete) { 8377 String requiredInstructionSet = null; 8378 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8379 requiredInstructionSet = VMRuntime.getInstructionSet( 8380 scannedPackage.applicationInfo.primaryCpuAbi); 8381 } 8382 8383 PackageSetting requirer = null; 8384 for (PackageSetting ps : packagesForUser) { 8385 // If packagesForUser contains scannedPackage, we skip it. This will happen 8386 // when scannedPackage is an update of an existing package. Without this check, 8387 // we will never be able to change the ABI of any package belonging to a shared 8388 // user, even if it's compatible with other packages. 8389 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8390 if (ps.primaryCpuAbiString == null) { 8391 continue; 8392 } 8393 8394 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8395 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8396 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8397 // this but there's not much we can do. 8398 String errorMessage = "Instruction set mismatch, " 8399 + ((requirer == null) ? "[caller]" : requirer) 8400 + " requires " + requiredInstructionSet + " whereas " + ps 8401 + " requires " + instructionSet; 8402 Slog.w(TAG, errorMessage); 8403 } 8404 8405 if (requiredInstructionSet == null) { 8406 requiredInstructionSet = instructionSet; 8407 requirer = ps; 8408 } 8409 } 8410 } 8411 8412 if (requiredInstructionSet != null) { 8413 String adjustedAbi; 8414 if (requirer != null) { 8415 // requirer != null implies that either scannedPackage was null or that scannedPackage 8416 // did not require an ABI, in which case we have to adjust scannedPackage to match 8417 // the ABI of the set (which is the same as requirer's ABI) 8418 adjustedAbi = requirer.primaryCpuAbiString; 8419 if (scannedPackage != null) { 8420 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8421 } 8422 } else { 8423 // requirer == null implies that we're updating all ABIs in the set to 8424 // match scannedPackage. 8425 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8426 } 8427 8428 for (PackageSetting ps : packagesForUser) { 8429 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8430 if (ps.primaryCpuAbiString != null) { 8431 continue; 8432 } 8433 8434 ps.primaryCpuAbiString = adjustedAbi; 8435 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8436 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8437 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8438 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8439 + " (requirer=" 8440 + (requirer == null ? "null" : requirer.pkg.packageName) 8441 + ", scannedPackage=" 8442 + (scannedPackage != null ? scannedPackage.packageName : "null") 8443 + ")"); 8444 try { 8445 mInstaller.rmdex(ps.codePathString, 8446 getDexCodeInstructionSet(getPreferredInstructionSet())); 8447 } catch (InstallerException ignored) { 8448 } 8449 } 8450 } 8451 } 8452 } 8453 } 8454 8455 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8456 synchronized (mPackages) { 8457 mResolverReplaced = true; 8458 // Set up information for custom user intent resolution activity. 8459 mResolveActivity.applicationInfo = pkg.applicationInfo; 8460 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8461 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8462 mResolveActivity.processName = pkg.applicationInfo.packageName; 8463 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8464 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8465 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8466 mResolveActivity.theme = 0; 8467 mResolveActivity.exported = true; 8468 mResolveActivity.enabled = true; 8469 mResolveInfo.activityInfo = mResolveActivity; 8470 mResolveInfo.priority = 0; 8471 mResolveInfo.preferredOrder = 0; 8472 mResolveInfo.match = 0; 8473 mResolveComponentName = mCustomResolverComponentName; 8474 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8475 mResolveComponentName); 8476 } 8477 } 8478 8479 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8480 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8481 8482 // Set up information for ephemeral installer activity 8483 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8484 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8485 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8486 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8487 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8488 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8489 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8490 mEphemeralInstallerActivity.theme = 0; 8491 mEphemeralInstallerActivity.exported = true; 8492 mEphemeralInstallerActivity.enabled = true; 8493 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8494 mEphemeralInstallerInfo.priority = 0; 8495 mEphemeralInstallerInfo.preferredOrder = 0; 8496 mEphemeralInstallerInfo.match = 0; 8497 8498 if (DEBUG_EPHEMERAL) { 8499 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8500 } 8501 } 8502 8503 private static String calculateBundledApkRoot(final String codePathString) { 8504 final File codePath = new File(codePathString); 8505 final File codeRoot; 8506 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8507 codeRoot = Environment.getRootDirectory(); 8508 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8509 codeRoot = Environment.getOemDirectory(); 8510 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8511 codeRoot = Environment.getVendorDirectory(); 8512 } else { 8513 // Unrecognized code path; take its top real segment as the apk root: 8514 // e.g. /something/app/blah.apk => /something 8515 try { 8516 File f = codePath.getCanonicalFile(); 8517 File parent = f.getParentFile(); // non-null because codePath is a file 8518 File tmp; 8519 while ((tmp = parent.getParentFile()) != null) { 8520 f = parent; 8521 parent = tmp; 8522 } 8523 codeRoot = f; 8524 Slog.w(TAG, "Unrecognized code path " 8525 + codePath + " - using " + codeRoot); 8526 } catch (IOException e) { 8527 // Can't canonicalize the code path -- shenanigans? 8528 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8529 return Environment.getRootDirectory().getPath(); 8530 } 8531 } 8532 return codeRoot.getPath(); 8533 } 8534 8535 /** 8536 * Derive and set the location of native libraries for the given package, 8537 * which varies depending on where and how the package was installed. 8538 */ 8539 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8540 final ApplicationInfo info = pkg.applicationInfo; 8541 final String codePath = pkg.codePath; 8542 final File codeFile = new File(codePath); 8543 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8544 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8545 8546 info.nativeLibraryRootDir = null; 8547 info.nativeLibraryRootRequiresIsa = false; 8548 info.nativeLibraryDir = null; 8549 info.secondaryNativeLibraryDir = null; 8550 8551 if (isApkFile(codeFile)) { 8552 // Monolithic install 8553 if (bundledApp) { 8554 // If "/system/lib64/apkname" exists, assume that is the per-package 8555 // native library directory to use; otherwise use "/system/lib/apkname". 8556 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8557 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8558 getPrimaryInstructionSet(info)); 8559 8560 // This is a bundled system app so choose the path based on the ABI. 8561 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8562 // is just the default path. 8563 final String apkName = deriveCodePathName(codePath); 8564 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8565 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8566 apkName).getAbsolutePath(); 8567 8568 if (info.secondaryCpuAbi != null) { 8569 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8570 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8571 secondaryLibDir, apkName).getAbsolutePath(); 8572 } 8573 } else if (asecApp) { 8574 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8575 .getAbsolutePath(); 8576 } else { 8577 final String apkName = deriveCodePathName(codePath); 8578 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8579 .getAbsolutePath(); 8580 } 8581 8582 info.nativeLibraryRootRequiresIsa = false; 8583 info.nativeLibraryDir = info.nativeLibraryRootDir; 8584 } else { 8585 // Cluster install 8586 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8587 info.nativeLibraryRootRequiresIsa = true; 8588 8589 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8590 getPrimaryInstructionSet(info)).getAbsolutePath(); 8591 8592 if (info.secondaryCpuAbi != null) { 8593 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8594 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8595 } 8596 } 8597 } 8598 8599 /** 8600 * Calculate the abis and roots for a bundled app. These can uniquely 8601 * be determined from the contents of the system partition, i.e whether 8602 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8603 * of this information, and instead assume that the system was built 8604 * sensibly. 8605 */ 8606 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8607 PackageSetting pkgSetting) { 8608 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8609 8610 // If "/system/lib64/apkname" exists, assume that is the per-package 8611 // native library directory to use; otherwise use "/system/lib/apkname". 8612 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8613 setBundledAppAbi(pkg, apkRoot, apkName); 8614 // pkgSetting might be null during rescan following uninstall of updates 8615 // to a bundled app, so accommodate that possibility. The settings in 8616 // that case will be established later from the parsed package. 8617 // 8618 // If the settings aren't null, sync them up with what we've just derived. 8619 // note that apkRoot isn't stored in the package settings. 8620 if (pkgSetting != null) { 8621 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8622 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8623 } 8624 } 8625 8626 /** 8627 * Deduces the ABI of a bundled app and sets the relevant fields on the 8628 * parsed pkg object. 8629 * 8630 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8631 * under which system libraries are installed. 8632 * @param apkName the name of the installed package. 8633 */ 8634 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8635 final File codeFile = new File(pkg.codePath); 8636 8637 final boolean has64BitLibs; 8638 final boolean has32BitLibs; 8639 if (isApkFile(codeFile)) { 8640 // Monolithic install 8641 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8642 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8643 } else { 8644 // Cluster install 8645 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8646 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8647 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8648 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8649 has64BitLibs = (new File(rootDir, isa)).exists(); 8650 } else { 8651 has64BitLibs = false; 8652 } 8653 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8654 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8655 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8656 has32BitLibs = (new File(rootDir, isa)).exists(); 8657 } else { 8658 has32BitLibs = false; 8659 } 8660 } 8661 8662 if (has64BitLibs && !has32BitLibs) { 8663 // The package has 64 bit libs, but not 32 bit libs. Its primary 8664 // ABI should be 64 bit. We can safely assume here that the bundled 8665 // native libraries correspond to the most preferred ABI in the list. 8666 8667 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8668 pkg.applicationInfo.secondaryCpuAbi = null; 8669 } else if (has32BitLibs && !has64BitLibs) { 8670 // The package has 32 bit libs but not 64 bit libs. Its primary 8671 // ABI should be 32 bit. 8672 8673 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8674 pkg.applicationInfo.secondaryCpuAbi = null; 8675 } else if (has32BitLibs && has64BitLibs) { 8676 // The application has both 64 and 32 bit bundled libraries. We check 8677 // here that the app declares multiArch support, and warn if it doesn't. 8678 // 8679 // We will be lenient here and record both ABIs. The primary will be the 8680 // ABI that's higher on the list, i.e, a device that's configured to prefer 8681 // 64 bit apps will see a 64 bit primary ABI, 8682 8683 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8684 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8685 } 8686 8687 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8688 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8689 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8690 } else { 8691 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8692 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8693 } 8694 } else { 8695 pkg.applicationInfo.primaryCpuAbi = null; 8696 pkg.applicationInfo.secondaryCpuAbi = null; 8697 } 8698 } 8699 8700 private void killPackage(PackageParser.Package pkg, String reason) { 8701 // Kill the parent package 8702 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8703 // Kill the child packages 8704 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8705 for (int i = 0; i < childCount; i++) { 8706 PackageParser.Package childPkg = pkg.childPackages.get(i); 8707 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8708 } 8709 } 8710 8711 private void killApplication(String pkgName, int appId, String reason) { 8712 // Request the ActivityManager to kill the process(only for existing packages) 8713 // so that we do not end up in a confused state while the user is still using the older 8714 // version of the application while the new one gets installed. 8715 IActivityManager am = ActivityManagerNative.getDefault(); 8716 if (am != null) { 8717 try { 8718 am.killApplicationWithAppId(pkgName, appId, reason); 8719 } catch (RemoteException e) { 8720 } 8721 } 8722 } 8723 8724 private void removePackageSettingLI(PackageParser.Package pkg, boolean chatty) { 8725 // Remove the parent package setting 8726 PackageSetting ps = (PackageSetting) pkg.mExtras; 8727 if (ps != null) { 8728 removePackageSettingLI(ps, chatty); 8729 } 8730 // Remove the child package setting 8731 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8732 for (int i = 0; i < childCount; i++) { 8733 PackageParser.Package childPkg = pkg.childPackages.get(i); 8734 ps = (PackageSetting) childPkg.mExtras; 8735 if (ps != null) { 8736 removePackageSettingLI(ps, chatty); 8737 } 8738 } 8739 } 8740 8741 void removePackageSettingLI(PackageSetting ps, boolean chatty) { 8742 if (DEBUG_INSTALL) { 8743 if (chatty) 8744 Log.d(TAG, "Removing package " + ps.name); 8745 } 8746 8747 // writer 8748 synchronized (mPackages) { 8749 mPackages.remove(ps.name); 8750 final PackageParser.Package pkg = ps.pkg; 8751 if (pkg != null) { 8752 cleanPackageDataStructuresLILPw(pkg, chatty); 8753 } 8754 } 8755 } 8756 8757 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8758 if (DEBUG_INSTALL) { 8759 if (chatty) 8760 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8761 } 8762 8763 // writer 8764 synchronized (mPackages) { 8765 // Remove the parent package 8766 mPackages.remove(pkg.applicationInfo.packageName); 8767 cleanPackageDataStructuresLILPw(pkg, chatty); 8768 8769 // Remove the child packages 8770 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8771 for (int i = 0; i < childCount; i++) { 8772 PackageParser.Package childPkg = pkg.childPackages.get(i); 8773 mPackages.remove(childPkg.applicationInfo.packageName); 8774 cleanPackageDataStructuresLILPw(childPkg, chatty); 8775 } 8776 } 8777 } 8778 8779 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8780 int N = pkg.providers.size(); 8781 StringBuilder r = null; 8782 int i; 8783 for (i=0; i<N; i++) { 8784 PackageParser.Provider p = pkg.providers.get(i); 8785 mProviders.removeProvider(p); 8786 if (p.info.authority == null) { 8787 8788 /* There was another ContentProvider with this authority when 8789 * this app was installed so this authority is null, 8790 * Ignore it as we don't have to unregister the provider. 8791 */ 8792 continue; 8793 } 8794 String names[] = p.info.authority.split(";"); 8795 for (int j = 0; j < names.length; j++) { 8796 if (mProvidersByAuthority.get(names[j]) == p) { 8797 mProvidersByAuthority.remove(names[j]); 8798 if (DEBUG_REMOVE) { 8799 if (chatty) 8800 Log.d(TAG, "Unregistered content provider: " + names[j] 8801 + ", className = " + p.info.name + ", isSyncable = " 8802 + p.info.isSyncable); 8803 } 8804 } 8805 } 8806 if (DEBUG_REMOVE && chatty) { 8807 if (r == null) { 8808 r = new StringBuilder(256); 8809 } else { 8810 r.append(' '); 8811 } 8812 r.append(p.info.name); 8813 } 8814 } 8815 if (r != null) { 8816 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8817 } 8818 8819 N = pkg.services.size(); 8820 r = null; 8821 for (i=0; i<N; i++) { 8822 PackageParser.Service s = pkg.services.get(i); 8823 mServices.removeService(s); 8824 if (chatty) { 8825 if (r == null) { 8826 r = new StringBuilder(256); 8827 } else { 8828 r.append(' '); 8829 } 8830 r.append(s.info.name); 8831 } 8832 } 8833 if (r != null) { 8834 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8835 } 8836 8837 N = pkg.receivers.size(); 8838 r = null; 8839 for (i=0; i<N; i++) { 8840 PackageParser.Activity a = pkg.receivers.get(i); 8841 mReceivers.removeActivity(a, "receiver"); 8842 if (DEBUG_REMOVE && chatty) { 8843 if (r == null) { 8844 r = new StringBuilder(256); 8845 } else { 8846 r.append(' '); 8847 } 8848 r.append(a.info.name); 8849 } 8850 } 8851 if (r != null) { 8852 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8853 } 8854 8855 N = pkg.activities.size(); 8856 r = null; 8857 for (i=0; i<N; i++) { 8858 PackageParser.Activity a = pkg.activities.get(i); 8859 mActivities.removeActivity(a, "activity"); 8860 if (DEBUG_REMOVE && chatty) { 8861 if (r == null) { 8862 r = new StringBuilder(256); 8863 } else { 8864 r.append(' '); 8865 } 8866 r.append(a.info.name); 8867 } 8868 } 8869 if (r != null) { 8870 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8871 } 8872 8873 N = pkg.permissions.size(); 8874 r = null; 8875 for (i=0; i<N; i++) { 8876 PackageParser.Permission p = pkg.permissions.get(i); 8877 BasePermission bp = mSettings.mPermissions.get(p.info.name); 8878 if (bp == null) { 8879 bp = mSettings.mPermissionTrees.get(p.info.name); 8880 } 8881 if (bp != null && bp.perm == p) { 8882 bp.perm = null; 8883 if (DEBUG_REMOVE && chatty) { 8884 if (r == null) { 8885 r = new StringBuilder(256); 8886 } else { 8887 r.append(' '); 8888 } 8889 r.append(p.info.name); 8890 } 8891 } 8892 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8893 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 8894 if (appOpPkgs != null) { 8895 appOpPkgs.remove(pkg.packageName); 8896 } 8897 } 8898 } 8899 if (r != null) { 8900 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8901 } 8902 8903 N = pkg.requestedPermissions.size(); 8904 r = null; 8905 for (i=0; i<N; i++) { 8906 String perm = pkg.requestedPermissions.get(i); 8907 BasePermission bp = mSettings.mPermissions.get(perm); 8908 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 8909 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 8910 if (appOpPkgs != null) { 8911 appOpPkgs.remove(pkg.packageName); 8912 if (appOpPkgs.isEmpty()) { 8913 mAppOpPermissionPackages.remove(perm); 8914 } 8915 } 8916 } 8917 } 8918 if (r != null) { 8919 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 8920 } 8921 8922 N = pkg.instrumentation.size(); 8923 r = null; 8924 for (i=0; i<N; i++) { 8925 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8926 mInstrumentation.remove(a.getComponentName()); 8927 if (DEBUG_REMOVE && chatty) { 8928 if (r == null) { 8929 r = new StringBuilder(256); 8930 } else { 8931 r.append(' '); 8932 } 8933 r.append(a.info.name); 8934 } 8935 } 8936 if (r != null) { 8937 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 8938 } 8939 8940 r = null; 8941 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8942 // Only system apps can hold shared libraries. 8943 if (pkg.libraryNames != null) { 8944 for (i=0; i<pkg.libraryNames.size(); i++) { 8945 String name = pkg.libraryNames.get(i); 8946 SharedLibraryEntry cur = mSharedLibraries.get(name); 8947 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 8948 mSharedLibraries.remove(name); 8949 if (DEBUG_REMOVE && chatty) { 8950 if (r == null) { 8951 r = new StringBuilder(256); 8952 } else { 8953 r.append(' '); 8954 } 8955 r.append(name); 8956 } 8957 } 8958 } 8959 } 8960 } 8961 if (r != null) { 8962 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 8963 } 8964 } 8965 8966 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 8967 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 8968 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 8969 return true; 8970 } 8971 } 8972 return false; 8973 } 8974 8975 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 8976 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 8977 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 8978 8979 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 8980 // Update the parent permissions 8981 updatePermissionsLPw(pkg.packageName, pkg, flags); 8982 // Update the child permissions 8983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8984 for (int i = 0; i < childCount; i++) { 8985 PackageParser.Package childPkg = pkg.childPackages.get(i); 8986 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 8987 } 8988 } 8989 8990 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 8991 int flags) { 8992 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 8993 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 8994 } 8995 8996 private void updatePermissionsLPw(String changingPkg, 8997 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 8998 // Make sure there are no dangling permission trees. 8999 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9000 while (it.hasNext()) { 9001 final BasePermission bp = it.next(); 9002 if (bp.packageSetting == null) { 9003 // We may not yet have parsed the package, so just see if 9004 // we still know about its settings. 9005 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9006 } 9007 if (bp.packageSetting == null) { 9008 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9009 + " from package " + bp.sourcePackage); 9010 it.remove(); 9011 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9012 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9013 Slog.i(TAG, "Removing old permission tree: " + bp.name 9014 + " from package " + bp.sourcePackage); 9015 flags |= UPDATE_PERMISSIONS_ALL; 9016 it.remove(); 9017 } 9018 } 9019 } 9020 9021 // Make sure all dynamic permissions have been assigned to a package, 9022 // and make sure there are no dangling permissions. 9023 it = mSettings.mPermissions.values().iterator(); 9024 while (it.hasNext()) { 9025 final BasePermission bp = it.next(); 9026 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9027 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9028 + bp.name + " pkg=" + bp.sourcePackage 9029 + " info=" + bp.pendingInfo); 9030 if (bp.packageSetting == null && bp.pendingInfo != null) { 9031 final BasePermission tree = findPermissionTreeLP(bp.name); 9032 if (tree != null && tree.perm != null) { 9033 bp.packageSetting = tree.packageSetting; 9034 bp.perm = new PackageParser.Permission(tree.perm.owner, 9035 new PermissionInfo(bp.pendingInfo)); 9036 bp.perm.info.packageName = tree.perm.info.packageName; 9037 bp.perm.info.name = bp.name; 9038 bp.uid = tree.uid; 9039 } 9040 } 9041 } 9042 if (bp.packageSetting == null) { 9043 // We may not yet have parsed the package, so just see if 9044 // we still know about its settings. 9045 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9046 } 9047 if (bp.packageSetting == null) { 9048 Slog.w(TAG, "Removing dangling permission: " + bp.name 9049 + " from package " + bp.sourcePackage); 9050 it.remove(); 9051 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9052 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9053 Slog.i(TAG, "Removing old permission: " + bp.name 9054 + " from package " + bp.sourcePackage); 9055 flags |= UPDATE_PERMISSIONS_ALL; 9056 it.remove(); 9057 } 9058 } 9059 } 9060 9061 // Now update the permissions for all packages, in particular 9062 // replace the granted permissions of the system packages. 9063 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9064 for (PackageParser.Package pkg : mPackages.values()) { 9065 if (pkg != pkgInfo) { 9066 // Only replace for packages on requested volume 9067 final String volumeUuid = getVolumeUuidForPackage(pkg); 9068 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9069 && Objects.equals(replaceVolumeUuid, volumeUuid); 9070 grantPermissionsLPw(pkg, replace, changingPkg); 9071 } 9072 } 9073 } 9074 9075 if (pkgInfo != null) { 9076 // Only replace for packages on requested volume 9077 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9078 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9079 && Objects.equals(replaceVolumeUuid, volumeUuid); 9080 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9081 } 9082 } 9083 9084 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9085 String packageOfInterest) { 9086 // IMPORTANT: There are two types of permissions: install and runtime. 9087 // Install time permissions are granted when the app is installed to 9088 // all device users and users added in the future. Runtime permissions 9089 // are granted at runtime explicitly to specific users. Normal and signature 9090 // protected permissions are install time permissions. Dangerous permissions 9091 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9092 // otherwise they are runtime permissions. This function does not manage 9093 // runtime permissions except for the case an app targeting Lollipop MR1 9094 // being upgraded to target a newer SDK, in which case dangerous permissions 9095 // are transformed from install time to runtime ones. 9096 9097 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9098 if (ps == null) { 9099 return; 9100 } 9101 9102 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9103 9104 PermissionsState permissionsState = ps.getPermissionsState(); 9105 PermissionsState origPermissions = permissionsState; 9106 9107 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9108 9109 boolean runtimePermissionsRevoked = false; 9110 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9111 9112 boolean changedInstallPermission = false; 9113 9114 if (replace) { 9115 ps.installPermissionsFixed = false; 9116 if (!ps.isSharedUser()) { 9117 origPermissions = new PermissionsState(permissionsState); 9118 permissionsState.reset(); 9119 } else { 9120 // We need to know only about runtime permission changes since the 9121 // calling code always writes the install permissions state but 9122 // the runtime ones are written only if changed. The only cases of 9123 // changed runtime permissions here are promotion of an install to 9124 // runtime and revocation of a runtime from a shared user. 9125 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9126 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9127 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9128 runtimePermissionsRevoked = true; 9129 } 9130 } 9131 } 9132 9133 permissionsState.setGlobalGids(mGlobalGids); 9134 9135 final int N = pkg.requestedPermissions.size(); 9136 for (int i=0; i<N; i++) { 9137 final String name = pkg.requestedPermissions.get(i); 9138 final BasePermission bp = mSettings.mPermissions.get(name); 9139 9140 if (DEBUG_INSTALL) { 9141 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9142 } 9143 9144 if (bp == null || bp.packageSetting == null) { 9145 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9146 Slog.w(TAG, "Unknown permission " + name 9147 + " in package " + pkg.packageName); 9148 } 9149 continue; 9150 } 9151 9152 final String perm = bp.name; 9153 boolean allowedSig = false; 9154 int grant = GRANT_DENIED; 9155 9156 // Keep track of app op permissions. 9157 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9158 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9159 if (pkgs == null) { 9160 pkgs = new ArraySet<>(); 9161 mAppOpPermissionPackages.put(bp.name, pkgs); 9162 } 9163 pkgs.add(pkg.packageName); 9164 } 9165 9166 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9167 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9168 >= Build.VERSION_CODES.M; 9169 switch (level) { 9170 case PermissionInfo.PROTECTION_NORMAL: { 9171 // For all apps normal permissions are install time ones. 9172 grant = GRANT_INSTALL; 9173 } break; 9174 9175 case PermissionInfo.PROTECTION_DANGEROUS: { 9176 // If a permission review is required for legacy apps we represent 9177 // their permissions as always granted runtime ones since we need 9178 // to keep the review required permission flag per user while an 9179 // install permission's state is shared across all users. 9180 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9181 // For legacy apps dangerous permissions are install time ones. 9182 grant = GRANT_INSTALL; 9183 } else if (origPermissions.hasInstallPermission(bp.name)) { 9184 // For legacy apps that became modern, install becomes runtime. 9185 grant = GRANT_UPGRADE; 9186 } else if (mPromoteSystemApps 9187 && isSystemApp(ps) 9188 && mExistingSystemPackages.contains(ps.name)) { 9189 // For legacy system apps, install becomes runtime. 9190 // We cannot check hasInstallPermission() for system apps since those 9191 // permissions were granted implicitly and not persisted pre-M. 9192 grant = GRANT_UPGRADE; 9193 } else { 9194 // For modern apps keep runtime permissions unchanged. 9195 grant = GRANT_RUNTIME; 9196 } 9197 } break; 9198 9199 case PermissionInfo.PROTECTION_SIGNATURE: { 9200 // For all apps signature permissions are install time ones. 9201 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9202 if (allowedSig) { 9203 grant = GRANT_INSTALL; 9204 } 9205 } break; 9206 } 9207 9208 if (DEBUG_INSTALL) { 9209 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9210 } 9211 9212 if (grant != GRANT_DENIED) { 9213 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9214 // If this is an existing, non-system package, then 9215 // we can't add any new permissions to it. 9216 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9217 // Except... if this is a permission that was added 9218 // to the platform (note: need to only do this when 9219 // updating the platform). 9220 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9221 grant = GRANT_DENIED; 9222 } 9223 } 9224 } 9225 9226 switch (grant) { 9227 case GRANT_INSTALL: { 9228 // Revoke this as runtime permission to handle the case of 9229 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9230 for (int userId : UserManagerService.getInstance().getUserIds()) { 9231 if (origPermissions.getRuntimePermissionState( 9232 bp.name, userId) != null) { 9233 // Revoke the runtime permission and clear the flags. 9234 origPermissions.revokeRuntimePermission(bp, userId); 9235 origPermissions.updatePermissionFlags(bp, userId, 9236 PackageManager.MASK_PERMISSION_FLAGS, 0); 9237 // If we revoked a permission permission, we have to write. 9238 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9239 changedRuntimePermissionUserIds, userId); 9240 } 9241 } 9242 // Grant an install permission. 9243 if (permissionsState.grantInstallPermission(bp) != 9244 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9245 changedInstallPermission = true; 9246 } 9247 } break; 9248 9249 case GRANT_RUNTIME: { 9250 // Grant previously granted runtime permissions. 9251 for (int userId : UserManagerService.getInstance().getUserIds()) { 9252 PermissionState permissionState = origPermissions 9253 .getRuntimePermissionState(bp.name, userId); 9254 int flags = permissionState != null 9255 ? permissionState.getFlags() : 0; 9256 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9257 if (permissionsState.grantRuntimePermission(bp, userId) == 9258 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9259 // If we cannot put the permission as it was, we have to write. 9260 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9261 changedRuntimePermissionUserIds, userId); 9262 } 9263 // If the app supports runtime permissions no need for a review. 9264 if (Build.PERMISSIONS_REVIEW_REQUIRED 9265 && appSupportsRuntimePermissions 9266 && (flags & PackageManager 9267 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9268 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9269 // Since we changed the flags, we have to write. 9270 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9271 changedRuntimePermissionUserIds, userId); 9272 } 9273 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9274 && !appSupportsRuntimePermissions) { 9275 // For legacy apps that need a permission review, every new 9276 // runtime permission is granted but it is pending a review. 9277 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9278 permissionsState.grantRuntimePermission(bp, userId); 9279 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9280 // We changed the permission and flags, hence have to write. 9281 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9282 changedRuntimePermissionUserIds, userId); 9283 } 9284 } 9285 // Propagate the permission flags. 9286 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9287 } 9288 } break; 9289 9290 case GRANT_UPGRADE: { 9291 // Grant runtime permissions for a previously held install permission. 9292 PermissionState permissionState = origPermissions 9293 .getInstallPermissionState(bp.name); 9294 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9295 9296 if (origPermissions.revokeInstallPermission(bp) 9297 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9298 // We will be transferring the permission flags, so clear them. 9299 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9300 PackageManager.MASK_PERMISSION_FLAGS, 0); 9301 changedInstallPermission = true; 9302 } 9303 9304 // If the permission is not to be promoted to runtime we ignore it and 9305 // also its other flags as they are not applicable to install permissions. 9306 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9307 for (int userId : currentUserIds) { 9308 if (permissionsState.grantRuntimePermission(bp, userId) != 9309 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9310 // Transfer the permission flags. 9311 permissionsState.updatePermissionFlags(bp, userId, 9312 flags, flags); 9313 // If we granted the permission, we have to write. 9314 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9315 changedRuntimePermissionUserIds, userId); 9316 } 9317 } 9318 } 9319 } break; 9320 9321 default: { 9322 if (packageOfInterest == null 9323 || packageOfInterest.equals(pkg.packageName)) { 9324 Slog.w(TAG, "Not granting permission " + perm 9325 + " to package " + pkg.packageName 9326 + " because it was previously installed without"); 9327 } 9328 } break; 9329 } 9330 } else { 9331 if (permissionsState.revokeInstallPermission(bp) != 9332 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9333 // Also drop the permission flags. 9334 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9335 PackageManager.MASK_PERMISSION_FLAGS, 0); 9336 changedInstallPermission = true; 9337 Slog.i(TAG, "Un-granting permission " + perm 9338 + " from package " + pkg.packageName 9339 + " (protectionLevel=" + bp.protectionLevel 9340 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9341 + ")"); 9342 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9343 // Don't print warning for app op permissions, since it is fine for them 9344 // not to be granted, there is a UI for the user to decide. 9345 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9346 Slog.w(TAG, "Not granting permission " + perm 9347 + " to package " + pkg.packageName 9348 + " (protectionLevel=" + bp.protectionLevel 9349 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9350 + ")"); 9351 } 9352 } 9353 } 9354 } 9355 9356 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9357 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9358 // This is the first that we have heard about this package, so the 9359 // permissions we have now selected are fixed until explicitly 9360 // changed. 9361 ps.installPermissionsFixed = true; 9362 } 9363 9364 // Persist the runtime permissions state for users with changes. If permissions 9365 // were revoked because no app in the shared user declares them we have to 9366 // write synchronously to avoid losing runtime permissions state. 9367 for (int userId : changedRuntimePermissionUserIds) { 9368 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9369 } 9370 9371 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9372 } 9373 9374 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9375 boolean allowed = false; 9376 final int NP = PackageParser.NEW_PERMISSIONS.length; 9377 for (int ip=0; ip<NP; ip++) { 9378 final PackageParser.NewPermissionInfo npi 9379 = PackageParser.NEW_PERMISSIONS[ip]; 9380 if (npi.name.equals(perm) 9381 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9382 allowed = true; 9383 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9384 + pkg.packageName); 9385 break; 9386 } 9387 } 9388 return allowed; 9389 } 9390 9391 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9392 BasePermission bp, PermissionsState origPermissions) { 9393 boolean allowed; 9394 allowed = (compareSignatures( 9395 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9396 == PackageManager.SIGNATURE_MATCH) 9397 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9398 == PackageManager.SIGNATURE_MATCH); 9399 if (!allowed && (bp.protectionLevel 9400 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9401 if (isSystemApp(pkg)) { 9402 // For updated system applications, a system permission 9403 // is granted only if it had been defined by the original application. 9404 if (pkg.isUpdatedSystemApp()) { 9405 final PackageSetting sysPs = mSettings 9406 .getDisabledSystemPkgLPr(pkg.packageName); 9407 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9408 // If the original was granted this permission, we take 9409 // that grant decision as read and propagate it to the 9410 // update. 9411 if (sysPs.isPrivileged()) { 9412 allowed = true; 9413 } 9414 } else { 9415 // The system apk may have been updated with an older 9416 // version of the one on the data partition, but which 9417 // granted a new system permission that it didn't have 9418 // before. In this case we do want to allow the app to 9419 // now get the new permission if the ancestral apk is 9420 // privileged to get it. 9421 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9422 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9423 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9424 allowed = true; 9425 break; 9426 } 9427 } 9428 } 9429 // Also if a privileged parent package on the system image or any of 9430 // its children requested a privileged permission, the updated child 9431 // packages can also get the permission. 9432 if (pkg.parentPackage != null) { 9433 final PackageSetting disabledSysParentPs = mSettings 9434 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9435 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9436 && disabledSysParentPs.isPrivileged()) { 9437 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9438 allowed = true; 9439 } else if (disabledSysParentPs.pkg.childPackages != null) { 9440 final int count = disabledSysParentPs.pkg.childPackages.size(); 9441 for (int i = 0; i < count; i++) { 9442 PackageParser.Package disabledSysChildPkg = 9443 disabledSysParentPs.pkg.childPackages.get(i); 9444 if (isPackageRequestingPermission(disabledSysChildPkg, 9445 perm)) { 9446 allowed = true; 9447 break; 9448 } 9449 } 9450 } 9451 } 9452 } 9453 } 9454 } else { 9455 allowed = isPrivilegedApp(pkg); 9456 } 9457 } 9458 } 9459 if (!allowed) { 9460 if (!allowed && (bp.protectionLevel 9461 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9462 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9463 // If this was a previously normal/dangerous permission that got moved 9464 // to a system permission as part of the runtime permission redesign, then 9465 // we still want to blindly grant it to old apps. 9466 allowed = true; 9467 } 9468 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9469 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9470 // If this permission is to be granted to the system installer and 9471 // this app is an installer, then it gets the permission. 9472 allowed = true; 9473 } 9474 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9475 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9476 // If this permission is to be granted to the system verifier and 9477 // this app is a verifier, then it gets the permission. 9478 allowed = true; 9479 } 9480 if (!allowed && (bp.protectionLevel 9481 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9482 && isSystemApp(pkg)) { 9483 // Any pre-installed system app is allowed to get this permission. 9484 allowed = true; 9485 } 9486 if (!allowed && (bp.protectionLevel 9487 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9488 // For development permissions, a development permission 9489 // is granted only if it was already granted. 9490 allowed = origPermissions.hasInstallPermission(perm); 9491 } 9492 } 9493 return allowed; 9494 } 9495 9496 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9497 final int permCount = pkg.requestedPermissions.size(); 9498 for (int j = 0; j < permCount; j++) { 9499 String requestedPermission = pkg.requestedPermissions.get(j); 9500 if (permission.equals(requestedPermission)) { 9501 return true; 9502 } 9503 } 9504 return false; 9505 } 9506 9507 final class ActivityIntentResolver 9508 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9509 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9510 boolean defaultOnly, int userId) { 9511 if (!sUserManager.exists(userId)) return null; 9512 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9513 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9514 } 9515 9516 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9517 int userId) { 9518 if (!sUserManager.exists(userId)) return null; 9519 mFlags = flags; 9520 return super.queryIntent(intent, resolvedType, 9521 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9522 } 9523 9524 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9525 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9526 if (!sUserManager.exists(userId)) return null; 9527 if (packageActivities == null) { 9528 return null; 9529 } 9530 mFlags = flags; 9531 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9532 final int N = packageActivities.size(); 9533 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9534 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9535 9536 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9537 for (int i = 0; i < N; ++i) { 9538 intentFilters = packageActivities.get(i).intents; 9539 if (intentFilters != null && intentFilters.size() > 0) { 9540 PackageParser.ActivityIntentInfo[] array = 9541 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9542 intentFilters.toArray(array); 9543 listCut.add(array); 9544 } 9545 } 9546 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9547 } 9548 9549 public final void addActivity(PackageParser.Activity a, String type) { 9550 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9551 mActivities.put(a.getComponentName(), a); 9552 if (DEBUG_SHOW_INFO) 9553 Log.v( 9554 TAG, " " + type + " " + 9555 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9556 if (DEBUG_SHOW_INFO) 9557 Log.v(TAG, " Class=" + a.info.name); 9558 final int NI = a.intents.size(); 9559 for (int j=0; j<NI; j++) { 9560 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9561 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9562 intent.setPriority(0); 9563 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9564 + a.className + " with priority > 0, forcing to 0"); 9565 } 9566 if (DEBUG_SHOW_INFO) { 9567 Log.v(TAG, " IntentFilter:"); 9568 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9569 } 9570 if (!intent.debugCheck()) { 9571 Log.w(TAG, "==> For Activity " + a.info.name); 9572 } 9573 addFilter(intent); 9574 } 9575 } 9576 9577 public final void removeActivity(PackageParser.Activity a, String type) { 9578 mActivities.remove(a.getComponentName()); 9579 if (DEBUG_SHOW_INFO) { 9580 Log.v(TAG, " " + type + " " 9581 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9582 : a.info.name) + ":"); 9583 Log.v(TAG, " Class=" + a.info.name); 9584 } 9585 final int NI = a.intents.size(); 9586 for (int j=0; j<NI; j++) { 9587 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9588 if (DEBUG_SHOW_INFO) { 9589 Log.v(TAG, " IntentFilter:"); 9590 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9591 } 9592 removeFilter(intent); 9593 } 9594 } 9595 9596 @Override 9597 protected boolean allowFilterResult( 9598 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9599 ActivityInfo filterAi = filter.activity.info; 9600 for (int i=dest.size()-1; i>=0; i--) { 9601 ActivityInfo destAi = dest.get(i).activityInfo; 9602 if (destAi.name == filterAi.name 9603 && destAi.packageName == filterAi.packageName) { 9604 return false; 9605 } 9606 } 9607 return true; 9608 } 9609 9610 @Override 9611 protected ActivityIntentInfo[] newArray(int size) { 9612 return new ActivityIntentInfo[size]; 9613 } 9614 9615 @Override 9616 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9617 if (!sUserManager.exists(userId)) return true; 9618 PackageParser.Package p = filter.activity.owner; 9619 if (p != null) { 9620 PackageSetting ps = (PackageSetting)p.mExtras; 9621 if (ps != null) { 9622 // System apps are never considered stopped for purposes of 9623 // filtering, because there may be no way for the user to 9624 // actually re-launch them. 9625 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9626 && ps.getStopped(userId); 9627 } 9628 } 9629 return false; 9630 } 9631 9632 @Override 9633 protected boolean isPackageForFilter(String packageName, 9634 PackageParser.ActivityIntentInfo info) { 9635 return packageName.equals(info.activity.owner.packageName); 9636 } 9637 9638 @Override 9639 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9640 int match, int userId) { 9641 if (!sUserManager.exists(userId)) return null; 9642 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9643 return null; 9644 } 9645 final PackageParser.Activity activity = info.activity; 9646 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9647 if (ps == null) { 9648 return null; 9649 } 9650 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9651 ps.readUserState(userId), userId); 9652 if (ai == null) { 9653 return null; 9654 } 9655 final ResolveInfo res = new ResolveInfo(); 9656 res.activityInfo = ai; 9657 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9658 res.filter = info; 9659 } 9660 if (info != null) { 9661 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9662 } 9663 res.priority = info.getPriority(); 9664 res.preferredOrder = activity.owner.mPreferredOrder; 9665 //System.out.println("Result: " + res.activityInfo.className + 9666 // " = " + res.priority); 9667 res.match = match; 9668 res.isDefault = info.hasDefault; 9669 res.labelRes = info.labelRes; 9670 res.nonLocalizedLabel = info.nonLocalizedLabel; 9671 if (userNeedsBadging(userId)) { 9672 res.noResourceId = true; 9673 } else { 9674 res.icon = info.icon; 9675 } 9676 res.iconResourceId = info.icon; 9677 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9678 return res; 9679 } 9680 9681 @Override 9682 protected void sortResults(List<ResolveInfo> results) { 9683 Collections.sort(results, mResolvePrioritySorter); 9684 } 9685 9686 @Override 9687 protected void dumpFilter(PrintWriter out, String prefix, 9688 PackageParser.ActivityIntentInfo filter) { 9689 out.print(prefix); out.print( 9690 Integer.toHexString(System.identityHashCode(filter.activity))); 9691 out.print(' '); 9692 filter.activity.printComponentShortName(out); 9693 out.print(" filter "); 9694 out.println(Integer.toHexString(System.identityHashCode(filter))); 9695 } 9696 9697 @Override 9698 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9699 return filter.activity; 9700 } 9701 9702 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9703 PackageParser.Activity activity = (PackageParser.Activity)label; 9704 out.print(prefix); out.print( 9705 Integer.toHexString(System.identityHashCode(activity))); 9706 out.print(' '); 9707 activity.printComponentShortName(out); 9708 if (count > 1) { 9709 out.print(" ("); out.print(count); out.print(" filters)"); 9710 } 9711 out.println(); 9712 } 9713 9714// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9715// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9716// final List<ResolveInfo> retList = Lists.newArrayList(); 9717// while (i.hasNext()) { 9718// final ResolveInfo resolveInfo = i.next(); 9719// if (isEnabledLP(resolveInfo.activityInfo)) { 9720// retList.add(resolveInfo); 9721// } 9722// } 9723// return retList; 9724// } 9725 9726 // Keys are String (activity class name), values are Activity. 9727 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9728 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9729 private int mFlags; 9730 } 9731 9732 private final class ServiceIntentResolver 9733 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9734 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9735 boolean defaultOnly, int userId) { 9736 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9737 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9738 } 9739 9740 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9741 int userId) { 9742 if (!sUserManager.exists(userId)) return null; 9743 mFlags = flags; 9744 return super.queryIntent(intent, resolvedType, 9745 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9746 } 9747 9748 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9749 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9750 if (!sUserManager.exists(userId)) return null; 9751 if (packageServices == null) { 9752 return null; 9753 } 9754 mFlags = flags; 9755 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9756 final int N = packageServices.size(); 9757 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9758 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9759 9760 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9761 for (int i = 0; i < N; ++i) { 9762 intentFilters = packageServices.get(i).intents; 9763 if (intentFilters != null && intentFilters.size() > 0) { 9764 PackageParser.ServiceIntentInfo[] array = 9765 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9766 intentFilters.toArray(array); 9767 listCut.add(array); 9768 } 9769 } 9770 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9771 } 9772 9773 public final void addService(PackageParser.Service s) { 9774 mServices.put(s.getComponentName(), s); 9775 if (DEBUG_SHOW_INFO) { 9776 Log.v(TAG, " " 9777 + (s.info.nonLocalizedLabel != null 9778 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9779 Log.v(TAG, " Class=" + s.info.name); 9780 } 9781 final int NI = s.intents.size(); 9782 int j; 9783 for (j=0; j<NI; j++) { 9784 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9785 if (DEBUG_SHOW_INFO) { 9786 Log.v(TAG, " IntentFilter:"); 9787 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9788 } 9789 if (!intent.debugCheck()) { 9790 Log.w(TAG, "==> For Service " + s.info.name); 9791 } 9792 addFilter(intent); 9793 } 9794 } 9795 9796 public final void removeService(PackageParser.Service s) { 9797 mServices.remove(s.getComponentName()); 9798 if (DEBUG_SHOW_INFO) { 9799 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9800 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9801 Log.v(TAG, " Class=" + s.info.name); 9802 } 9803 final int NI = s.intents.size(); 9804 int j; 9805 for (j=0; j<NI; j++) { 9806 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9807 if (DEBUG_SHOW_INFO) { 9808 Log.v(TAG, " IntentFilter:"); 9809 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9810 } 9811 removeFilter(intent); 9812 } 9813 } 9814 9815 @Override 9816 protected boolean allowFilterResult( 9817 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9818 ServiceInfo filterSi = filter.service.info; 9819 for (int i=dest.size()-1; i>=0; i--) { 9820 ServiceInfo destAi = dest.get(i).serviceInfo; 9821 if (destAi.name == filterSi.name 9822 && destAi.packageName == filterSi.packageName) { 9823 return false; 9824 } 9825 } 9826 return true; 9827 } 9828 9829 @Override 9830 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9831 return new PackageParser.ServiceIntentInfo[size]; 9832 } 9833 9834 @Override 9835 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9836 if (!sUserManager.exists(userId)) return true; 9837 PackageParser.Package p = filter.service.owner; 9838 if (p != null) { 9839 PackageSetting ps = (PackageSetting)p.mExtras; 9840 if (ps != null) { 9841 // System apps are never considered stopped for purposes of 9842 // filtering, because there may be no way for the user to 9843 // actually re-launch them. 9844 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9845 && ps.getStopped(userId); 9846 } 9847 } 9848 return false; 9849 } 9850 9851 @Override 9852 protected boolean isPackageForFilter(String packageName, 9853 PackageParser.ServiceIntentInfo info) { 9854 return packageName.equals(info.service.owner.packageName); 9855 } 9856 9857 @Override 9858 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9859 int match, int userId) { 9860 if (!sUserManager.exists(userId)) return null; 9861 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9862 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9863 return null; 9864 } 9865 final PackageParser.Service service = info.service; 9866 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9867 if (ps == null) { 9868 return null; 9869 } 9870 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9871 ps.readUserState(userId), userId); 9872 if (si == null) { 9873 return null; 9874 } 9875 final ResolveInfo res = new ResolveInfo(); 9876 res.serviceInfo = si; 9877 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9878 res.filter = filter; 9879 } 9880 res.priority = info.getPriority(); 9881 res.preferredOrder = service.owner.mPreferredOrder; 9882 res.match = match; 9883 res.isDefault = info.hasDefault; 9884 res.labelRes = info.labelRes; 9885 res.nonLocalizedLabel = info.nonLocalizedLabel; 9886 res.icon = info.icon; 9887 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 9888 return res; 9889 } 9890 9891 @Override 9892 protected void sortResults(List<ResolveInfo> results) { 9893 Collections.sort(results, mResolvePrioritySorter); 9894 } 9895 9896 @Override 9897 protected void dumpFilter(PrintWriter out, String prefix, 9898 PackageParser.ServiceIntentInfo filter) { 9899 out.print(prefix); out.print( 9900 Integer.toHexString(System.identityHashCode(filter.service))); 9901 out.print(' '); 9902 filter.service.printComponentShortName(out); 9903 out.print(" filter "); 9904 out.println(Integer.toHexString(System.identityHashCode(filter))); 9905 } 9906 9907 @Override 9908 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 9909 return filter.service; 9910 } 9911 9912 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9913 PackageParser.Service service = (PackageParser.Service)label; 9914 out.print(prefix); out.print( 9915 Integer.toHexString(System.identityHashCode(service))); 9916 out.print(' '); 9917 service.printComponentShortName(out); 9918 if (count > 1) { 9919 out.print(" ("); out.print(count); out.print(" filters)"); 9920 } 9921 out.println(); 9922 } 9923 9924// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9925// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9926// final List<ResolveInfo> retList = Lists.newArrayList(); 9927// while (i.hasNext()) { 9928// final ResolveInfo resolveInfo = (ResolveInfo) i; 9929// if (isEnabledLP(resolveInfo.serviceInfo)) { 9930// retList.add(resolveInfo); 9931// } 9932// } 9933// return retList; 9934// } 9935 9936 // Keys are String (activity class name), values are Activity. 9937 private final ArrayMap<ComponentName, PackageParser.Service> mServices 9938 = new ArrayMap<ComponentName, PackageParser.Service>(); 9939 private int mFlags; 9940 }; 9941 9942 private final class ProviderIntentResolver 9943 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 9944 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9945 boolean defaultOnly, int userId) { 9946 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9947 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9948 } 9949 9950 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9951 int userId) { 9952 if (!sUserManager.exists(userId)) 9953 return null; 9954 mFlags = flags; 9955 return super.queryIntent(intent, resolvedType, 9956 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9957 } 9958 9959 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9960 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 9961 if (!sUserManager.exists(userId)) 9962 return null; 9963 if (packageProviders == null) { 9964 return null; 9965 } 9966 mFlags = flags; 9967 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 9968 final int N = packageProviders.size(); 9969 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 9970 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 9971 9972 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 9973 for (int i = 0; i < N; ++i) { 9974 intentFilters = packageProviders.get(i).intents; 9975 if (intentFilters != null && intentFilters.size() > 0) { 9976 PackageParser.ProviderIntentInfo[] array = 9977 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 9978 intentFilters.toArray(array); 9979 listCut.add(array); 9980 } 9981 } 9982 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9983 } 9984 9985 public final void addProvider(PackageParser.Provider p) { 9986 if (mProviders.containsKey(p.getComponentName())) { 9987 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 9988 return; 9989 } 9990 9991 mProviders.put(p.getComponentName(), p); 9992 if (DEBUG_SHOW_INFO) { 9993 Log.v(TAG, " " 9994 + (p.info.nonLocalizedLabel != null 9995 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 9996 Log.v(TAG, " Class=" + p.info.name); 9997 } 9998 final int NI = p.intents.size(); 9999 int j; 10000 for (j = 0; j < NI; j++) { 10001 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10002 if (DEBUG_SHOW_INFO) { 10003 Log.v(TAG, " IntentFilter:"); 10004 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10005 } 10006 if (!intent.debugCheck()) { 10007 Log.w(TAG, "==> For Provider " + p.info.name); 10008 } 10009 addFilter(intent); 10010 } 10011 } 10012 10013 public final void removeProvider(PackageParser.Provider p) { 10014 mProviders.remove(p.getComponentName()); 10015 if (DEBUG_SHOW_INFO) { 10016 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10017 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10018 Log.v(TAG, " Class=" + p.info.name); 10019 } 10020 final int NI = p.intents.size(); 10021 int j; 10022 for (j = 0; j < NI; j++) { 10023 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10024 if (DEBUG_SHOW_INFO) { 10025 Log.v(TAG, " IntentFilter:"); 10026 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10027 } 10028 removeFilter(intent); 10029 } 10030 } 10031 10032 @Override 10033 protected boolean allowFilterResult( 10034 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10035 ProviderInfo filterPi = filter.provider.info; 10036 for (int i = dest.size() - 1; i >= 0; i--) { 10037 ProviderInfo destPi = dest.get(i).providerInfo; 10038 if (destPi.name == filterPi.name 10039 && destPi.packageName == filterPi.packageName) { 10040 return false; 10041 } 10042 } 10043 return true; 10044 } 10045 10046 @Override 10047 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10048 return new PackageParser.ProviderIntentInfo[size]; 10049 } 10050 10051 @Override 10052 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10053 if (!sUserManager.exists(userId)) 10054 return true; 10055 PackageParser.Package p = filter.provider.owner; 10056 if (p != null) { 10057 PackageSetting ps = (PackageSetting) p.mExtras; 10058 if (ps != null) { 10059 // System apps are never considered stopped for purposes of 10060 // filtering, because there may be no way for the user to 10061 // actually re-launch them. 10062 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10063 && ps.getStopped(userId); 10064 } 10065 } 10066 return false; 10067 } 10068 10069 @Override 10070 protected boolean isPackageForFilter(String packageName, 10071 PackageParser.ProviderIntentInfo info) { 10072 return packageName.equals(info.provider.owner.packageName); 10073 } 10074 10075 @Override 10076 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10077 int match, int userId) { 10078 if (!sUserManager.exists(userId)) 10079 return null; 10080 final PackageParser.ProviderIntentInfo info = filter; 10081 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10082 return null; 10083 } 10084 final PackageParser.Provider provider = info.provider; 10085 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10086 if (ps == null) { 10087 return null; 10088 } 10089 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10090 ps.readUserState(userId), userId); 10091 if (pi == null) { 10092 return null; 10093 } 10094 final ResolveInfo res = new ResolveInfo(); 10095 res.providerInfo = pi; 10096 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10097 res.filter = filter; 10098 } 10099 res.priority = info.getPriority(); 10100 res.preferredOrder = provider.owner.mPreferredOrder; 10101 res.match = match; 10102 res.isDefault = info.hasDefault; 10103 res.labelRes = info.labelRes; 10104 res.nonLocalizedLabel = info.nonLocalizedLabel; 10105 res.icon = info.icon; 10106 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10107 return res; 10108 } 10109 10110 @Override 10111 protected void sortResults(List<ResolveInfo> results) { 10112 Collections.sort(results, mResolvePrioritySorter); 10113 } 10114 10115 @Override 10116 protected void dumpFilter(PrintWriter out, String prefix, 10117 PackageParser.ProviderIntentInfo filter) { 10118 out.print(prefix); 10119 out.print( 10120 Integer.toHexString(System.identityHashCode(filter.provider))); 10121 out.print(' '); 10122 filter.provider.printComponentShortName(out); 10123 out.print(" filter "); 10124 out.println(Integer.toHexString(System.identityHashCode(filter))); 10125 } 10126 10127 @Override 10128 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10129 return filter.provider; 10130 } 10131 10132 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10133 PackageParser.Provider provider = (PackageParser.Provider)label; 10134 out.print(prefix); out.print( 10135 Integer.toHexString(System.identityHashCode(provider))); 10136 out.print(' '); 10137 provider.printComponentShortName(out); 10138 if (count > 1) { 10139 out.print(" ("); out.print(count); out.print(" filters)"); 10140 } 10141 out.println(); 10142 } 10143 10144 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10145 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10146 private int mFlags; 10147 } 10148 10149 private static final class EphemeralIntentResolver 10150 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10151 @Override 10152 protected EphemeralResolveIntentInfo[] newArray(int size) { 10153 return new EphemeralResolveIntentInfo[size]; 10154 } 10155 10156 @Override 10157 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10158 return true; 10159 } 10160 10161 @Override 10162 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10163 int userId) { 10164 if (!sUserManager.exists(userId)) { 10165 return null; 10166 } 10167 return info.getEphemeralResolveInfo(); 10168 } 10169 } 10170 10171 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10172 new Comparator<ResolveInfo>() { 10173 public int compare(ResolveInfo r1, ResolveInfo r2) { 10174 int v1 = r1.priority; 10175 int v2 = r2.priority; 10176 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10177 if (v1 != v2) { 10178 return (v1 > v2) ? -1 : 1; 10179 } 10180 v1 = r1.preferredOrder; 10181 v2 = r2.preferredOrder; 10182 if (v1 != v2) { 10183 return (v1 > v2) ? -1 : 1; 10184 } 10185 if (r1.isDefault != r2.isDefault) { 10186 return r1.isDefault ? -1 : 1; 10187 } 10188 v1 = r1.match; 10189 v2 = r2.match; 10190 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10191 if (v1 != v2) { 10192 return (v1 > v2) ? -1 : 1; 10193 } 10194 if (r1.system != r2.system) { 10195 return r1.system ? -1 : 1; 10196 } 10197 if (r1.activityInfo != null) { 10198 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10199 } 10200 if (r1.serviceInfo != null) { 10201 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10202 } 10203 if (r1.providerInfo != null) { 10204 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10205 } 10206 return 0; 10207 } 10208 }; 10209 10210 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10211 new Comparator<ProviderInfo>() { 10212 public int compare(ProviderInfo p1, ProviderInfo p2) { 10213 final int v1 = p1.initOrder; 10214 final int v2 = p2.initOrder; 10215 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10216 } 10217 }; 10218 10219 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10220 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10221 final int[] userIds) { 10222 mHandler.post(new Runnable() { 10223 @Override 10224 public void run() { 10225 try { 10226 final IActivityManager am = ActivityManagerNative.getDefault(); 10227 if (am == null) return; 10228 final int[] resolvedUserIds; 10229 if (userIds == null) { 10230 resolvedUserIds = am.getRunningUserIds(); 10231 } else { 10232 resolvedUserIds = userIds; 10233 } 10234 for (int id : resolvedUserIds) { 10235 final Intent intent = new Intent(action, 10236 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10237 if (extras != null) { 10238 intent.putExtras(extras); 10239 } 10240 if (targetPkg != null) { 10241 intent.setPackage(targetPkg); 10242 } 10243 // Modify the UID when posting to other users 10244 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10245 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10246 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10247 intent.putExtra(Intent.EXTRA_UID, uid); 10248 } 10249 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10250 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10251 if (DEBUG_BROADCASTS) { 10252 RuntimeException here = new RuntimeException("here"); 10253 here.fillInStackTrace(); 10254 Slog.d(TAG, "Sending to user " + id + ": " 10255 + intent.toShortString(false, true, false, false) 10256 + " " + intent.getExtras(), here); 10257 } 10258 am.broadcastIntent(null, intent, null, finishedReceiver, 10259 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10260 null, finishedReceiver != null, false, id); 10261 } 10262 } catch (RemoteException ex) { 10263 } 10264 } 10265 }); 10266 } 10267 10268 /** 10269 * Check if the external storage media is available. This is true if there 10270 * is a mounted external storage medium or if the external storage is 10271 * emulated. 10272 */ 10273 private boolean isExternalMediaAvailable() { 10274 return mMediaMounted || Environment.isExternalStorageEmulated(); 10275 } 10276 10277 @Override 10278 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10279 // writer 10280 synchronized (mPackages) { 10281 if (!isExternalMediaAvailable()) { 10282 // If the external storage is no longer mounted at this point, 10283 // the caller may not have been able to delete all of this 10284 // packages files and can not delete any more. Bail. 10285 return null; 10286 } 10287 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10288 if (lastPackage != null) { 10289 pkgs.remove(lastPackage); 10290 } 10291 if (pkgs.size() > 0) { 10292 return pkgs.get(0); 10293 } 10294 } 10295 return null; 10296 } 10297 10298 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10299 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10300 userId, andCode ? 1 : 0, packageName); 10301 if (mSystemReady) { 10302 msg.sendToTarget(); 10303 } else { 10304 if (mPostSystemReadyMessages == null) { 10305 mPostSystemReadyMessages = new ArrayList<>(); 10306 } 10307 mPostSystemReadyMessages.add(msg); 10308 } 10309 } 10310 10311 void startCleaningPackages() { 10312 // reader 10313 synchronized (mPackages) { 10314 if (!isExternalMediaAvailable()) { 10315 return; 10316 } 10317 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10318 return; 10319 } 10320 } 10321 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10322 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10323 IActivityManager am = ActivityManagerNative.getDefault(); 10324 if (am != null) { 10325 try { 10326 am.startService(null, intent, null, mContext.getOpPackageName(), 10327 UserHandle.USER_SYSTEM); 10328 } catch (RemoteException e) { 10329 } 10330 } 10331 } 10332 10333 @Override 10334 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10335 int installFlags, String installerPackageName, int userId) { 10336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10337 10338 final int callingUid = Binder.getCallingUid(); 10339 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 10340 10341 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10342 try { 10343 if (observer != null) { 10344 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10345 } 10346 } catch (RemoteException re) { 10347 } 10348 return; 10349 } 10350 10351 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10352 installFlags |= PackageManager.INSTALL_FROM_ADB; 10353 10354 } else { 10355 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10356 // about installerPackageName. 10357 10358 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10359 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10360 } 10361 10362 UserHandle user; 10363 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10364 user = UserHandle.ALL; 10365 } else { 10366 user = new UserHandle(userId); 10367 } 10368 10369 // Only system components can circumvent runtime permissions when installing. 10370 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10371 && mContext.checkCallingOrSelfPermission(Manifest.permission 10372 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10373 throw new SecurityException("You need the " 10374 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10375 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10376 } 10377 10378 final File originFile = new File(originPath); 10379 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10380 10381 final Message msg = mHandler.obtainMessage(INIT_COPY); 10382 final VerificationInfo verificationInfo = new VerificationInfo( 10383 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10384 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10385 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10386 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10387 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10388 msg.obj = params; 10389 10390 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10391 System.identityHashCode(msg.obj)); 10392 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10393 System.identityHashCode(msg.obj)); 10394 10395 mHandler.sendMessage(msg); 10396 } 10397 10398 void installStage(String packageName, File stagedDir, String stagedCid, 10399 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10400 String installerPackageName, int installerUid, UserHandle user) { 10401 if (DEBUG_EPHEMERAL) { 10402 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10403 Slog.d(TAG, "Ephemeral install of " + packageName); 10404 } 10405 } 10406 final VerificationInfo verificationInfo = new VerificationInfo( 10407 sessionParams.originatingUri, sessionParams.referrerUri, 10408 sessionParams.originatingUid, installerUid); 10409 10410 final OriginInfo origin; 10411 if (stagedDir != null) { 10412 origin = OriginInfo.fromStagedFile(stagedDir); 10413 } else { 10414 origin = OriginInfo.fromStagedContainer(stagedCid); 10415 } 10416 10417 final Message msg = mHandler.obtainMessage(INIT_COPY); 10418 final InstallParams params = new InstallParams(origin, null, observer, 10419 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10420 verificationInfo, user, sessionParams.abiOverride, 10421 sessionParams.grantedRuntimePermissions); 10422 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10423 msg.obj = params; 10424 10425 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10426 System.identityHashCode(msg.obj)); 10427 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10428 System.identityHashCode(msg.obj)); 10429 10430 mHandler.sendMessage(msg); 10431 } 10432 10433 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 10434 Bundle extras = new Bundle(1); 10435 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 10436 10437 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10438 packageName, extras, 0, null, null, new int[] {userId}); 10439 try { 10440 IActivityManager am = ActivityManagerNative.getDefault(); 10441 final boolean isSystem = 10442 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10443 if (isSystem && am.isUserRunning(userId, 0)) { 10444 // The just-installed/enabled app is bundled on the system, so presumed 10445 // to be able to run automatically without needing an explicit launch. 10446 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10447 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10448 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10449 .setPackage(packageName); 10450 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10451 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10452 } 10453 } catch (RemoteException e) { 10454 // shouldn't happen 10455 Slog.w(TAG, "Unable to bootstrap installed package", e); 10456 } 10457 } 10458 10459 @Override 10460 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10461 int userId) { 10462 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10463 PackageSetting pkgSetting; 10464 final int uid = Binder.getCallingUid(); 10465 enforceCrossUserPermission(uid, userId, true, true, 10466 "setApplicationHiddenSetting for user " + userId); 10467 10468 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10469 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10470 return false; 10471 } 10472 10473 long callingId = Binder.clearCallingIdentity(); 10474 try { 10475 boolean sendAdded = false; 10476 boolean sendRemoved = false; 10477 // writer 10478 synchronized (mPackages) { 10479 pkgSetting = mSettings.mPackages.get(packageName); 10480 if (pkgSetting == null) { 10481 return false; 10482 } 10483 if (pkgSetting.getHidden(userId) != hidden) { 10484 pkgSetting.setHidden(hidden, userId); 10485 mSettings.writePackageRestrictionsLPr(userId); 10486 if (hidden) { 10487 sendRemoved = true; 10488 } else { 10489 sendAdded = true; 10490 } 10491 } 10492 } 10493 if (sendAdded) { 10494 sendPackageAddedForUser(packageName, pkgSetting, userId); 10495 return true; 10496 } 10497 if (sendRemoved) { 10498 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10499 "hiding pkg"); 10500 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10501 return true; 10502 } 10503 } finally { 10504 Binder.restoreCallingIdentity(callingId); 10505 } 10506 return false; 10507 } 10508 10509 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10510 int userId) { 10511 final PackageRemovedInfo info = new PackageRemovedInfo(); 10512 info.removedPackage = packageName; 10513 info.removedUsers = new int[] {userId}; 10514 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10515 info.sendBroadcast(false, false, false); 10516 } 10517 10518 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10519 if (pkgList.length > 0) { 10520 Bundle extras = new Bundle(1); 10521 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10522 10523 sendPackageBroadcast( 10524 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10525 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10526 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10527 new int[] {userId}); 10528 } 10529 } 10530 10531 /** 10532 * Returns true if application is not found or there was an error. Otherwise it returns 10533 * the hidden state of the package for the given user. 10534 */ 10535 @Override 10536 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10537 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10538 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 10539 false, "getApplicationHidden for user " + userId); 10540 PackageSetting pkgSetting; 10541 long callingId = Binder.clearCallingIdentity(); 10542 try { 10543 // writer 10544 synchronized (mPackages) { 10545 pkgSetting = mSettings.mPackages.get(packageName); 10546 if (pkgSetting == null) { 10547 return true; 10548 } 10549 return pkgSetting.getHidden(userId); 10550 } 10551 } finally { 10552 Binder.restoreCallingIdentity(callingId); 10553 } 10554 } 10555 10556 /** 10557 * @hide 10558 */ 10559 @Override 10560 public int installExistingPackageAsUser(String packageName, int userId) { 10561 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10562 null); 10563 PackageSetting pkgSetting; 10564 final int uid = Binder.getCallingUid(); 10565 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 10566 + userId); 10567 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10568 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10569 } 10570 10571 long callingId = Binder.clearCallingIdentity(); 10572 try { 10573 boolean installed = false; 10574 10575 // writer 10576 synchronized (mPackages) { 10577 pkgSetting = mSettings.mPackages.get(packageName); 10578 if (pkgSetting == null) { 10579 return PackageManager.INSTALL_FAILED_INVALID_URI; 10580 } 10581 if (!pkgSetting.getInstalled(userId)) { 10582 pkgSetting.setInstalled(true, userId); 10583 pkgSetting.setHidden(false, userId); 10584 mSettings.writePackageRestrictionsLPr(userId); 10585 if (pkgSetting.pkg != null) { 10586 prepareAppDataAfterInstall(pkgSetting.pkg); 10587 } 10588 installed = true; 10589 } 10590 } 10591 10592 if (installed) { 10593 sendPackageAddedForUser(packageName, pkgSetting, userId); 10594 } 10595 } finally { 10596 Binder.restoreCallingIdentity(callingId); 10597 } 10598 10599 return PackageManager.INSTALL_SUCCEEDED; 10600 } 10601 10602 boolean isUserRestricted(int userId, String restrictionKey) { 10603 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10604 if (restrictions.getBoolean(restrictionKey, false)) { 10605 Log.w(TAG, "User is restricted: " + restrictionKey); 10606 return true; 10607 } 10608 return false; 10609 } 10610 10611 @Override 10612 public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) { 10613 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10614 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true, 10615 "setPackageSuspended for user " + userId); 10616 10617 // TODO: investigate and add more restrictions for suspending crucial packages. 10618 if (isPackageDeviceAdmin(packageName, userId)) { 10619 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10620 + "\": has active device admin"); 10621 return false; 10622 } 10623 10624 long callingId = Binder.clearCallingIdentity(); 10625 try { 10626 boolean changed = false; 10627 boolean success = false; 10628 int appId = -1; 10629 synchronized (mPackages) { 10630 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10631 if (pkgSetting != null) { 10632 if (pkgSetting.getSuspended(userId) != suspended) { 10633 pkgSetting.setSuspended(suspended, userId); 10634 mSettings.writePackageRestrictionsLPr(userId); 10635 appId = pkgSetting.appId; 10636 changed = true; 10637 } 10638 success = true; 10639 } 10640 } 10641 10642 if (changed) { 10643 sendPackagesSuspendedForUser(new String[]{packageName}, userId, suspended); 10644 if (suspended) { 10645 killApplication(packageName, UserHandle.getUid(userId, appId), 10646 "suspending package"); 10647 } 10648 } 10649 return success; 10650 } finally { 10651 Binder.restoreCallingIdentity(callingId); 10652 } 10653 } 10654 10655 @Override 10656 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10657 mContext.enforceCallingOrSelfPermission( 10658 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10659 "Only package verification agents can verify applications"); 10660 10661 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10662 final PackageVerificationResponse response = new PackageVerificationResponse( 10663 verificationCode, Binder.getCallingUid()); 10664 msg.arg1 = id; 10665 msg.obj = response; 10666 mHandler.sendMessage(msg); 10667 } 10668 10669 @Override 10670 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10671 long millisecondsToDelay) { 10672 mContext.enforceCallingOrSelfPermission( 10673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10674 "Only package verification agents can extend verification timeouts"); 10675 10676 final PackageVerificationState state = mPendingVerification.get(id); 10677 final PackageVerificationResponse response = new PackageVerificationResponse( 10678 verificationCodeAtTimeout, Binder.getCallingUid()); 10679 10680 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10681 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10682 } 10683 if (millisecondsToDelay < 0) { 10684 millisecondsToDelay = 0; 10685 } 10686 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10687 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10688 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10689 } 10690 10691 if ((state != null) && !state.timeoutExtended()) { 10692 state.extendTimeout(); 10693 10694 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10695 msg.arg1 = id; 10696 msg.obj = response; 10697 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10698 } 10699 } 10700 10701 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10702 int verificationCode, UserHandle user) { 10703 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10704 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10705 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10706 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10707 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10708 10709 mContext.sendBroadcastAsUser(intent, user, 10710 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10711 } 10712 10713 private ComponentName matchComponentForVerifier(String packageName, 10714 List<ResolveInfo> receivers) { 10715 ActivityInfo targetReceiver = null; 10716 10717 final int NR = receivers.size(); 10718 for (int i = 0; i < NR; i++) { 10719 final ResolveInfo info = receivers.get(i); 10720 if (info.activityInfo == null) { 10721 continue; 10722 } 10723 10724 if (packageName.equals(info.activityInfo.packageName)) { 10725 targetReceiver = info.activityInfo; 10726 break; 10727 } 10728 } 10729 10730 if (targetReceiver == null) { 10731 return null; 10732 } 10733 10734 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10735 } 10736 10737 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10738 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10739 if (pkgInfo.verifiers.length == 0) { 10740 return null; 10741 } 10742 10743 final int N = pkgInfo.verifiers.length; 10744 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10745 for (int i = 0; i < N; i++) { 10746 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10747 10748 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10749 receivers); 10750 if (comp == null) { 10751 continue; 10752 } 10753 10754 final int verifierUid = getUidForVerifier(verifierInfo); 10755 if (verifierUid == -1) { 10756 continue; 10757 } 10758 10759 if (DEBUG_VERIFY) { 10760 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10761 + " with the correct signature"); 10762 } 10763 sufficientVerifiers.add(comp); 10764 verificationState.addSufficientVerifier(verifierUid); 10765 } 10766 10767 return sufficientVerifiers; 10768 } 10769 10770 private int getUidForVerifier(VerifierInfo verifierInfo) { 10771 synchronized (mPackages) { 10772 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10773 if (pkg == null) { 10774 return -1; 10775 } else if (pkg.mSignatures.length != 1) { 10776 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10777 + " has more than one signature; ignoring"); 10778 return -1; 10779 } 10780 10781 /* 10782 * If the public key of the package's signature does not match 10783 * our expected public key, then this is a different package and 10784 * we should skip. 10785 */ 10786 10787 final byte[] expectedPublicKey; 10788 try { 10789 final Signature verifierSig = pkg.mSignatures[0]; 10790 final PublicKey publicKey = verifierSig.getPublicKey(); 10791 expectedPublicKey = publicKey.getEncoded(); 10792 } catch (CertificateException e) { 10793 return -1; 10794 } 10795 10796 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10797 10798 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10799 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10800 + " does not have the expected public key; ignoring"); 10801 return -1; 10802 } 10803 10804 return pkg.applicationInfo.uid; 10805 } 10806 } 10807 10808 @Override 10809 public void finishPackageInstall(int token) { 10810 enforceSystemOrRoot("Only the system is allowed to finish installs"); 10811 10812 if (DEBUG_INSTALL) { 10813 Slog.v(TAG, "BM finishing package install for " + token); 10814 } 10815 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 10816 10817 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 10818 mHandler.sendMessage(msg); 10819 } 10820 10821 /** 10822 * Get the verification agent timeout. 10823 * 10824 * @return verification timeout in milliseconds 10825 */ 10826 private long getVerificationTimeout() { 10827 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 10828 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 10829 DEFAULT_VERIFICATION_TIMEOUT); 10830 } 10831 10832 /** 10833 * Get the default verification agent response code. 10834 * 10835 * @return default verification response code 10836 */ 10837 private int getDefaultVerificationResponse() { 10838 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10839 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 10840 DEFAULT_VERIFICATION_RESPONSE); 10841 } 10842 10843 /** 10844 * Check whether or not package verification has been enabled. 10845 * 10846 * @return true if verification should be performed 10847 */ 10848 private boolean isVerificationEnabled(int userId, int installFlags) { 10849 if (!DEFAULT_VERIFY_ENABLE) { 10850 return false; 10851 } 10852 // Ephemeral apps don't get the full verification treatment 10853 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10854 if (DEBUG_EPHEMERAL) { 10855 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 10856 } 10857 return false; 10858 } 10859 10860 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 10861 10862 // Check if installing from ADB 10863 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 10864 // Do not run verification in a test harness environment 10865 if (ActivityManager.isRunningInTestHarness()) { 10866 return false; 10867 } 10868 if (ensureVerifyAppsEnabled) { 10869 return true; 10870 } 10871 // Check if the developer does not want package verification for ADB installs 10872 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10873 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 10874 return false; 10875 } 10876 } 10877 10878 if (ensureVerifyAppsEnabled) { 10879 return true; 10880 } 10881 10882 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10883 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 10884 } 10885 10886 @Override 10887 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 10888 throws RemoteException { 10889 mContext.enforceCallingOrSelfPermission( 10890 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 10891 "Only intentfilter verification agents can verify applications"); 10892 10893 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 10894 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 10895 Binder.getCallingUid(), verificationCode, failedDomains); 10896 msg.arg1 = id; 10897 msg.obj = response; 10898 mHandler.sendMessage(msg); 10899 } 10900 10901 @Override 10902 public int getIntentVerificationStatus(String packageName, int userId) { 10903 synchronized (mPackages) { 10904 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 10905 } 10906 } 10907 10908 @Override 10909 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 10910 mContext.enforceCallingOrSelfPermission( 10911 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10912 10913 boolean result = false; 10914 synchronized (mPackages) { 10915 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 10916 } 10917 if (result) { 10918 scheduleWritePackageRestrictionsLocked(userId); 10919 } 10920 return result; 10921 } 10922 10923 @Override 10924 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 10925 synchronized (mPackages) { 10926 return mSettings.getIntentFilterVerificationsLPr(packageName); 10927 } 10928 } 10929 10930 @Override 10931 public List<IntentFilter> getAllIntentFilters(String packageName) { 10932 if (TextUtils.isEmpty(packageName)) { 10933 return Collections.<IntentFilter>emptyList(); 10934 } 10935 synchronized (mPackages) { 10936 PackageParser.Package pkg = mPackages.get(packageName); 10937 if (pkg == null || pkg.activities == null) { 10938 return Collections.<IntentFilter>emptyList(); 10939 } 10940 final int count = pkg.activities.size(); 10941 ArrayList<IntentFilter> result = new ArrayList<>(); 10942 for (int n=0; n<count; n++) { 10943 PackageParser.Activity activity = pkg.activities.get(n); 10944 if (activity.intents != null && activity.intents.size() > 0) { 10945 result.addAll(activity.intents); 10946 } 10947 } 10948 return result; 10949 } 10950 } 10951 10952 @Override 10953 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 10954 mContext.enforceCallingOrSelfPermission( 10955 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10956 10957 synchronized (mPackages) { 10958 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 10959 if (packageName != null) { 10960 result |= updateIntentVerificationStatus(packageName, 10961 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 10962 userId); 10963 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 10964 packageName, userId); 10965 } 10966 return result; 10967 } 10968 } 10969 10970 @Override 10971 public String getDefaultBrowserPackageName(int userId) { 10972 synchronized (mPackages) { 10973 return mSettings.getDefaultBrowserPackageNameLPw(userId); 10974 } 10975 } 10976 10977 /** 10978 * Get the "allow unknown sources" setting. 10979 * 10980 * @return the current "allow unknown sources" setting 10981 */ 10982 private int getUnknownSourcesSettings() { 10983 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10984 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 10985 -1); 10986 } 10987 10988 @Override 10989 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 10990 final int uid = Binder.getCallingUid(); 10991 // writer 10992 synchronized (mPackages) { 10993 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 10994 if (targetPackageSetting == null) { 10995 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 10996 } 10997 10998 PackageSetting installerPackageSetting; 10999 if (installerPackageName != null) { 11000 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11001 if (installerPackageSetting == null) { 11002 throw new IllegalArgumentException("Unknown installer package: " 11003 + installerPackageName); 11004 } 11005 } else { 11006 installerPackageSetting = null; 11007 } 11008 11009 Signature[] callerSignature; 11010 Object obj = mSettings.getUserIdLPr(uid); 11011 if (obj != null) { 11012 if (obj instanceof SharedUserSetting) { 11013 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11014 } else if (obj instanceof PackageSetting) { 11015 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11016 } else { 11017 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11018 } 11019 } else { 11020 throw new SecurityException("Unknown calling UID: " + uid); 11021 } 11022 11023 // Verify: can't set installerPackageName to a package that is 11024 // not signed with the same cert as the caller. 11025 if (installerPackageSetting != null) { 11026 if (compareSignatures(callerSignature, 11027 installerPackageSetting.signatures.mSignatures) 11028 != PackageManager.SIGNATURE_MATCH) { 11029 throw new SecurityException( 11030 "Caller does not have same cert as new installer package " 11031 + installerPackageName); 11032 } 11033 } 11034 11035 // Verify: if target already has an installer package, it must 11036 // be signed with the same cert as the caller. 11037 if (targetPackageSetting.installerPackageName != null) { 11038 PackageSetting setting = mSettings.mPackages.get( 11039 targetPackageSetting.installerPackageName); 11040 // If the currently set package isn't valid, then it's always 11041 // okay to change it. 11042 if (setting != null) { 11043 if (compareSignatures(callerSignature, 11044 setting.signatures.mSignatures) 11045 != PackageManager.SIGNATURE_MATCH) { 11046 throw new SecurityException( 11047 "Caller does not have same cert as old installer package " 11048 + targetPackageSetting.installerPackageName); 11049 } 11050 } 11051 } 11052 11053 // Okay! 11054 targetPackageSetting.installerPackageName = installerPackageName; 11055 scheduleWriteSettingsLocked(); 11056 } 11057 } 11058 11059 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11060 // Queue up an async operation since the package installation may take a little while. 11061 mHandler.post(new Runnable() { 11062 public void run() { 11063 mHandler.removeCallbacks(this); 11064 // Result object to be returned 11065 PackageInstalledInfo res = new PackageInstalledInfo(); 11066 res.returnCode = currentStatus; 11067 res.uid = -1; 11068 res.pkg = null; 11069 res.removedInfo = new PackageRemovedInfo(); 11070 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11071 args.doPreInstall(res.returnCode); 11072 synchronized (mInstallLock) { 11073 installPackageTracedLI(args, res); 11074 } 11075 args.doPostInstall(res.returnCode, res.uid); 11076 } 11077 11078 // A restore should be performed at this point if (a) the install 11079 // succeeded, (b) the operation is not an update, and (c) the new 11080 // package has not opted out of backup participation. 11081 final boolean update = res.removedInfo.removedPackage != null; 11082 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11083 boolean doRestore = !update 11084 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11085 11086 // Set up the post-install work request bookkeeping. This will be used 11087 // and cleaned up by the post-install event handling regardless of whether 11088 // there's a restore pass performed. Token values are >= 1. 11089 int token; 11090 if (mNextInstallToken < 0) mNextInstallToken = 1; 11091 token = mNextInstallToken++; 11092 11093 PostInstallData data = new PostInstallData(args, res); 11094 mRunningInstalls.put(token, data); 11095 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11096 11097 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11098 // Pass responsibility to the Backup Manager. It will perform a 11099 // restore if appropriate, then pass responsibility back to the 11100 // Package Manager to run the post-install observer callbacks 11101 // and broadcasts. 11102 IBackupManager bm = IBackupManager.Stub.asInterface( 11103 ServiceManager.getService(Context.BACKUP_SERVICE)); 11104 if (bm != null) { 11105 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11106 + " to BM for possible restore"); 11107 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11108 try { 11109 // TODO: http://b/22388012 11110 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11111 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11112 } else { 11113 doRestore = false; 11114 } 11115 } catch (RemoteException e) { 11116 // can't happen; the backup manager is local 11117 } catch (Exception e) { 11118 Slog.e(TAG, "Exception trying to enqueue restore", e); 11119 doRestore = false; 11120 } 11121 } else { 11122 Slog.e(TAG, "Backup Manager not found!"); 11123 doRestore = false; 11124 } 11125 } 11126 11127 if (!doRestore) { 11128 // No restore possible, or the Backup Manager was mysteriously not 11129 // available -- just fire the post-install work request directly. 11130 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11131 11132 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11133 11134 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11135 mHandler.sendMessage(msg); 11136 } 11137 } 11138 }); 11139 } 11140 11141 private abstract class HandlerParams { 11142 private static final int MAX_RETRIES = 4; 11143 11144 /** 11145 * Number of times startCopy() has been attempted and had a non-fatal 11146 * error. 11147 */ 11148 private int mRetries = 0; 11149 11150 /** User handle for the user requesting the information or installation. */ 11151 private final UserHandle mUser; 11152 String traceMethod; 11153 int traceCookie; 11154 11155 HandlerParams(UserHandle user) { 11156 mUser = user; 11157 } 11158 11159 UserHandle getUser() { 11160 return mUser; 11161 } 11162 11163 HandlerParams setTraceMethod(String traceMethod) { 11164 this.traceMethod = traceMethod; 11165 return this; 11166 } 11167 11168 HandlerParams setTraceCookie(int traceCookie) { 11169 this.traceCookie = traceCookie; 11170 return this; 11171 } 11172 11173 final boolean startCopy() { 11174 boolean res; 11175 try { 11176 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11177 11178 if (++mRetries > MAX_RETRIES) { 11179 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11180 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11181 handleServiceError(); 11182 return false; 11183 } else { 11184 handleStartCopy(); 11185 res = true; 11186 } 11187 } catch (RemoteException e) { 11188 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11189 mHandler.sendEmptyMessage(MCS_RECONNECT); 11190 res = false; 11191 } 11192 handleReturnCode(); 11193 return res; 11194 } 11195 11196 final void serviceError() { 11197 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11198 handleServiceError(); 11199 handleReturnCode(); 11200 } 11201 11202 abstract void handleStartCopy() throws RemoteException; 11203 abstract void handleServiceError(); 11204 abstract void handleReturnCode(); 11205 } 11206 11207 class MeasureParams extends HandlerParams { 11208 private final PackageStats mStats; 11209 private boolean mSuccess; 11210 11211 private final IPackageStatsObserver mObserver; 11212 11213 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11214 super(new UserHandle(stats.userHandle)); 11215 mObserver = observer; 11216 mStats = stats; 11217 } 11218 11219 @Override 11220 public String toString() { 11221 return "MeasureParams{" 11222 + Integer.toHexString(System.identityHashCode(this)) 11223 + " " + mStats.packageName + "}"; 11224 } 11225 11226 @Override 11227 void handleStartCopy() throws RemoteException { 11228 synchronized (mInstallLock) { 11229 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11230 } 11231 11232 if (mSuccess) { 11233 final boolean mounted; 11234 if (Environment.isExternalStorageEmulated()) { 11235 mounted = true; 11236 } else { 11237 final String status = Environment.getExternalStorageState(); 11238 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11239 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11240 } 11241 11242 if (mounted) { 11243 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11244 11245 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11246 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11247 11248 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11249 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11250 11251 // Always subtract cache size, since it's a subdirectory 11252 mStats.externalDataSize -= mStats.externalCacheSize; 11253 11254 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11255 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11256 11257 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11258 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11259 } 11260 } 11261 } 11262 11263 @Override 11264 void handleReturnCode() { 11265 if (mObserver != null) { 11266 try { 11267 mObserver.onGetStatsCompleted(mStats, mSuccess); 11268 } catch (RemoteException e) { 11269 Slog.i(TAG, "Observer no longer exists."); 11270 } 11271 } 11272 } 11273 11274 @Override 11275 void handleServiceError() { 11276 Slog.e(TAG, "Could not measure application " + mStats.packageName 11277 + " external storage"); 11278 } 11279 } 11280 11281 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11282 throws RemoteException { 11283 long result = 0; 11284 for (File path : paths) { 11285 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11286 } 11287 return result; 11288 } 11289 11290 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11291 for (File path : paths) { 11292 try { 11293 mcs.clearDirectory(path.getAbsolutePath()); 11294 } catch (RemoteException e) { 11295 } 11296 } 11297 } 11298 11299 static class OriginInfo { 11300 /** 11301 * Location where install is coming from, before it has been 11302 * copied/renamed into place. This could be a single monolithic APK 11303 * file, or a cluster directory. This location may be untrusted. 11304 */ 11305 final File file; 11306 final String cid; 11307 11308 /** 11309 * Flag indicating that {@link #file} or {@link #cid} has already been 11310 * staged, meaning downstream users don't need to defensively copy the 11311 * contents. 11312 */ 11313 final boolean staged; 11314 11315 /** 11316 * Flag indicating that {@link #file} or {@link #cid} is an already 11317 * installed app that is being moved. 11318 */ 11319 final boolean existing; 11320 11321 final String resolvedPath; 11322 final File resolvedFile; 11323 11324 static OriginInfo fromNothing() { 11325 return new OriginInfo(null, null, false, false); 11326 } 11327 11328 static OriginInfo fromUntrustedFile(File file) { 11329 return new OriginInfo(file, null, false, false); 11330 } 11331 11332 static OriginInfo fromExistingFile(File file) { 11333 return new OriginInfo(file, null, false, true); 11334 } 11335 11336 static OriginInfo fromStagedFile(File file) { 11337 return new OriginInfo(file, null, true, false); 11338 } 11339 11340 static OriginInfo fromStagedContainer(String cid) { 11341 return new OriginInfo(null, cid, true, false); 11342 } 11343 11344 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11345 this.file = file; 11346 this.cid = cid; 11347 this.staged = staged; 11348 this.existing = existing; 11349 11350 if (cid != null) { 11351 resolvedPath = PackageHelper.getSdDir(cid); 11352 resolvedFile = new File(resolvedPath); 11353 } else if (file != null) { 11354 resolvedPath = file.getAbsolutePath(); 11355 resolvedFile = file; 11356 } else { 11357 resolvedPath = null; 11358 resolvedFile = null; 11359 } 11360 } 11361 } 11362 11363 static class MoveInfo { 11364 final int moveId; 11365 final String fromUuid; 11366 final String toUuid; 11367 final String packageName; 11368 final String dataAppName; 11369 final int appId; 11370 final String seinfo; 11371 final int targetSdkVersion; 11372 11373 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11374 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11375 this.moveId = moveId; 11376 this.fromUuid = fromUuid; 11377 this.toUuid = toUuid; 11378 this.packageName = packageName; 11379 this.dataAppName = dataAppName; 11380 this.appId = appId; 11381 this.seinfo = seinfo; 11382 this.targetSdkVersion = targetSdkVersion; 11383 } 11384 } 11385 11386 static class VerificationInfo { 11387 /** A constant used to indicate that a uid value is not present. */ 11388 public static final int NO_UID = -1; 11389 11390 /** URI referencing where the package was downloaded from. */ 11391 final Uri originatingUri; 11392 11393 /** HTTP referrer URI associated with the originatingURI. */ 11394 final Uri referrer; 11395 11396 /** UID of the application that the install request originated from. */ 11397 final int originatingUid; 11398 11399 /** UID of application requesting the install */ 11400 final int installerUid; 11401 11402 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11403 this.originatingUri = originatingUri; 11404 this.referrer = referrer; 11405 this.originatingUid = originatingUid; 11406 this.installerUid = installerUid; 11407 } 11408 } 11409 11410 class InstallParams extends HandlerParams { 11411 final OriginInfo origin; 11412 final MoveInfo move; 11413 final IPackageInstallObserver2 observer; 11414 int installFlags; 11415 final String installerPackageName; 11416 final String volumeUuid; 11417 private InstallArgs mArgs; 11418 private int mRet; 11419 final String packageAbiOverride; 11420 final String[] grantedRuntimePermissions; 11421 final VerificationInfo verificationInfo; 11422 11423 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11424 int installFlags, String installerPackageName, String volumeUuid, 11425 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11426 String[] grantedPermissions) { 11427 super(user); 11428 this.origin = origin; 11429 this.move = move; 11430 this.observer = observer; 11431 this.installFlags = installFlags; 11432 this.installerPackageName = installerPackageName; 11433 this.volumeUuid = volumeUuid; 11434 this.verificationInfo = verificationInfo; 11435 this.packageAbiOverride = packageAbiOverride; 11436 this.grantedRuntimePermissions = grantedPermissions; 11437 } 11438 11439 @Override 11440 public String toString() { 11441 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11442 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11443 } 11444 11445 private int installLocationPolicy(PackageInfoLite pkgLite) { 11446 String packageName = pkgLite.packageName; 11447 int installLocation = pkgLite.installLocation; 11448 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11449 // reader 11450 synchronized (mPackages) { 11451 PackageParser.Package pkg = mPackages.get(packageName); 11452 if (pkg != null) { 11453 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11454 // Check for downgrading. 11455 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 11456 try { 11457 checkDowngrade(pkg, pkgLite); 11458 } catch (PackageManagerException e) { 11459 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11460 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11461 } 11462 } 11463 // Check for updated system application. 11464 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11465 if (onSd) { 11466 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11467 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11468 } 11469 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11470 } else { 11471 if (onSd) { 11472 // Install flag overrides everything. 11473 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11474 } 11475 // If current upgrade specifies particular preference 11476 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11477 // Application explicitly specified internal. 11478 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11479 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11480 // App explictly prefers external. Let policy decide 11481 } else { 11482 // Prefer previous location 11483 if (isExternal(pkg)) { 11484 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11485 } 11486 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11487 } 11488 } 11489 } else { 11490 // Invalid install. Return error code 11491 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11492 } 11493 } 11494 } 11495 // All the special cases have been taken care of. 11496 // Return result based on recommended install location. 11497 if (onSd) { 11498 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11499 } 11500 return pkgLite.recommendedInstallLocation; 11501 } 11502 11503 /* 11504 * Invoke remote method to get package information and install 11505 * location values. Override install location based on default 11506 * policy if needed and then create install arguments based 11507 * on the install location. 11508 */ 11509 public void handleStartCopy() throws RemoteException { 11510 int ret = PackageManager.INSTALL_SUCCEEDED; 11511 11512 // If we're already staged, we've firmly committed to an install location 11513 if (origin.staged) { 11514 if (origin.file != null) { 11515 installFlags |= PackageManager.INSTALL_INTERNAL; 11516 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11517 } else if (origin.cid != null) { 11518 installFlags |= PackageManager.INSTALL_EXTERNAL; 11519 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11520 } else { 11521 throw new IllegalStateException("Invalid stage location"); 11522 } 11523 } 11524 11525 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11526 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11527 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11528 PackageInfoLite pkgLite = null; 11529 11530 if (onInt && onSd) { 11531 // Check if both bits are set. 11532 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11533 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11534 } else if (onSd && ephemeral) { 11535 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11536 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11537 } else { 11538 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11539 packageAbiOverride); 11540 11541 if (DEBUG_EPHEMERAL && ephemeral) { 11542 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11543 } 11544 11545 /* 11546 * If we have too little free space, try to free cache 11547 * before giving up. 11548 */ 11549 if (!origin.staged && pkgLite.recommendedInstallLocation 11550 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11551 // TODO: focus freeing disk space on the target device 11552 final StorageManager storage = StorageManager.from(mContext); 11553 final long lowThreshold = storage.getStorageLowBytes( 11554 Environment.getDataDirectory()); 11555 11556 final long sizeBytes = mContainerService.calculateInstalledSize( 11557 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11558 11559 try { 11560 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11561 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11562 installFlags, packageAbiOverride); 11563 } catch (InstallerException e) { 11564 Slog.w(TAG, "Failed to free cache", e); 11565 } 11566 11567 /* 11568 * The cache free must have deleted the file we 11569 * downloaded to install. 11570 * 11571 * TODO: fix the "freeCache" call to not delete 11572 * the file we care about. 11573 */ 11574 if (pkgLite.recommendedInstallLocation 11575 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11576 pkgLite.recommendedInstallLocation 11577 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11578 } 11579 } 11580 } 11581 11582 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11583 int loc = pkgLite.recommendedInstallLocation; 11584 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11585 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11586 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11587 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11588 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11589 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11590 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11591 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11592 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11593 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11594 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11595 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11596 } else { 11597 // Override with defaults if needed. 11598 loc = installLocationPolicy(pkgLite); 11599 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11600 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11601 } else if (!onSd && !onInt) { 11602 // Override install location with flags 11603 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11604 // Set the flag to install on external media. 11605 installFlags |= PackageManager.INSTALL_EXTERNAL; 11606 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11607 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11608 if (DEBUG_EPHEMERAL) { 11609 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11610 } 11611 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11612 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11613 |PackageManager.INSTALL_INTERNAL); 11614 } else { 11615 // Make sure the flag for installing on external 11616 // media is unset 11617 installFlags |= PackageManager.INSTALL_INTERNAL; 11618 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11619 } 11620 } 11621 } 11622 } 11623 11624 final InstallArgs args = createInstallArgs(this); 11625 mArgs = args; 11626 11627 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11628 // TODO: http://b/22976637 11629 // Apps installed for "all" users use the device owner to verify the app 11630 UserHandle verifierUser = getUser(); 11631 if (verifierUser == UserHandle.ALL) { 11632 verifierUser = UserHandle.SYSTEM; 11633 } 11634 11635 /* 11636 * Determine if we have any installed package verifiers. If we 11637 * do, then we'll defer to them to verify the packages. 11638 */ 11639 final int requiredUid = mRequiredVerifierPackage == null ? -1 11640 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11641 verifierUser.getIdentifier()); 11642 if (!origin.existing && requiredUid != -1 11643 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11644 final Intent verification = new Intent( 11645 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11646 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11647 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11648 PACKAGE_MIME_TYPE); 11649 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11650 11651 // Query all live verifiers based on current user state 11652 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 11653 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11654 11655 if (DEBUG_VERIFY) { 11656 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11657 + verification.toString() + " with " + pkgLite.verifiers.length 11658 + " optional verifiers"); 11659 } 11660 11661 final int verificationId = mPendingVerificationToken++; 11662 11663 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11664 11665 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11666 installerPackageName); 11667 11668 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11669 installFlags); 11670 11671 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11672 pkgLite.packageName); 11673 11674 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11675 pkgLite.versionCode); 11676 11677 if (verificationInfo != null) { 11678 if (verificationInfo.originatingUri != null) { 11679 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11680 verificationInfo.originatingUri); 11681 } 11682 if (verificationInfo.referrer != null) { 11683 verification.putExtra(Intent.EXTRA_REFERRER, 11684 verificationInfo.referrer); 11685 } 11686 if (verificationInfo.originatingUid >= 0) { 11687 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11688 verificationInfo.originatingUid); 11689 } 11690 if (verificationInfo.installerUid >= 0) { 11691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11692 verificationInfo.installerUid); 11693 } 11694 } 11695 11696 final PackageVerificationState verificationState = new PackageVerificationState( 11697 requiredUid, args); 11698 11699 mPendingVerification.append(verificationId, verificationState); 11700 11701 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11702 receivers, verificationState); 11703 11704 /* 11705 * If any sufficient verifiers were listed in the package 11706 * manifest, attempt to ask them. 11707 */ 11708 if (sufficientVerifiers != null) { 11709 final int N = sufficientVerifiers.size(); 11710 if (N == 0) { 11711 Slog.i(TAG, "Additional verifiers required, but none installed."); 11712 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11713 } else { 11714 for (int i = 0; i < N; i++) { 11715 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11716 11717 final Intent sufficientIntent = new Intent(verification); 11718 sufficientIntent.setComponent(verifierComponent); 11719 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11720 } 11721 } 11722 } 11723 11724 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11725 mRequiredVerifierPackage, receivers); 11726 if (ret == PackageManager.INSTALL_SUCCEEDED 11727 && mRequiredVerifierPackage != null) { 11728 Trace.asyncTraceBegin( 11729 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11730 /* 11731 * Send the intent to the required verification agent, 11732 * but only start the verification timeout after the 11733 * target BroadcastReceivers have run. 11734 */ 11735 verification.setComponent(requiredVerifierComponent); 11736 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11737 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11738 new BroadcastReceiver() { 11739 @Override 11740 public void onReceive(Context context, Intent intent) { 11741 final Message msg = mHandler 11742 .obtainMessage(CHECK_PENDING_VERIFICATION); 11743 msg.arg1 = verificationId; 11744 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11745 } 11746 }, null, 0, null, null); 11747 11748 /* 11749 * We don't want the copy to proceed until verification 11750 * succeeds, so null out this field. 11751 */ 11752 mArgs = null; 11753 } 11754 } else { 11755 /* 11756 * No package verification is enabled, so immediately start 11757 * the remote call to initiate copy using temporary file. 11758 */ 11759 ret = args.copyApk(mContainerService, true); 11760 } 11761 } 11762 11763 mRet = ret; 11764 } 11765 11766 @Override 11767 void handleReturnCode() { 11768 // If mArgs is null, then MCS couldn't be reached. When it 11769 // reconnects, it will try again to install. At that point, this 11770 // will succeed. 11771 if (mArgs != null) { 11772 processPendingInstall(mArgs, mRet); 11773 } 11774 } 11775 11776 @Override 11777 void handleServiceError() { 11778 mArgs = createInstallArgs(this); 11779 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11780 } 11781 11782 public boolean isForwardLocked() { 11783 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11784 } 11785 } 11786 11787 /** 11788 * Used during creation of InstallArgs 11789 * 11790 * @param installFlags package installation flags 11791 * @return true if should be installed on external storage 11792 */ 11793 private static boolean installOnExternalAsec(int installFlags) { 11794 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 11795 return false; 11796 } 11797 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 11798 return true; 11799 } 11800 return false; 11801 } 11802 11803 /** 11804 * Used during creation of InstallArgs 11805 * 11806 * @param installFlags package installation flags 11807 * @return true if should be installed as forward locked 11808 */ 11809 private static boolean installForwardLocked(int installFlags) { 11810 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11811 } 11812 11813 private InstallArgs createInstallArgs(InstallParams params) { 11814 if (params.move != null) { 11815 return new MoveInstallArgs(params); 11816 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 11817 return new AsecInstallArgs(params); 11818 } else { 11819 return new FileInstallArgs(params); 11820 } 11821 } 11822 11823 /** 11824 * Create args that describe an existing installed package. Typically used 11825 * when cleaning up old installs, or used as a move source. 11826 */ 11827 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 11828 String resourcePath, String[] instructionSets) { 11829 final boolean isInAsec; 11830 if (installOnExternalAsec(installFlags)) { 11831 /* Apps on SD card are always in ASEC containers. */ 11832 isInAsec = true; 11833 } else if (installForwardLocked(installFlags) 11834 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 11835 /* 11836 * Forward-locked apps are only in ASEC containers if they're the 11837 * new style 11838 */ 11839 isInAsec = true; 11840 } else { 11841 isInAsec = false; 11842 } 11843 11844 if (isInAsec) { 11845 return new AsecInstallArgs(codePath, instructionSets, 11846 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 11847 } else { 11848 return new FileInstallArgs(codePath, resourcePath, instructionSets); 11849 } 11850 } 11851 11852 static abstract class InstallArgs { 11853 /** @see InstallParams#origin */ 11854 final OriginInfo origin; 11855 /** @see InstallParams#move */ 11856 final MoveInfo move; 11857 11858 final IPackageInstallObserver2 observer; 11859 // Always refers to PackageManager flags only 11860 final int installFlags; 11861 final String installerPackageName; 11862 final String volumeUuid; 11863 final UserHandle user; 11864 final String abiOverride; 11865 final String[] installGrantPermissions; 11866 /** If non-null, drop an async trace when the install completes */ 11867 final String traceMethod; 11868 final int traceCookie; 11869 11870 // The list of instruction sets supported by this app. This is currently 11871 // only used during the rmdex() phase to clean up resources. We can get rid of this 11872 // if we move dex files under the common app path. 11873 /* nullable */ String[] instructionSets; 11874 11875 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11876 int installFlags, String installerPackageName, String volumeUuid, 11877 UserHandle user, String[] instructionSets, 11878 String abiOverride, String[] installGrantPermissions, 11879 String traceMethod, int traceCookie) { 11880 this.origin = origin; 11881 this.move = move; 11882 this.installFlags = installFlags; 11883 this.observer = observer; 11884 this.installerPackageName = installerPackageName; 11885 this.volumeUuid = volumeUuid; 11886 this.user = user; 11887 this.instructionSets = instructionSets; 11888 this.abiOverride = abiOverride; 11889 this.installGrantPermissions = installGrantPermissions; 11890 this.traceMethod = traceMethod; 11891 this.traceCookie = traceCookie; 11892 } 11893 11894 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 11895 abstract int doPreInstall(int status); 11896 11897 /** 11898 * Rename package into final resting place. All paths on the given 11899 * scanned package should be updated to reflect the rename. 11900 */ 11901 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 11902 abstract int doPostInstall(int status, int uid); 11903 11904 /** @see PackageSettingBase#codePathString */ 11905 abstract String getCodePath(); 11906 /** @see PackageSettingBase#resourcePathString */ 11907 abstract String getResourcePath(); 11908 11909 // Need installer lock especially for dex file removal. 11910 abstract void cleanUpResourcesLI(); 11911 abstract boolean doPostDeleteLI(boolean delete); 11912 11913 /** 11914 * Called before the source arguments are copied. This is used mostly 11915 * for MoveParams when it needs to read the source file to put it in the 11916 * destination. 11917 */ 11918 int doPreCopy() { 11919 return PackageManager.INSTALL_SUCCEEDED; 11920 } 11921 11922 /** 11923 * Called after the source arguments are copied. This is used mostly for 11924 * MoveParams when it needs to read the source file to put it in the 11925 * destination. 11926 * 11927 * @return 11928 */ 11929 int doPostCopy(int uid) { 11930 return PackageManager.INSTALL_SUCCEEDED; 11931 } 11932 11933 protected boolean isFwdLocked() { 11934 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 11935 } 11936 11937 protected boolean isExternalAsec() { 11938 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11939 } 11940 11941 protected boolean isEphemeral() { 11942 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11943 } 11944 11945 UserHandle getUser() { 11946 return user; 11947 } 11948 } 11949 11950 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 11951 if (!allCodePaths.isEmpty()) { 11952 if (instructionSets == null) { 11953 throw new IllegalStateException("instructionSet == null"); 11954 } 11955 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 11956 for (String codePath : allCodePaths) { 11957 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 11958 try { 11959 mInstaller.rmdex(codePath, dexCodeInstructionSet); 11960 } catch (InstallerException ignored) { 11961 } 11962 } 11963 } 11964 } 11965 } 11966 11967 /** 11968 * Logic to handle installation of non-ASEC applications, including copying 11969 * and renaming logic. 11970 */ 11971 class FileInstallArgs extends InstallArgs { 11972 private File codeFile; 11973 private File resourceFile; 11974 11975 // Example topology: 11976 // /data/app/com.example/base.apk 11977 // /data/app/com.example/split_foo.apk 11978 // /data/app/com.example/lib/arm/libfoo.so 11979 // /data/app/com.example/lib/arm64/libfoo.so 11980 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 11981 11982 /** New install */ 11983 FileInstallArgs(InstallParams params) { 11984 super(params.origin, params.move, params.observer, params.installFlags, 11985 params.installerPackageName, params.volumeUuid, 11986 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 11987 params.grantedRuntimePermissions, 11988 params.traceMethod, params.traceCookie); 11989 if (isFwdLocked()) { 11990 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 11991 } 11992 } 11993 11994 /** Existing install */ 11995 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 11996 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 11997 null, null, null, 0); 11998 this.codeFile = (codePath != null) ? new File(codePath) : null; 11999 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12000 } 12001 12002 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12003 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12004 try { 12005 return doCopyApk(imcs, temp); 12006 } finally { 12007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12008 } 12009 } 12010 12011 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12012 if (origin.staged) { 12013 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12014 codeFile = origin.file; 12015 resourceFile = origin.file; 12016 return PackageManager.INSTALL_SUCCEEDED; 12017 } 12018 12019 try { 12020 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12021 final File tempDir = 12022 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12023 codeFile = tempDir; 12024 resourceFile = tempDir; 12025 } catch (IOException e) { 12026 Slog.w(TAG, "Failed to create copy file: " + e); 12027 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12028 } 12029 12030 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12031 @Override 12032 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12033 if (!FileUtils.isValidExtFilename(name)) { 12034 throw new IllegalArgumentException("Invalid filename: " + name); 12035 } 12036 try { 12037 final File file = new File(codeFile, name); 12038 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12039 O_RDWR | O_CREAT, 0644); 12040 Os.chmod(file.getAbsolutePath(), 0644); 12041 return new ParcelFileDescriptor(fd); 12042 } catch (ErrnoException e) { 12043 throw new RemoteException("Failed to open: " + e.getMessage()); 12044 } 12045 } 12046 }; 12047 12048 int ret = PackageManager.INSTALL_SUCCEEDED; 12049 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12050 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12051 Slog.e(TAG, "Failed to copy package"); 12052 return ret; 12053 } 12054 12055 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12056 NativeLibraryHelper.Handle handle = null; 12057 try { 12058 handle = NativeLibraryHelper.Handle.create(codeFile); 12059 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12060 abiOverride); 12061 } catch (IOException e) { 12062 Slog.e(TAG, "Copying native libraries failed", e); 12063 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12064 } finally { 12065 IoUtils.closeQuietly(handle); 12066 } 12067 12068 return ret; 12069 } 12070 12071 int doPreInstall(int status) { 12072 if (status != PackageManager.INSTALL_SUCCEEDED) { 12073 cleanUp(); 12074 } 12075 return status; 12076 } 12077 12078 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12079 if (status != PackageManager.INSTALL_SUCCEEDED) { 12080 cleanUp(); 12081 return false; 12082 } 12083 12084 final File targetDir = codeFile.getParentFile(); 12085 final File beforeCodeFile = codeFile; 12086 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12087 12088 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12089 try { 12090 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12091 } catch (ErrnoException e) { 12092 Slog.w(TAG, "Failed to rename", e); 12093 return false; 12094 } 12095 12096 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12097 Slog.w(TAG, "Failed to restorecon"); 12098 return false; 12099 } 12100 12101 // Reflect the rename internally 12102 codeFile = afterCodeFile; 12103 resourceFile = afterCodeFile; 12104 12105 // Reflect the rename in scanned details 12106 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12107 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12108 afterCodeFile, pkg.baseCodePath)); 12109 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12110 afterCodeFile, pkg.splitCodePaths)); 12111 12112 // Reflect the rename in app info 12113 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12114 pkg.setApplicationInfoCodePath(pkg.codePath); 12115 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12116 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12117 pkg.setApplicationInfoResourcePath(pkg.codePath); 12118 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12119 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12120 12121 return true; 12122 } 12123 12124 int doPostInstall(int status, int uid) { 12125 if (status != PackageManager.INSTALL_SUCCEEDED) { 12126 cleanUp(); 12127 } 12128 return status; 12129 } 12130 12131 @Override 12132 String getCodePath() { 12133 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12134 } 12135 12136 @Override 12137 String getResourcePath() { 12138 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12139 } 12140 12141 private boolean cleanUp() { 12142 if (codeFile == null || !codeFile.exists()) { 12143 return false; 12144 } 12145 12146 removeCodePathLI(codeFile); 12147 12148 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12149 resourceFile.delete(); 12150 } 12151 12152 return true; 12153 } 12154 12155 void cleanUpResourcesLI() { 12156 // Try enumerating all code paths before deleting 12157 List<String> allCodePaths = Collections.EMPTY_LIST; 12158 if (codeFile != null && codeFile.exists()) { 12159 try { 12160 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12161 allCodePaths = pkg.getAllCodePaths(); 12162 } catch (PackageParserException e) { 12163 // Ignored; we tried our best 12164 } 12165 } 12166 12167 cleanUp(); 12168 removeDexFiles(allCodePaths, instructionSets); 12169 } 12170 12171 boolean doPostDeleteLI(boolean delete) { 12172 // XXX err, shouldn't we respect the delete flag? 12173 cleanUpResourcesLI(); 12174 return true; 12175 } 12176 } 12177 12178 private boolean isAsecExternal(String cid) { 12179 final String asecPath = PackageHelper.getSdFilesystem(cid); 12180 return !asecPath.startsWith(mAsecInternalPath); 12181 } 12182 12183 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12184 PackageManagerException { 12185 if (copyRet < 0) { 12186 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12187 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12188 throw new PackageManagerException(copyRet, message); 12189 } 12190 } 12191 } 12192 12193 /** 12194 * Extract the MountService "container ID" from the full code path of an 12195 * .apk. 12196 */ 12197 static String cidFromCodePath(String fullCodePath) { 12198 int eidx = fullCodePath.lastIndexOf("/"); 12199 String subStr1 = fullCodePath.substring(0, eidx); 12200 int sidx = subStr1.lastIndexOf("/"); 12201 return subStr1.substring(sidx+1, eidx); 12202 } 12203 12204 /** 12205 * Logic to handle installation of ASEC applications, including copying and 12206 * renaming logic. 12207 */ 12208 class AsecInstallArgs extends InstallArgs { 12209 static final String RES_FILE_NAME = "pkg.apk"; 12210 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12211 12212 String cid; 12213 String packagePath; 12214 String resourcePath; 12215 12216 /** New install */ 12217 AsecInstallArgs(InstallParams params) { 12218 super(params.origin, params.move, params.observer, params.installFlags, 12219 params.installerPackageName, params.volumeUuid, 12220 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12221 params.grantedRuntimePermissions, 12222 params.traceMethod, params.traceCookie); 12223 } 12224 12225 /** Existing install */ 12226 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12227 boolean isExternal, boolean isForwardLocked) { 12228 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12229 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12230 instructionSets, null, null, null, 0); 12231 // Hackily pretend we're still looking at a full code path 12232 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12233 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12234 } 12235 12236 // Extract cid from fullCodePath 12237 int eidx = fullCodePath.lastIndexOf("/"); 12238 String subStr1 = fullCodePath.substring(0, eidx); 12239 int sidx = subStr1.lastIndexOf("/"); 12240 cid = subStr1.substring(sidx+1, eidx); 12241 setMountPath(subStr1); 12242 } 12243 12244 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12245 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12246 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12247 instructionSets, null, null, null, 0); 12248 this.cid = cid; 12249 setMountPath(PackageHelper.getSdDir(cid)); 12250 } 12251 12252 void createCopyFile() { 12253 cid = mInstallerService.allocateExternalStageCidLegacy(); 12254 } 12255 12256 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12257 if (origin.staged && origin.cid != null) { 12258 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12259 cid = origin.cid; 12260 setMountPath(PackageHelper.getSdDir(cid)); 12261 return PackageManager.INSTALL_SUCCEEDED; 12262 } 12263 12264 if (temp) { 12265 createCopyFile(); 12266 } else { 12267 /* 12268 * Pre-emptively destroy the container since it's destroyed if 12269 * copying fails due to it existing anyway. 12270 */ 12271 PackageHelper.destroySdDir(cid); 12272 } 12273 12274 final String newMountPath = imcs.copyPackageToContainer( 12275 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12276 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12277 12278 if (newMountPath != null) { 12279 setMountPath(newMountPath); 12280 return PackageManager.INSTALL_SUCCEEDED; 12281 } else { 12282 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12283 } 12284 } 12285 12286 @Override 12287 String getCodePath() { 12288 return packagePath; 12289 } 12290 12291 @Override 12292 String getResourcePath() { 12293 return resourcePath; 12294 } 12295 12296 int doPreInstall(int status) { 12297 if (status != PackageManager.INSTALL_SUCCEEDED) { 12298 // Destroy container 12299 PackageHelper.destroySdDir(cid); 12300 } else { 12301 boolean mounted = PackageHelper.isContainerMounted(cid); 12302 if (!mounted) { 12303 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12304 Process.SYSTEM_UID); 12305 if (newMountPath != null) { 12306 setMountPath(newMountPath); 12307 } else { 12308 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12309 } 12310 } 12311 } 12312 return status; 12313 } 12314 12315 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12316 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12317 String newMountPath = null; 12318 if (PackageHelper.isContainerMounted(cid)) { 12319 // Unmount the container 12320 if (!PackageHelper.unMountSdDir(cid)) { 12321 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12322 return false; 12323 } 12324 } 12325 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12326 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12327 " which might be stale. Will try to clean up."); 12328 // Clean up the stale container and proceed to recreate. 12329 if (!PackageHelper.destroySdDir(newCacheId)) { 12330 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12331 return false; 12332 } 12333 // Successfully cleaned up stale container. Try to rename again. 12334 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12335 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12336 + " inspite of cleaning it up."); 12337 return false; 12338 } 12339 } 12340 if (!PackageHelper.isContainerMounted(newCacheId)) { 12341 Slog.w(TAG, "Mounting container " + newCacheId); 12342 newMountPath = PackageHelper.mountSdDir(newCacheId, 12343 getEncryptKey(), Process.SYSTEM_UID); 12344 } else { 12345 newMountPath = PackageHelper.getSdDir(newCacheId); 12346 } 12347 if (newMountPath == null) { 12348 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12349 return false; 12350 } 12351 Log.i(TAG, "Succesfully renamed " + cid + 12352 " to " + newCacheId + 12353 " at new path: " + newMountPath); 12354 cid = newCacheId; 12355 12356 final File beforeCodeFile = new File(packagePath); 12357 setMountPath(newMountPath); 12358 final File afterCodeFile = new File(packagePath); 12359 12360 // Reflect the rename in scanned details 12361 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12362 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12363 afterCodeFile, pkg.baseCodePath)); 12364 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12365 afterCodeFile, pkg.splitCodePaths)); 12366 12367 // Reflect the rename in app info 12368 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12369 pkg.setApplicationInfoCodePath(pkg.codePath); 12370 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12371 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12372 pkg.setApplicationInfoResourcePath(pkg.codePath); 12373 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12374 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12375 12376 return true; 12377 } 12378 12379 private void setMountPath(String mountPath) { 12380 final File mountFile = new File(mountPath); 12381 12382 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12383 if (monolithicFile.exists()) { 12384 packagePath = monolithicFile.getAbsolutePath(); 12385 if (isFwdLocked()) { 12386 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12387 } else { 12388 resourcePath = packagePath; 12389 } 12390 } else { 12391 packagePath = mountFile.getAbsolutePath(); 12392 resourcePath = packagePath; 12393 } 12394 } 12395 12396 int doPostInstall(int status, int uid) { 12397 if (status != PackageManager.INSTALL_SUCCEEDED) { 12398 cleanUp(); 12399 } else { 12400 final int groupOwner; 12401 final String protectedFile; 12402 if (isFwdLocked()) { 12403 groupOwner = UserHandle.getSharedAppGid(uid); 12404 protectedFile = RES_FILE_NAME; 12405 } else { 12406 groupOwner = -1; 12407 protectedFile = null; 12408 } 12409 12410 if (uid < Process.FIRST_APPLICATION_UID 12411 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12412 Slog.e(TAG, "Failed to finalize " + cid); 12413 PackageHelper.destroySdDir(cid); 12414 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12415 } 12416 12417 boolean mounted = PackageHelper.isContainerMounted(cid); 12418 if (!mounted) { 12419 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12420 } 12421 } 12422 return status; 12423 } 12424 12425 private void cleanUp() { 12426 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12427 12428 // Destroy secure container 12429 PackageHelper.destroySdDir(cid); 12430 } 12431 12432 private List<String> getAllCodePaths() { 12433 final File codeFile = new File(getCodePath()); 12434 if (codeFile != null && codeFile.exists()) { 12435 try { 12436 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12437 return pkg.getAllCodePaths(); 12438 } catch (PackageParserException e) { 12439 // Ignored; we tried our best 12440 } 12441 } 12442 return Collections.EMPTY_LIST; 12443 } 12444 12445 void cleanUpResourcesLI() { 12446 // Enumerate all code paths before deleting 12447 cleanUpResourcesLI(getAllCodePaths()); 12448 } 12449 12450 private void cleanUpResourcesLI(List<String> allCodePaths) { 12451 cleanUp(); 12452 removeDexFiles(allCodePaths, instructionSets); 12453 } 12454 12455 String getPackageName() { 12456 return getAsecPackageName(cid); 12457 } 12458 12459 boolean doPostDeleteLI(boolean delete) { 12460 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12461 final List<String> allCodePaths = getAllCodePaths(); 12462 boolean mounted = PackageHelper.isContainerMounted(cid); 12463 if (mounted) { 12464 // Unmount first 12465 if (PackageHelper.unMountSdDir(cid)) { 12466 mounted = false; 12467 } 12468 } 12469 if (!mounted && delete) { 12470 cleanUpResourcesLI(allCodePaths); 12471 } 12472 return !mounted; 12473 } 12474 12475 @Override 12476 int doPreCopy() { 12477 if (isFwdLocked()) { 12478 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12479 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12480 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12481 } 12482 } 12483 12484 return PackageManager.INSTALL_SUCCEEDED; 12485 } 12486 12487 @Override 12488 int doPostCopy(int uid) { 12489 if (isFwdLocked()) { 12490 if (uid < Process.FIRST_APPLICATION_UID 12491 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12492 RES_FILE_NAME)) { 12493 Slog.e(TAG, "Failed to finalize " + cid); 12494 PackageHelper.destroySdDir(cid); 12495 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12496 } 12497 } 12498 12499 return PackageManager.INSTALL_SUCCEEDED; 12500 } 12501 } 12502 12503 /** 12504 * Logic to handle movement of existing installed applications. 12505 */ 12506 class MoveInstallArgs extends InstallArgs { 12507 private File codeFile; 12508 private File resourceFile; 12509 12510 /** New install */ 12511 MoveInstallArgs(InstallParams params) { 12512 super(params.origin, params.move, params.observer, params.installFlags, 12513 params.installerPackageName, params.volumeUuid, 12514 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12515 params.grantedRuntimePermissions, 12516 params.traceMethod, params.traceCookie); 12517 } 12518 12519 int copyApk(IMediaContainerService imcs, boolean temp) { 12520 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12521 + move.fromUuid + " to " + move.toUuid); 12522 synchronized (mInstaller) { 12523 try { 12524 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12525 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12526 } catch (InstallerException e) { 12527 Slog.w(TAG, "Failed to move app", e); 12528 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12529 } 12530 } 12531 12532 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12533 resourceFile = codeFile; 12534 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12535 12536 return PackageManager.INSTALL_SUCCEEDED; 12537 } 12538 12539 int doPreInstall(int status) { 12540 if (status != PackageManager.INSTALL_SUCCEEDED) { 12541 cleanUp(move.toUuid); 12542 } 12543 return status; 12544 } 12545 12546 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12547 if (status != PackageManager.INSTALL_SUCCEEDED) { 12548 cleanUp(move.toUuid); 12549 return false; 12550 } 12551 12552 // Reflect the move in app info 12553 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12554 pkg.setApplicationInfoCodePath(pkg.codePath); 12555 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12556 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12557 pkg.setApplicationInfoResourcePath(pkg.codePath); 12558 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12559 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12560 12561 return true; 12562 } 12563 12564 int doPostInstall(int status, int uid) { 12565 if (status == PackageManager.INSTALL_SUCCEEDED) { 12566 cleanUp(move.fromUuid); 12567 } else { 12568 cleanUp(move.toUuid); 12569 } 12570 return status; 12571 } 12572 12573 @Override 12574 String getCodePath() { 12575 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12576 } 12577 12578 @Override 12579 String getResourcePath() { 12580 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12581 } 12582 12583 private boolean cleanUp(String volumeUuid) { 12584 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12585 move.dataAppName); 12586 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12587 synchronized (mInstallLock) { 12588 // Clean up both app data and code 12589 removeDataDirsLI(volumeUuid, move.packageName); 12590 removeCodePathLI(codeFile); 12591 } 12592 return true; 12593 } 12594 12595 void cleanUpResourcesLI() { 12596 throw new UnsupportedOperationException(); 12597 } 12598 12599 boolean doPostDeleteLI(boolean delete) { 12600 throw new UnsupportedOperationException(); 12601 } 12602 } 12603 12604 static String getAsecPackageName(String packageCid) { 12605 int idx = packageCid.lastIndexOf("-"); 12606 if (idx == -1) { 12607 return packageCid; 12608 } 12609 return packageCid.substring(0, idx); 12610 } 12611 12612 // Utility method used to create code paths based on package name and available index. 12613 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12614 String idxStr = ""; 12615 int idx = 1; 12616 // Fall back to default value of idx=1 if prefix is not 12617 // part of oldCodePath 12618 if (oldCodePath != null) { 12619 String subStr = oldCodePath; 12620 // Drop the suffix right away 12621 if (suffix != null && subStr.endsWith(suffix)) { 12622 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12623 } 12624 // If oldCodePath already contains prefix find out the 12625 // ending index to either increment or decrement. 12626 int sidx = subStr.lastIndexOf(prefix); 12627 if (sidx != -1) { 12628 subStr = subStr.substring(sidx + prefix.length()); 12629 if (subStr != null) { 12630 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12631 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12632 } 12633 try { 12634 idx = Integer.parseInt(subStr); 12635 if (idx <= 1) { 12636 idx++; 12637 } else { 12638 idx--; 12639 } 12640 } catch(NumberFormatException e) { 12641 } 12642 } 12643 } 12644 } 12645 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12646 return prefix + idxStr; 12647 } 12648 12649 private File getNextCodePath(File targetDir, String packageName) { 12650 int suffix = 1; 12651 File result; 12652 do { 12653 result = new File(targetDir, packageName + "-" + suffix); 12654 suffix++; 12655 } while (result.exists()); 12656 return result; 12657 } 12658 12659 // Utility method that returns the relative package path with respect 12660 // to the installation directory. Like say for /data/data/com.test-1.apk 12661 // string com.test-1 is returned. 12662 static String deriveCodePathName(String codePath) { 12663 if (codePath == null) { 12664 return null; 12665 } 12666 final File codeFile = new File(codePath); 12667 final String name = codeFile.getName(); 12668 if (codeFile.isDirectory()) { 12669 return name; 12670 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12671 final int lastDot = name.lastIndexOf('.'); 12672 return name.substring(0, lastDot); 12673 } else { 12674 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12675 return null; 12676 } 12677 } 12678 12679 static class PackageInstalledInfo { 12680 String name; 12681 int uid; 12682 // The set of users that originally had this package installed. 12683 int[] origUsers; 12684 // The set of users that now have this package installed. 12685 int[] newUsers; 12686 PackageParser.Package pkg; 12687 int returnCode; 12688 String returnMsg; 12689 PackageRemovedInfo removedInfo; 12690 12691 public void setError(int code, String msg) { 12692 returnCode = code; 12693 returnMsg = msg; 12694 Slog.w(TAG, msg); 12695 } 12696 12697 public void setError(String msg, PackageParserException e) { 12698 returnCode = e.error; 12699 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12700 Slog.w(TAG, msg, e); 12701 } 12702 12703 public void setError(String msg, PackageManagerException e) { 12704 returnCode = e.error; 12705 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 12706 Slog.w(TAG, msg, e); 12707 } 12708 12709 // In some error cases we want to convey more info back to the observer 12710 String origPackage; 12711 String origPermission; 12712 } 12713 12714 /* 12715 * Install a non-existing package. 12716 */ 12717 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12718 UserHandle user, String installerPackageName, String volumeUuid, 12719 PackageInstalledInfo res) { 12720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12721 12722 // Remember this for later, in case we need to rollback this install 12723 String pkgName = pkg.packageName; 12724 12725 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12726 // TODO: b/23350563 12727 final boolean dataDirExists = Environment 12728 .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists(); 12729 12730 synchronized(mPackages) { 12731 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12732 // A package with the same name is already installed, though 12733 // it has been renamed to an older name. The package we 12734 // are trying to install should be installed as an update to 12735 // the existing one, but that has not been requested, so bail. 12736 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12737 + " without first uninstalling package running as " 12738 + mSettings.mRenamedPackages.get(pkgName)); 12739 return; 12740 } 12741 if (mPackages.containsKey(pkgName)) { 12742 // Don't allow installation over an existing package with the same name. 12743 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12744 + " without first uninstalling."); 12745 return; 12746 } 12747 } 12748 12749 try { 12750 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12751 System.currentTimeMillis(), user); 12752 12753 updateSettingsLI(newPackage, installerPackageName, null, null, res, user); 12754 prepareAppDataAfterInstall(newPackage); 12755 12756 // delete the partially installed application. the data directory will have to be 12757 // restored if it was already existing 12758 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12759 // remove package from internal structures. Note that we want deletePackageX to 12760 // delete the package data and cache directories that it created in 12761 // scanPackageLocked, unless those directories existed before we even tried to 12762 // install. 12763 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 12764 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 12765 res.removedInfo, true, null); 12766 } 12767 12768 } catch (PackageManagerException e) { 12769 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12770 } 12771 12772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12773 } 12774 12775 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 12776 // Can't rotate keys during boot or if sharedUser. 12777 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 12778 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 12779 return false; 12780 } 12781 // app is using upgradeKeySets; make sure all are valid 12782 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12783 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 12784 for (int i = 0; i < upgradeKeySets.length; i++) { 12785 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 12786 Slog.wtf(TAG, "Package " 12787 + (oldPs.name != null ? oldPs.name : "<null>") 12788 + " contains upgrade-key-set reference to unknown key-set: " 12789 + upgradeKeySets[i] 12790 + " reverting to signatures check."); 12791 return false; 12792 } 12793 } 12794 return true; 12795 } 12796 12797 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 12798 // Upgrade keysets are being used. Determine if new package has a superset of the 12799 // required keys. 12800 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 12801 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12802 for (int i = 0; i < upgradeKeySets.length; i++) { 12803 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 12804 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 12805 return true; 12806 } 12807 } 12808 return false; 12809 } 12810 12811 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12812 UserHandle user, String installerPackageName, String volumeUuid, 12813 PackageInstalledInfo res) { 12814 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 12815 12816 final PackageParser.Package oldPackage; 12817 final String pkgName = pkg.packageName; 12818 final int[] allUsers; 12819 final boolean[] perUserInstalled; 12820 12821 // First find the old package info and check signatures 12822 synchronized(mPackages) { 12823 oldPackage = mPackages.get(pkgName); 12824 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 12825 if (isEphemeral && !oldIsEphemeral) { 12826 // can't downgrade from full to ephemeral 12827 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 12828 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 12829 return; 12830 } 12831 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 12832 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12833 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 12834 if (!checkUpgradeKeySetLP(ps, pkg)) { 12835 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12836 "New package not signed by keys specified by upgrade-keysets: " 12837 + pkgName); 12838 return; 12839 } 12840 } else { 12841 // default to original signature matching 12842 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 12843 != PackageManager.SIGNATURE_MATCH) { 12844 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 12845 "New package has a different signature: " + pkgName); 12846 return; 12847 } 12848 } 12849 12850 // In case of rollback, remember per-user/profile install state 12851 allUsers = sUserManager.getUserIds(); 12852 perUserInstalled = new boolean[allUsers.length]; 12853 for (int i = 0; i < allUsers.length; i++) { 12854 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12855 } 12856 } 12857 12858 boolean sysPkg = (isSystemApp(oldPackage)); 12859 if (sysPkg) { 12860 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12861 user, allUsers, perUserInstalled, installerPackageName, res); 12862 } else { 12863 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 12864 user, allUsers, perUserInstalled, installerPackageName, res); 12865 } 12866 } 12867 12868 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 12869 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12870 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12871 PackageInstalledInfo res) { 12872 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 12873 + deletedPackage); 12874 12875 String pkgName = deletedPackage.packageName; 12876 boolean deletedPkg = true; 12877 boolean addedPkg = false; 12878 12879 final long origUpdateTime = (pkg.mExtras != null) 12880 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 12881 12882 // First delete the existing package while retaining the data directory 12883 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 12884 res.removedInfo, true, pkg)) { 12885 // If the existing package wasn't successfully deleted 12886 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 12887 deletedPkg = false; 12888 } else { 12889 // Successfully deleted the old package; proceed with replace. 12890 12891 // If deleted package lived in a container, give users a chance to 12892 // relinquish resources before killing. 12893 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 12894 if (DEBUG_INSTALL) { 12895 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 12896 } 12897 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 12898 final ArrayList<String> pkgList = new ArrayList<String>(1); 12899 pkgList.add(deletedPackage.applicationInfo.packageName); 12900 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 12901 } 12902 12903 deleteCodeCacheDirsLI(pkg); 12904 12905 try { 12906 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 12907 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 12908 updateSettingsLI(newPackage, installerPackageName, allUsers, 12909 perUserInstalled, res, user); 12910 prepareAppDataAfterInstall(newPackage); 12911 addedPkg = true; 12912 } catch (PackageManagerException e) { 12913 res.setError("Package couldn't be installed in " + pkg.codePath, e); 12914 } 12915 } 12916 12917 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12918 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 12919 12920 // Revert all internal state mutations and added folders for the failed install 12921 if (addedPkg) { 12922 deletePackageLI(pkgName, null, true, allUsers, perUserInstalled, 12923 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12924 } 12925 12926 // Restore the old package 12927 if (deletedPkg) { 12928 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 12929 File restoreFile = new File(deletedPackage.codePath); 12930 // Parse old package 12931 boolean oldExternal = isExternal(deletedPackage); 12932 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 12933 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 12934 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 12935 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 12936 try { 12937 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 12938 null); 12939 } catch (PackageManagerException e) { 12940 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 12941 + e.getMessage()); 12942 return; 12943 } 12944 12945 synchronized (mPackages) { 12946 // Ensure the installer package name up to date 12947 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 12948 12949 // Update permissions for restored package 12950 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 12951 12952 mSettings.writeLPr(); 12953 } 12954 12955 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 12956 } 12957 } 12958 } 12959 12960 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 12961 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 12962 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 12963 PackageInstalledInfo res) { 12964 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 12965 + ", old=" + deletedPackage); 12966 12967 final boolean disabledSystem; 12968 12969 // Set the system/privileged flags as needed 12970 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 12971 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 12972 != 0) { 12973 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12974 } 12975 12976 // Kill package processes including services, providers, etc. 12977 killPackage(deletedPackage, "replace sys pkg"); 12978 12979 // Report the result for the parent package only 12980 res.removedInfo.uid = deletedPackage.applicationInfo.uid; 12981 res.removedInfo.removedPackage = deletedPackage.packageName; 12982 12983 // Remove existing system package 12984 removePackageSettingLI(deletedPackage, true); 12985 12986 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 12987 if (!disabledSystem) { 12988 // We didn't need to disable the .apk as a current system package, 12989 // which means we are replacing another update that is already 12990 // installed. We need to make sure to delete the older one's .apk. 12991 res.removedInfo.args = createInstallArgsForExisting(0, 12992 deletedPackage.applicationInfo.getCodePath(), 12993 deletedPackage.applicationInfo.getResourcePath(), 12994 getAppDexInstructionSets(deletedPackage.applicationInfo)); 12995 } else { 12996 res.removedInfo.args = null; 12997 } 12998 12999 // Successfully disabled the old package. Now proceed with re-installation 13000 deleteCodeCacheDirsLI(pkg); 13001 13002 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 13003 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13004 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13005 13006 PackageParser.Package newPackage = null; 13007 try { 13008 // Add the package to the internal data structures 13009 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13010 13011 // Set the update and install times 13012 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13013 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13014 System.currentTimeMillis()); 13015 13016 // Check for shared user id changes 13017 String invalidPackageName = getParentOrChildPackageChangedSharedUser(deletedPackage, newPackage); 13018 if (invalidPackageName != null) { 13019 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13020 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13021 + " to " + invalidPackageName); 13022 } 13023 13024 // Update the package dynamic state if succeeded 13025 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13026 // Now that the install succeeded make sure we remove data 13027 // directories for any child package the update removed. 13028 final int deletedChildCount = (deletedPackage.childPackages != null) 13029 ? deletedPackage.childPackages.size() : 0; 13030 final int newChildCount = (newPackage.childPackages != null) 13031 ? newPackage.childPackages.size() : 0; 13032 for (int i = 0; i < deletedChildCount; i++) { 13033 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13034 boolean childPackageDeleted = true; 13035 for (int j = 0; j < newChildCount; j++) { 13036 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13037 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13038 childPackageDeleted = false; 13039 break; 13040 } 13041 } 13042 if (childPackageDeleted) { 13043 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13044 deletedChildPkg.packageName); 13045 if (ps != null) { 13046 removePackageDataLI(ps, allUsers, perUserInstalled, null, 0, false); 13047 } 13048 } 13049 } 13050 13051 updateSettingsLI(newPackage, installerPackageName, allUsers, 13052 perUserInstalled, res, user); 13053 prepareAppDataAfterInstall(newPackage); 13054 } 13055 } catch (PackageManagerException e) { 13056 res.returnCode = INSTALL_FAILED_INTERNAL_ERROR; 13057 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13058 } 13059 13060 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13061 // Re installation failed. Restore old information 13062 // Remove new pkg information 13063 if (newPackage != null) { 13064 removeInstalledPackageLI(newPackage, true); 13065 } 13066 // Add back the old system package 13067 try { 13068 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13069 } catch (PackageManagerException e) { 13070 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13071 } 13072 13073 synchronized (mPackages) { 13074 if (disabledSystem) { 13075 enableSystemPackageLPw(deletedPackage); 13076 } 13077 13078 // Ensure the installer package name up to date 13079 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13080 13081 // Update permissions for restored package 13082 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13083 13084 mSettings.writeLPr(); 13085 } 13086 13087 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13088 + " after failed upgrade"); 13089 } 13090 } 13091 13092 /** 13093 * Checks whether the parent or any of the child packages have a change shared 13094 * user. For a package to be a valid update the shred users of the parent and 13095 * the children should match. We may later support changing child shared users. 13096 * @param oldPkg The updated package. 13097 * @param newPkg The update package. 13098 * @return The shared user that change between the versions. 13099 */ 13100 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13101 PackageParser.Package newPkg) { 13102 // Check parent shared user 13103 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13104 return newPkg.packageName; 13105 } 13106 // Check child shared users 13107 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13108 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13109 for (int i = 0; i < newChildCount; i++) { 13110 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13111 // If this child was present, did it have the same shared user? 13112 for (int j = 0; j < oldChildCount; j++) { 13113 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13114 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13115 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13116 return newChildPkg.packageName; 13117 } 13118 } 13119 } 13120 return null; 13121 } 13122 13123 private void removeNativeBinariesLI(PackageParser.Package pkg) { 13124 // Remove the lib path for the parent package 13125 PackageSetting ps = (PackageSetting) pkg.mExtras; 13126 if (ps != null) { 13127 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13128 } 13129 // Remove the lib path for the child packages 13130 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13131 for (int i = 0; i < childCount; i++) { 13132 ps = (PackageSetting) pkg.childPackages.get(i).mExtras; 13133 if (ps != null) { 13134 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13135 } 13136 } 13137 } 13138 13139 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13140 // Enable the parent package 13141 mSettings.enableSystemPackageLPw(pkg.packageName); 13142 // Enable the child packages 13143 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13144 for (int i = 0; i < childCount; i++) { 13145 PackageParser.Package childPkg = pkg.childPackages.get(i); 13146 mSettings.enableSystemPackageLPw(childPkg.packageName); 13147 } 13148 } 13149 13150 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13151 PackageParser.Package newPkg) { 13152 // Disable the parent package (parent always replaced) 13153 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13154 // Disable the child packages 13155 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13156 for (int i = 0; i < childCount; i++) { 13157 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13158 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13159 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13160 } 13161 return disabled; 13162 } 13163 13164 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13165 String installerPackageName) { 13166 // Enable the parent package 13167 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13168 // Enable the child packages 13169 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13170 for (int i = 0; i < childCount; i++) { 13171 PackageParser.Package childPkg = pkg.childPackages.get(i); 13172 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13173 } 13174 } 13175 13176 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13177 // Collect all used permissions in the UID 13178 ArraySet<String> usedPermissions = new ArraySet<>(); 13179 final int packageCount = su.packages.size(); 13180 for (int i = 0; i < packageCount; i++) { 13181 PackageSetting ps = su.packages.valueAt(i); 13182 if (ps.pkg == null) { 13183 continue; 13184 } 13185 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13186 for (int j = 0; j < requestedPermCount; j++) { 13187 String permission = ps.pkg.requestedPermissions.get(j); 13188 BasePermission bp = mSettings.mPermissions.get(permission); 13189 if (bp != null) { 13190 usedPermissions.add(permission); 13191 } 13192 } 13193 } 13194 13195 PermissionsState permissionsState = su.getPermissionsState(); 13196 // Prune install permissions 13197 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13198 final int installPermCount = installPermStates.size(); 13199 for (int i = installPermCount - 1; i >= 0; i--) { 13200 PermissionState permissionState = installPermStates.get(i); 13201 if (!usedPermissions.contains(permissionState.getName())) { 13202 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13203 if (bp != null) { 13204 permissionsState.revokeInstallPermission(bp); 13205 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13206 PackageManager.MASK_PERMISSION_FLAGS, 0); 13207 } 13208 } 13209 } 13210 13211 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13212 13213 // Prune runtime permissions 13214 for (int userId : allUserIds) { 13215 List<PermissionState> runtimePermStates = permissionsState 13216 .getRuntimePermissionStates(userId); 13217 final int runtimePermCount = runtimePermStates.size(); 13218 for (int i = runtimePermCount - 1; i >= 0; i--) { 13219 PermissionState permissionState = runtimePermStates.get(i); 13220 if (!usedPermissions.contains(permissionState.getName())) { 13221 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13222 if (bp != null) { 13223 permissionsState.revokeRuntimePermission(bp, userId); 13224 permissionsState.updatePermissionFlags(bp, userId, 13225 PackageManager.MASK_PERMISSION_FLAGS, 0); 13226 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13227 runtimePermissionChangedUserIds, userId); 13228 } 13229 } 13230 } 13231 } 13232 13233 return runtimePermissionChangedUserIds; 13234 } 13235 13236 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13237 int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, UserHandle user) { 13238 // Update the parent package setting 13239 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, perUserInstalled, 13240 res, user); 13241 // Update the child packages setting 13242 final int childCount = (newPackage.childPackages != null) 13243 ? newPackage.childPackages.size() : 0; 13244 for (int i = 0; i < childCount; i++) { 13245 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13246 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, perUserInstalled, 13247 res, user); 13248 } 13249 } 13250 13251 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13252 String installerPackageName, int[] allUsers, boolean[] perUserInstalled, 13253 PackageInstalledInfo res, UserHandle user) { 13254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13255 13256 String pkgName = newPackage.packageName; 13257 synchronized (mPackages) { 13258 //write settings. the installStatus will be incomplete at this stage. 13259 //note that the new package setting would have already been 13260 //added to mPackages. It hasn't been persisted yet. 13261 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13262 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13263 mSettings.writeLPr(); 13264 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13265 } 13266 13267 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13268 synchronized (mPackages) { 13269 updatePermissionsLPw(newPackage.packageName, newPackage, 13270 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13271 ? UPDATE_PERMISSIONS_ALL : 0)); 13272 // For system-bundled packages, we assume that installing an upgraded version 13273 // of the package implies that the user actually wants to run that new code, 13274 // so we enable the package. 13275 PackageSetting ps = mSettings.mPackages.get(pkgName); 13276 if (ps != null) { 13277 if (isSystemApp(newPackage)) { 13278 // NB: implicit assumption that system package upgrades apply to all users 13279 if (DEBUG_INSTALL) { 13280 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13281 } 13282 if (res.origUsers != null) { 13283 for (int userHandle : res.origUsers) { 13284 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13285 userHandle, installerPackageName); 13286 } 13287 } 13288 // Also convey the prior install/uninstall state 13289 if (allUsers != null && perUserInstalled != null) { 13290 for (int i = 0; i < allUsers.length; i++) { 13291 if (DEBUG_INSTALL) { 13292 Slog.d(TAG, " user " + allUsers[i] 13293 + " => " + perUserInstalled[i]); 13294 } 13295 ps.setInstalled(perUserInstalled[i], allUsers[i]); 13296 } 13297 // these install state changes will be persisted in the 13298 // upcoming call to mSettings.writeLPr(). 13299 } 13300 } 13301 // It's implied that when a user requests installation, they want the app to be 13302 // installed and enabled. 13303 int userId = user.getIdentifier(); 13304 if (userId != UserHandle.USER_ALL) { 13305 ps.setInstalled(true, userId); 13306 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13307 } 13308 } 13309 res.name = pkgName; 13310 res.uid = newPackage.applicationInfo.uid; 13311 res.pkg = newPackage; 13312 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13313 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13314 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 13315 //to update install status 13316 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13317 mSettings.writeLPr(); 13318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13319 } 13320 13321 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13322 } 13323 13324 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13325 try { 13326 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13327 installPackageLI(args, res); 13328 } finally { 13329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13330 } 13331 } 13332 13333 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13334 final int installFlags = args.installFlags; 13335 final String installerPackageName = args.installerPackageName; 13336 final String volumeUuid = args.volumeUuid; 13337 final File tmpPackageFile = new File(args.getCodePath()); 13338 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13339 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13340 || (args.volumeUuid != null)); 13341 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13342 boolean replace = false; 13343 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13344 if (args.move != null) { 13345 // moving a complete application; perfom an initial scan on the new install location 13346 scanFlags |= SCAN_INITIAL; 13347 } 13348 // Result object to be returned 13349 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 13350 13351 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13352 13353 // Sanity check 13354 if (ephemeral && (forwardLocked || onExternal)) { 13355 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13356 + " external=" + onExternal); 13357 res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 13358 return; 13359 } 13360 13361 // Retrieve PackageSettings and parse package 13362 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13363 | PackageParser.PARSE_ENFORCE_CODE 13364 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13365 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13366 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13367 PackageParser pp = new PackageParser(); 13368 pp.setSeparateProcesses(mSeparateProcesses); 13369 pp.setDisplayMetrics(mMetrics); 13370 13371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13372 final PackageParser.Package pkg; 13373 try { 13374 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13375 } catch (PackageParserException e) { 13376 res.setError("Failed parse during installPackageLI", e); 13377 return; 13378 } finally { 13379 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13380 } 13381 13382 // If package doesn't declare API override, mark that we have an install 13383 // time CPU ABI override. 13384 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13385 pkg.cpuAbiOverride = args.abiOverride; 13386 } 13387 13388 String pkgName = res.name = pkg.packageName; 13389 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13390 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13391 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13392 return; 13393 } 13394 } 13395 13396 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13397 try { 13398 PackageParser.collectCertificates(pkg, parseFlags); 13399 } catch (PackageParserException e) { 13400 res.setError("Failed collect during installPackageLI", e); 13401 return; 13402 } finally { 13403 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13404 } 13405 13406 // Get rid of all references to package scan path via parser. 13407 pp = null; 13408 String oldCodePath = null; 13409 boolean systemApp = false; 13410 synchronized (mPackages) { 13411 // Check if installing already existing package 13412 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13413 String oldName = mSettings.mRenamedPackages.get(pkgName); 13414 if (pkg.mOriginalPackages != null 13415 && pkg.mOriginalPackages.contains(oldName) 13416 && mPackages.containsKey(oldName)) { 13417 // This package is derived from an original package, 13418 // and this device has been updating from that original 13419 // name. We must continue using the original name, so 13420 // rename the new package here. 13421 pkg.setPackageName(oldName); 13422 pkgName = pkg.packageName; 13423 replace = true; 13424 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13425 + oldName + " pkgName=" + pkgName); 13426 } else if (mPackages.containsKey(pkgName)) { 13427 // This package, under its official name, already exists 13428 // on the device; we should replace it. 13429 replace = true; 13430 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13431 } 13432 13433 // Child packages are installed through the parent package 13434 if (pkg.parentPackage != null) { 13435 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13436 "Package " + pkg.packageName + " is child of package " 13437 + pkg.parentPackage.parentPackage + ". Child packages " 13438 + "can be updated only through the parent package."); 13439 return; 13440 } 13441 13442 if (replace) { 13443 // Prevent apps opting out from runtime permissions 13444 PackageParser.Package oldPackage = mPackages.get(pkgName); 13445 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13446 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13447 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13448 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13449 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13450 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13451 + " doesn't support runtime permissions but the old" 13452 + " target SDK " + oldTargetSdk + " does."); 13453 return; 13454 } 13455 13456 // Prevent installing of child packages 13457 if (oldPackage.parentPackage != null) { 13458 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13459 "Package " + pkg.packageName + " is child of package " 13460 + oldPackage.parentPackage + ". Child packages " 13461 + "can be updated only through the parent package."); 13462 return; 13463 } 13464 } 13465 } 13466 13467 PackageSetting ps = mSettings.mPackages.get(pkgName); 13468 if (ps != null) { 13469 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13470 13471 // Quick sanity check that we're signed correctly if updating; 13472 // we'll check this again later when scanning, but we want to 13473 // bail early here before tripping over redefined permissions. 13474 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13475 if (!checkUpgradeKeySetLP(ps, pkg)) { 13476 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13477 + pkg.packageName + " upgrade keys do not match the " 13478 + "previously installed version"); 13479 return; 13480 } 13481 } else { 13482 try { 13483 verifySignaturesLP(ps, pkg); 13484 } catch (PackageManagerException e) { 13485 res.setError(e.error, e.getMessage()); 13486 return; 13487 } 13488 } 13489 13490 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13491 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13492 systemApp = (ps.pkg.applicationInfo.flags & 13493 ApplicationInfo.FLAG_SYSTEM) != 0; 13494 } 13495 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13496 } 13497 13498 // Check whether the newly-scanned package wants to define an already-defined perm 13499 int N = pkg.permissions.size(); 13500 for (int i = N-1; i >= 0; i--) { 13501 PackageParser.Permission perm = pkg.permissions.get(i); 13502 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13503 if (bp != null) { 13504 // If the defining package is signed with our cert, it's okay. This 13505 // also includes the "updating the same package" case, of course. 13506 // "updating same package" could also involve key-rotation. 13507 final boolean sigsOk; 13508 if (bp.sourcePackage.equals(pkg.packageName) 13509 && (bp.packageSetting instanceof PackageSetting) 13510 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13511 scanFlags))) { 13512 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13513 } else { 13514 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13515 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13516 } 13517 if (!sigsOk) { 13518 // If the owning package is the system itself, we log but allow 13519 // install to proceed; we fail the install on all other permission 13520 // redefinitions. 13521 if (!bp.sourcePackage.equals("android")) { 13522 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13523 + pkg.packageName + " attempting to redeclare permission " 13524 + perm.info.name + " already owned by " + bp.sourcePackage); 13525 res.origPermission = perm.info.name; 13526 res.origPackage = bp.sourcePackage; 13527 return; 13528 } else { 13529 Slog.w(TAG, "Package " + pkg.packageName 13530 + " attempting to redeclare system permission " 13531 + perm.info.name + "; ignoring new declaration"); 13532 pkg.permissions.remove(i); 13533 } 13534 } 13535 } 13536 } 13537 } 13538 13539 if (systemApp) { 13540 if (onExternal) { 13541 // Abort update; system app can't be replaced with app on sdcard 13542 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13543 "Cannot install updates to system apps on sdcard"); 13544 return; 13545 } else if (ephemeral) { 13546 // Abort update; system app can't be replaced with an ephemeral app 13547 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13548 "Cannot update a system app with an ephemeral app"); 13549 return; 13550 } 13551 } 13552 13553 if (args.move != null) { 13554 // We did an in-place move, so dex is ready to roll 13555 scanFlags |= SCAN_NO_DEX; 13556 scanFlags |= SCAN_MOVE; 13557 13558 synchronized (mPackages) { 13559 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13560 if (ps == null) { 13561 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13562 "Missing settings for moved package " + pkgName); 13563 } 13564 13565 // We moved the entire application as-is, so bring over the 13566 // previously derived ABI information. 13567 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13568 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13569 } 13570 13571 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13572 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13573 scanFlags |= SCAN_NO_DEX; 13574 13575 try { 13576 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13577 args.abiOverride : pkg.cpuAbiOverride); 13578 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13579 true /* extract libs */); 13580 } catch (PackageManagerException pme) { 13581 Slog.e(TAG, "Error deriving application ABI", pme); 13582 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13583 return; 13584 } 13585 13586 // Extract package to save the VM unzipping the APK in memory during 13587 // launch. Only do this if profile-guided compilation is enabled because 13588 // otherwise BackgroundDexOptService will not dexopt the package later. 13589 if (mUseJitProfiles) { 13590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13591 // Do not run PackageDexOptimizer through the local performDexOpt 13592 // method because `pkg` is not in `mPackages` yet. 13593 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13594 false /* useProfiles */, true /* extractOnly */); 13595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13596 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13597 String msg = "Extracking package failed for " + pkgName; 13598 res.setError(INSTALL_FAILED_DEXOPT, msg); 13599 return; 13600 } 13601 } 13602 } 13603 13604 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13605 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13606 return; 13607 } 13608 13609 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13610 13611 if (replace) { 13612 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13613 installerPackageName, volumeUuid, res); 13614 } else { 13615 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13616 args.user, installerPackageName, volumeUuid, res); 13617 } 13618 synchronized (mPackages) { 13619 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13620 if (ps != null) { 13621 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13622 } 13623 } 13624 } 13625 13626 private void startIntentFilterVerifications(int userId, boolean replacing, 13627 PackageParser.Package pkg) { 13628 if (mIntentFilterVerifierComponent == null) { 13629 Slog.w(TAG, "No IntentFilter verification will not be done as " 13630 + "there is no IntentFilterVerifier available!"); 13631 return; 13632 } 13633 13634 final int verifierUid = getPackageUid( 13635 mIntentFilterVerifierComponent.getPackageName(), 13636 MATCH_DEBUG_TRIAGED_MISSING, 13637 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13638 13639 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 13640 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 13641 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 13642 mHandler.sendMessage(msg); 13643 } 13644 13645 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 13646 PackageParser.Package pkg) { 13647 int size = pkg.activities.size(); 13648 if (size == 0) { 13649 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13650 "No activity, so no need to verify any IntentFilter!"); 13651 return; 13652 } 13653 13654 final boolean hasDomainURLs = hasDomainURLs(pkg); 13655 if (!hasDomainURLs) { 13656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13657 "No domain URLs, so no need to verify any IntentFilter!"); 13658 return; 13659 } 13660 13661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 13662 + " if any IntentFilter from the " + size 13663 + " Activities needs verification ..."); 13664 13665 int count = 0; 13666 final String packageName = pkg.packageName; 13667 13668 synchronized (mPackages) { 13669 // If this is a new install and we see that we've already run verification for this 13670 // package, we have nothing to do: it means the state was restored from backup. 13671 if (!replacing) { 13672 IntentFilterVerificationInfo ivi = 13673 mSettings.getIntentFilterVerificationLPr(packageName); 13674 if (ivi != null) { 13675 if (DEBUG_DOMAIN_VERIFICATION) { 13676 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 13677 + ivi.getStatusString()); 13678 } 13679 return; 13680 } 13681 } 13682 13683 // If any filters need to be verified, then all need to be. 13684 boolean needToVerify = false; 13685 for (PackageParser.Activity a : pkg.activities) { 13686 for (ActivityIntentInfo filter : a.intents) { 13687 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 13688 if (DEBUG_DOMAIN_VERIFICATION) { 13689 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 13690 } 13691 needToVerify = true; 13692 break; 13693 } 13694 } 13695 } 13696 13697 if (needToVerify) { 13698 final int verificationId = mIntentFilterVerificationToken++; 13699 for (PackageParser.Activity a : pkg.activities) { 13700 for (ActivityIntentInfo filter : a.intents) { 13701 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 13702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 13703 "Verification needed for IntentFilter:" + filter.toString()); 13704 mIntentFilterVerifier.addOneIntentFilterVerification( 13705 verifierUid, userId, verificationId, filter, packageName); 13706 count++; 13707 } 13708 } 13709 } 13710 } 13711 } 13712 13713 if (count > 0) { 13714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 13715 + " IntentFilter verification" + (count > 1 ? "s" : "") 13716 + " for userId:" + userId); 13717 mIntentFilterVerifier.startVerifications(userId); 13718 } else { 13719 if (DEBUG_DOMAIN_VERIFICATION) { 13720 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 13721 } 13722 } 13723 } 13724 13725 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 13726 final ComponentName cn = filter.activity.getComponentName(); 13727 final String packageName = cn.getPackageName(); 13728 13729 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 13730 packageName); 13731 if (ivi == null) { 13732 return true; 13733 } 13734 int status = ivi.getStatus(); 13735 switch (status) { 13736 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 13737 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 13738 return true; 13739 13740 default: 13741 // Nothing to do 13742 return false; 13743 } 13744 } 13745 13746 private static boolean isMultiArch(ApplicationInfo info) { 13747 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 13748 } 13749 13750 private static boolean isExternal(PackageParser.Package pkg) { 13751 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13752 } 13753 13754 private static boolean isExternal(PackageSetting ps) { 13755 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 13756 } 13757 13758 private static boolean isEphemeral(PackageParser.Package pkg) { 13759 return pkg.applicationInfo.isEphemeralApp(); 13760 } 13761 13762 private static boolean isEphemeral(PackageSetting ps) { 13763 return ps.pkg != null && isEphemeral(ps.pkg); 13764 } 13765 13766 private static boolean isSystemApp(PackageParser.Package pkg) { 13767 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 13768 } 13769 13770 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 13771 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13772 } 13773 13774 private static boolean hasDomainURLs(PackageParser.Package pkg) { 13775 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 13776 } 13777 13778 private static boolean isSystemApp(PackageSetting ps) { 13779 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 13780 } 13781 13782 private static boolean isUpdatedSystemApp(PackageSetting ps) { 13783 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 13784 } 13785 13786 private int packageFlagsToInstallFlags(PackageSetting ps) { 13787 int installFlags = 0; 13788 if (isEphemeral(ps)) { 13789 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13790 } 13791 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 13792 // This existing package was an external ASEC install when we have 13793 // the external flag without a UUID 13794 installFlags |= PackageManager.INSTALL_EXTERNAL; 13795 } 13796 if (ps.isForwardLocked()) { 13797 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13798 } 13799 return installFlags; 13800 } 13801 13802 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 13803 if (isExternal(pkg)) { 13804 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13805 return StorageManager.UUID_PRIMARY_PHYSICAL; 13806 } else { 13807 return pkg.volumeUuid; 13808 } 13809 } else { 13810 return StorageManager.UUID_PRIVATE_INTERNAL; 13811 } 13812 } 13813 13814 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 13815 if (isExternal(pkg)) { 13816 if (TextUtils.isEmpty(pkg.volumeUuid)) { 13817 return mSettings.getExternalVersion(); 13818 } else { 13819 return mSettings.findOrCreateVersion(pkg.volumeUuid); 13820 } 13821 } else { 13822 return mSettings.getInternalVersion(); 13823 } 13824 } 13825 13826 private void deleteTempPackageFiles() { 13827 final FilenameFilter filter = new FilenameFilter() { 13828 public boolean accept(File dir, String name) { 13829 return name.startsWith("vmdl") && name.endsWith(".tmp"); 13830 } 13831 }; 13832 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 13833 file.delete(); 13834 } 13835 } 13836 13837 @Override 13838 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 13839 int flags) { 13840 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 13841 flags); 13842 } 13843 13844 @Override 13845 public void deletePackage(final String packageName, 13846 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 13847 mContext.enforceCallingOrSelfPermission( 13848 android.Manifest.permission.DELETE_PACKAGES, null); 13849 Preconditions.checkNotNull(packageName); 13850 Preconditions.checkNotNull(observer); 13851 final int uid = Binder.getCallingUid(); 13852 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 13853 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 13854 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 13855 mContext.enforceCallingOrSelfPermission( 13856 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13857 "deletePackage for user " + userId); 13858 } 13859 13860 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 13861 try { 13862 observer.onPackageDeleted(packageName, 13863 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 13864 } catch (RemoteException re) { 13865 } 13866 return; 13867 } 13868 13869 for (int currentUserId : users) { 13870 if (getBlockUninstallForUser(packageName, currentUserId)) { 13871 try { 13872 observer.onPackageDeleted(packageName, 13873 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 13874 } catch (RemoteException re) { 13875 } 13876 return; 13877 } 13878 } 13879 13880 if (DEBUG_REMOVE) { 13881 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 13882 } 13883 // Queue up an async operation since the package deletion may take a little while. 13884 mHandler.post(new Runnable() { 13885 public void run() { 13886 mHandler.removeCallbacks(this); 13887 final int returnCode = deletePackageX(packageName, userId, flags); 13888 try { 13889 observer.onPackageDeleted(packageName, returnCode, null); 13890 } catch (RemoteException e) { 13891 Log.i(TAG, "Observer no longer exists."); 13892 } //end catch 13893 } //end run 13894 }); 13895 } 13896 13897 private boolean isPackageDeviceAdmin(String packageName, int userId) { 13898 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13899 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13900 try { 13901 if (dpm != null) { 13902 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 13903 /* callingUserOnly =*/ false); 13904 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 13905 : deviceOwnerComponentName.getPackageName(); 13906 // Does the package contains the device owner? 13907 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 13908 // this check is probably not needed, since DO should be registered as a device 13909 // admin on some user too. (Original bug for this: b/17657954) 13910 if (packageName.equals(deviceOwnerPackageName)) { 13911 return true; 13912 } 13913 // Does it contain a device admin for any user? 13914 int[] users; 13915 if (userId == UserHandle.USER_ALL) { 13916 users = sUserManager.getUserIds(); 13917 } else { 13918 users = new int[]{userId}; 13919 } 13920 for (int i = 0; i < users.length; ++i) { 13921 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 13922 return true; 13923 } 13924 } 13925 } 13926 } catch (RemoteException e) { 13927 } 13928 return false; 13929 } 13930 13931 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 13932 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 13933 } 13934 13935 /** 13936 * This method is an internal method that could be get invoked either 13937 * to delete an installed package or to clean up a failed installation. 13938 * After deleting an installed package, a broadcast is sent to notify any 13939 * listeners that the package has been installed. For cleaning up a failed 13940 * installation, the broadcast is not necessary since the package's 13941 * installation wouldn't have sent the initial broadcast either 13942 * The key steps in deleting a package are 13943 * deleting the package information in internal structures like mPackages, 13944 * deleting the packages base directories through installd 13945 * updating mSettings to reflect current status 13946 * persisting settings for later use 13947 * sending a broadcast if necessary 13948 */ 13949 private int deletePackageX(String packageName, int userId, int flags) { 13950 final PackageRemovedInfo info = new PackageRemovedInfo(); 13951 final boolean res; 13952 13953 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 13954 ? UserHandle.ALL : new UserHandle(userId); 13955 13956 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 13957 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 13958 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 13959 } 13960 13961 boolean removedForAllUsers = false; 13962 boolean systemUpdate = false; 13963 13964 PackageParser.Package uninstalledPkg; 13965 13966 // for the uninstall-updates case and restricted profiles, remember the per- 13967 // userhandle installed state 13968 int[] allUsers; 13969 boolean[] perUserInstalled; 13970 synchronized (mPackages) { 13971 uninstalledPkg = mPackages.get(packageName); 13972 PackageSetting ps = mSettings.mPackages.get(packageName); 13973 allUsers = sUserManager.getUserIds(); 13974 perUserInstalled = new boolean[allUsers.length]; 13975 for (int i = 0; i < allUsers.length; i++) { 13976 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 13977 } 13978 } 13979 13980 synchronized (mInstallLock) { 13981 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 13982 res = deletePackageLI(packageName, removeForUser, true, allUsers, perUserInstalled, 13983 flags | REMOVE_CHATTY, info, true, null); 13984 systemUpdate = info.isRemovedPackageSystemUpdate; 13985 synchronized (mPackages) { 13986 if (res) { 13987 if (!systemUpdate && mPackages.get(packageName) == null) { 13988 removedForAllUsers = true; 13989 } 13990 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg); 13991 } 13992 } 13993 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 13994 + " removedForAllUsers=" + removedForAllUsers); 13995 } 13996 13997 if (res) { 13998 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 13999 14000 // If the removed package was a system update, the old system package 14001 // was re-enabled; we need to broadcast this information 14002 if (systemUpdate) { 14003 Bundle extras = new Bundle(1); 14004 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 14005 ? info.removedAppId : info.uid); 14006 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14007 14008 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 14009 extras, 0, null, null, null); 14010 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 14011 extras, 0, null, null, null); 14012 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14013 null, 0, packageName, null, null); 14014 } 14015 } 14016 // Force a gc here. 14017 Runtime.getRuntime().gc(); 14018 // Delete the resources here after sending the broadcast to let 14019 // other processes clean up before deleting resources. 14020 if (info.args != null) { 14021 synchronized (mInstallLock) { 14022 info.args.doPostDeleteLI(true); 14023 } 14024 } 14025 14026 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14027 } 14028 14029 class PackageRemovedInfo { 14030 String removedPackage; 14031 int uid = -1; 14032 int removedAppId = -1; 14033 int[] removedUsers = null; 14034 boolean isRemovedPackageSystemUpdate = false; 14035 // Clean up resources deleted packages. 14036 InstallArgs args = null; 14037 14038 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 14039 Bundle extras = new Bundle(1); 14040 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14041 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 14042 if (replacing) { 14043 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14044 } 14045 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14046 if (removedPackage != null) { 14047 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14048 extras, 0, null, null, removedUsers); 14049 if (fullRemove && !replacing) { 14050 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 14051 extras, 0, null, null, removedUsers); 14052 } 14053 } 14054 if (removedAppId >= 0) { 14055 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14056 removedUsers); 14057 } 14058 } 14059 } 14060 14061 /* 14062 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14063 * flag is not set, the data directory is removed as well. 14064 * make sure this flag is set for partially installed apps. If not its meaningless to 14065 * delete a partially installed application. 14066 */ 14067 private void removePackageDataLI(PackageSetting ps, 14068 int[] allUserHandles, boolean[] perUserInstalled, 14069 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14070 String packageName = ps.name; 14071 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14072 removePackageSettingLI(ps, (flags&REMOVE_CHATTY) != 0); 14073 // Retrieve object to delete permissions for shared user later on 14074 final PackageSetting deletedPs; 14075 // reader 14076 synchronized (mPackages) { 14077 deletedPs = mSettings.mPackages.get(packageName); 14078 if (outInfo != null) { 14079 outInfo.removedPackage = packageName; 14080 outInfo.removedUsers = deletedPs != null 14081 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14082 : null; 14083 } 14084 } 14085 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14086 removeDataDirsLI(ps.volumeUuid, packageName); 14087 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14088 } 14089 // writer 14090 synchronized (mPackages) { 14091 if (deletedPs != null) { 14092 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14093 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14094 clearDefaultBrowserIfNeeded(packageName); 14095 if (outInfo != null) { 14096 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14097 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14098 } 14099 updatePermissionsLPw(deletedPs.name, null, 0); 14100 if (deletedPs.sharedUser != null) { 14101 // Remove permissions associated with package. Since runtime 14102 // permissions are per user we have to kill the removed package 14103 // or packages running under the shared user of the removed 14104 // package if revoking the permissions requested only by the removed 14105 // package is successful and this causes a change in gids. 14106 for (int userId : UserManagerService.getInstance().getUserIds()) { 14107 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14108 userId); 14109 if (userIdToKill == UserHandle.USER_ALL 14110 || userIdToKill >= UserHandle.USER_SYSTEM) { 14111 // If gids changed for this user, kill all affected packages. 14112 mHandler.post(new Runnable() { 14113 @Override 14114 public void run() { 14115 // This has to happen with no lock held. 14116 killApplication(deletedPs.name, deletedPs.appId, 14117 KILL_APP_REASON_GIDS_CHANGED); 14118 } 14119 }); 14120 break; 14121 } 14122 } 14123 } 14124 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14125 } 14126 // make sure to preserve per-user disabled state if this removal was just 14127 // a downgrade of a system app to the factory package 14128 if (allUserHandles != null && perUserInstalled != null) { 14129 if (DEBUG_REMOVE) { 14130 Slog.d(TAG, "Propagating install state across downgrade"); 14131 } 14132 for (int i = 0; i < allUserHandles.length; i++) { 14133 if (DEBUG_REMOVE) { 14134 Slog.d(TAG, " user " + allUserHandles[i] 14135 + " => " + perUserInstalled[i]); 14136 } 14137 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 14138 } 14139 } 14140 } 14141 // can downgrade to reader 14142 if (writeSettings) { 14143 // Save settings now 14144 mSettings.writeLPr(); 14145 } 14146 } 14147 if (outInfo != null) { 14148 // A user ID was deleted here. Go through all users and remove it 14149 // from KeyStore. 14150 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14151 } 14152 } 14153 14154 static boolean locationIsPrivileged(File path) { 14155 try { 14156 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14157 .getCanonicalPath(); 14158 return path.getCanonicalPath().startsWith(privilegedAppDir); 14159 } catch (IOException e) { 14160 Slog.e(TAG, "Unable to access code path " + path); 14161 } 14162 return false; 14163 } 14164 14165 /* 14166 * Tries to delete system package. 14167 */ 14168 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14169 PackageSetting deletedPs, int[] allUserHandles, boolean[] perUserInstalled, 14170 int flags, PackageRemovedInfo outInfo, boolean writeSettings, 14171 PackageParser.Package replacingPackage) { 14172 if (deletedPkg.parentPackage != null) { 14173 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14174 return false; 14175 } 14176 14177 final boolean applyUserRestrictions 14178 = (allUserHandles != null) && (perUserInstalled != null); 14179 final PackageSetting disabledPs; 14180 // Confirm if the system package has been updated 14181 // An updated system app can be deleted. This will also have to restore 14182 // the system pkg from system partition 14183 // reader 14184 synchronized (mPackages) { 14185 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPkg.packageName); 14186 } 14187 14188 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14189 + " disabledPs=" + disabledPs); 14190 14191 if (disabledPs == null) { 14192 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14193 return false; 14194 } else if (DEBUG_REMOVE) { 14195 Slog.d(TAG, "Deleting system pkg from data partition"); 14196 } 14197 14198 if (DEBUG_REMOVE) { 14199 if (applyUserRestrictions) { 14200 Slog.d(TAG, "Remembering install states:"); 14201 for (int i = 0; i < allUserHandles.length; i++) { 14202 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 14203 } 14204 } 14205 } 14206 14207 // Delete the updated package 14208 outInfo.isRemovedPackageSystemUpdate = true; 14209 if (disabledPs.versionCode < deletedPs.versionCode) { 14210 // Delete data for downgrades 14211 flags &= ~PackageManager.DELETE_KEEP_DATA; 14212 } else { 14213 // Preserve data by setting flag 14214 flags |= PackageManager.DELETE_KEEP_DATA; 14215 } 14216 boolean ret = deleteInstalledPackageLI(deletedPkg, true, flags, allUserHandles, 14217 perUserInstalled, outInfo, writeSettings, replacingPackage); 14218 if (!ret) { 14219 return false; 14220 } 14221 14222 // writer 14223 synchronized (mPackages) { 14224 // Reinstate the old system package 14225 enableSystemPackageLPw(disabledPs.pkg); 14226 // Remove any native libraries from the upgraded package. 14227 removeNativeBinariesLI(deletedPkg); 14228 } 14229 14230 // Install the system package 14231 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14232 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14233 if (locationIsPrivileged(disabledPs.codePath)) { 14234 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14235 } 14236 14237 final PackageParser.Package newPkg; 14238 try { 14239 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14240 } catch (PackageManagerException e) { 14241 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14242 + e.getMessage()); 14243 return false; 14244 } 14245 14246 prepareAppDataAfterInstall(newPkg); 14247 14248 // writer 14249 synchronized (mPackages) { 14250 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14251 14252 // Propagate the permissions state as we do not want to drop on the floor 14253 // runtime permissions. The update permissions method below will take 14254 // care of removing obsolete permissions and grant install permissions. 14255 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14256 updatePermissionsLPw(newPkg.packageName, newPkg, 14257 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14258 14259 if (applyUserRestrictions) { 14260 if (DEBUG_REMOVE) { 14261 Slog.d(TAG, "Propagating install state across reinstall"); 14262 } 14263 for (int i = 0; i < allUserHandles.length; i++) { 14264 if (DEBUG_REMOVE) { 14265 Slog.d(TAG, " user " + allUserHandles[i] 14266 + " => " + perUserInstalled[i]); 14267 } 14268 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 14269 14270 mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false); 14271 } 14272 // Regardless of writeSettings we need to ensure that this restriction 14273 // state propagation is persisted 14274 mSettings.writeAllUsersPackageRestrictionsLPr(); 14275 } 14276 // can downgrade to reader here 14277 if (writeSettings) { 14278 mSettings.writeLPr(); 14279 } 14280 } 14281 return true; 14282 } 14283 14284 private boolean deleteInstalledPackageLI(PackageParser.Package pkg, 14285 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14286 boolean[] perUserInstalled, PackageRemovedInfo outInfo, boolean writeSettings, 14287 PackageParser.Package replacingPackage) { 14288 PackageSetting ps = null; 14289 14290 synchronized (mPackages) { 14291 pkg = mPackages.get(pkg.packageName); 14292 if (pkg == null) { 14293 return false; 14294 } 14295 14296 ps = mSettings.mPackages.get(pkg.packageName); 14297 if (ps == null) { 14298 return false; 14299 } 14300 14301 if (outInfo != null) { 14302 outInfo.uid = ps.appId; 14303 } 14304 } 14305 14306 // Delete package data from internal structures and also remove data if flag is set 14307 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, 14308 writeSettings); 14309 14310 // Delete the child packages data 14311 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14312 for (int i = 0; i < childCount; i++) { 14313 PackageSetting childPs; 14314 synchronized (mPackages) { 14315 childPs = mSettings.peekPackageLPr(pkg.childPackages.get(i).packageName); 14316 } 14317 if (childPs != null) { 14318 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14319 && (replacingPackage != null 14320 && !replacingPackage.hasChildPackage(childPs.name)) 14321 ? flags & ~DELETE_KEEP_DATA : flags; 14322 removePackageDataLI(childPs, allUserHandles, perUserInstalled, outInfo, 14323 deleteFlags, writeSettings); 14324 } 14325 } 14326 14327 // Delete application code and resources only for parent packages 14328 if (ps.pkg.parentPackage == null) { 14329 if (deleteCodeAndResources && (outInfo != null)) { 14330 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14331 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14332 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14333 } 14334 } 14335 14336 return true; 14337 } 14338 14339 @Override 14340 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14341 int userId) { 14342 mContext.enforceCallingOrSelfPermission( 14343 android.Manifest.permission.DELETE_PACKAGES, null); 14344 synchronized (mPackages) { 14345 PackageSetting ps = mSettings.mPackages.get(packageName); 14346 if (ps == null) { 14347 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14348 return false; 14349 } 14350 if (!ps.getInstalled(userId)) { 14351 // Can't block uninstall for an app that is not installed or enabled. 14352 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14353 return false; 14354 } 14355 ps.setBlockUninstall(blockUninstall, userId); 14356 mSettings.writePackageRestrictionsLPr(userId); 14357 } 14358 return true; 14359 } 14360 14361 @Override 14362 public boolean getBlockUninstallForUser(String packageName, int userId) { 14363 synchronized (mPackages) { 14364 PackageSetting ps = mSettings.mPackages.get(packageName); 14365 if (ps == null) { 14366 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14367 return false; 14368 } 14369 return ps.getBlockUninstall(userId); 14370 } 14371 } 14372 14373 @Override 14374 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14375 int callingUid = Binder.getCallingUid(); 14376 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14377 throw new SecurityException( 14378 "setRequiredForSystemUser can only be run by the system or root"); 14379 } 14380 synchronized (mPackages) { 14381 PackageSetting ps = mSettings.mPackages.get(packageName); 14382 if (ps == null) { 14383 Log.w(TAG, "Package doesn't exist: " + packageName); 14384 return false; 14385 } 14386 if (systemUserApp) { 14387 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14388 } else { 14389 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14390 } 14391 mSettings.writeLPr(); 14392 } 14393 return true; 14394 } 14395 14396 /* 14397 * This method handles package deletion in general 14398 */ 14399 private boolean deletePackageLI(String packageName, UserHandle user, 14400 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 14401 int flags, PackageRemovedInfo outInfo, boolean writeSettings, 14402 PackageParser.Package replacingPackage) { 14403 if (packageName == null) { 14404 Slog.w(TAG, "Attempt to delete null packageName."); 14405 return false; 14406 } 14407 14408 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14409 14410 PackageSetting ps; 14411 14412 synchronized (mPackages) { 14413 ps = mSettings.mPackages.get(packageName); 14414 if (ps == null) { 14415 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14416 return false; 14417 } 14418 14419 if (ps.pkg.parentPackage != null && (!isSystemApp(ps) 14420 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14421 if (DEBUG_REMOVE) { 14422 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14423 + ((user == null) ? UserHandle.USER_ALL : user)); 14424 } 14425 final int removedUserId = (user != null) ? user.getIdentifier() 14426 : UserHandle.USER_ALL; 14427 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14428 return false; 14429 } 14430 markPackageUninstalledForUserLPw(ps, user); 14431 scheduleWritePackageRestrictionsLocked(user); 14432 return true; 14433 } 14434 } 14435 14436 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14437 && user.getIdentifier() != UserHandle.USER_ALL)) { 14438 // The caller is asking that the package only be deleted for a single 14439 // user. To do this, we just mark its uninstalled state and delete 14440 // its data. If this is a system app, we only allow this to happen if 14441 // they have set the special DELETE_SYSTEM_APP which requests different 14442 // semantics than normal for uninstalling system apps. 14443 markPackageUninstalledForUserLPw(ps, user); 14444 14445 if (!isSystemApp(ps)) { 14446 // Do not uninstall the APK if an app should be cached 14447 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14448 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14449 // Other user still have this package installed, so all 14450 // we need to do is clear this user's data and save that 14451 // it is uninstalled. 14452 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14453 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14454 return false; 14455 } 14456 scheduleWritePackageRestrictionsLocked(user); 14457 return true; 14458 } else { 14459 // We need to set it back to 'installed' so the uninstall 14460 // broadcasts will be sent correctly. 14461 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14462 ps.setInstalled(true, user.getIdentifier()); 14463 } 14464 } else { 14465 // This is a system app, so we assume that the 14466 // other users still have this package installed, so all 14467 // we need to do is clear this user's data and save that 14468 // it is uninstalled. 14469 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14470 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14471 return false; 14472 } 14473 scheduleWritePackageRestrictionsLocked(user); 14474 return true; 14475 } 14476 } 14477 14478 boolean ret = false; 14479 if (isSystemApp(ps)) { 14480 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14481 // When an updated system application is deleted we delete the existing resources as well and 14482 // fall back to existing code in system partition 14483 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, perUserInstalled, 14484 flags, outInfo, writeSettings, replacingPackage); 14485 } else { 14486 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14487 // Kill application pre-emptively especially for apps on sd. 14488 killApplication(packageName, ps.appId, "uninstall pkg"); 14489 ret = deleteInstalledPackageLI(ps.pkg, deleteCodeAndResources, flags, allUserHandles, 14490 perUserInstalled, outInfo, writeSettings, replacingPackage); 14491 } 14492 14493 return ret; 14494 } 14495 14496 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 14497 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 14498 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 14499 for (int nextUserId : userIds) { 14500 if (DEBUG_REMOVE) { 14501 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 14502 } 14503 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 14504 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 14505 false /*hidden*/, false /*suspended*/, null, null, null, 14506 false /*blockUninstall*/, 14507 ps.readUserState(nextUserId).domainVerificationStatus, 0); 14508 } 14509 } 14510 14511 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 14512 PackageRemovedInfo outInfo) { 14513 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 14514 : new int[] {userId}; 14515 for (int nextUserId : userIds) { 14516 if (DEBUG_REMOVE) { 14517 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 14518 + nextUserId); 14519 } 14520 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 14521 try { 14522 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 14523 } catch (InstallerException e) { 14524 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 14525 return false; 14526 } 14527 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 14528 schedulePackageCleaning(ps.name, nextUserId, false); 14529 synchronized (mPackages) { 14530 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 14531 scheduleWritePackageRestrictionsLocked(nextUserId); 14532 } 14533 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 14534 } 14535 } 14536 14537 if (outInfo != null) { 14538 outInfo.removedPackage = ps.name; 14539 outInfo.removedAppId = ps.appId; 14540 outInfo.removedUsers = userIds; 14541 } 14542 14543 return true; 14544 } 14545 14546 private final class ClearStorageConnection implements ServiceConnection { 14547 IMediaContainerService mContainerService; 14548 14549 @Override 14550 public void onServiceConnected(ComponentName name, IBinder service) { 14551 synchronized (this) { 14552 mContainerService = IMediaContainerService.Stub.asInterface(service); 14553 notifyAll(); 14554 } 14555 } 14556 14557 @Override 14558 public void onServiceDisconnected(ComponentName name) { 14559 } 14560 } 14561 14562 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 14563 final boolean mounted; 14564 if (Environment.isExternalStorageEmulated()) { 14565 mounted = true; 14566 } else { 14567 final String status = Environment.getExternalStorageState(); 14568 14569 mounted = status.equals(Environment.MEDIA_MOUNTED) 14570 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 14571 } 14572 14573 if (!mounted) { 14574 return; 14575 } 14576 14577 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 14578 int[] users; 14579 if (userId == UserHandle.USER_ALL) { 14580 users = sUserManager.getUserIds(); 14581 } else { 14582 users = new int[] { userId }; 14583 } 14584 final ClearStorageConnection conn = new ClearStorageConnection(); 14585 if (mContext.bindServiceAsUser( 14586 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 14587 try { 14588 for (int curUser : users) { 14589 long timeout = SystemClock.uptimeMillis() + 5000; 14590 synchronized (conn) { 14591 long now = SystemClock.uptimeMillis(); 14592 while (conn.mContainerService == null && now < timeout) { 14593 try { 14594 conn.wait(timeout - now); 14595 } catch (InterruptedException e) { 14596 } 14597 } 14598 } 14599 if (conn.mContainerService == null) { 14600 return; 14601 } 14602 14603 final UserEnvironment userEnv = new UserEnvironment(curUser); 14604 clearDirectory(conn.mContainerService, 14605 userEnv.buildExternalStorageAppCacheDirs(packageName)); 14606 if (allData) { 14607 clearDirectory(conn.mContainerService, 14608 userEnv.buildExternalStorageAppDataDirs(packageName)); 14609 clearDirectory(conn.mContainerService, 14610 userEnv.buildExternalStorageAppMediaDirs(packageName)); 14611 } 14612 } 14613 } finally { 14614 mContext.unbindService(conn); 14615 } 14616 } 14617 } 14618 14619 @Override 14620 public void clearApplicationUserData(final String packageName, 14621 final IPackageDataObserver observer, final int userId) { 14622 mContext.enforceCallingOrSelfPermission( 14623 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 14624 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 14625 // Queue up an async operation since the package deletion may take a little while. 14626 mHandler.post(new Runnable() { 14627 public void run() { 14628 mHandler.removeCallbacks(this); 14629 final boolean succeeded; 14630 synchronized (mInstallLock) { 14631 succeeded = clearApplicationUserDataLI(packageName, userId); 14632 } 14633 clearExternalStorageDataSync(packageName, userId, true); 14634 if (succeeded) { 14635 // invoke DeviceStorageMonitor's update method to clear any notifications 14636 DeviceStorageMonitorInternal 14637 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14638 if (dsm != null) { 14639 dsm.checkMemory(); 14640 } 14641 } 14642 if(observer != null) { 14643 try { 14644 observer.onRemoveCompleted(packageName, succeeded); 14645 } catch (RemoteException e) { 14646 Log.i(TAG, "Observer no longer exists."); 14647 } 14648 } //end if observer 14649 } //end run 14650 }); 14651 } 14652 14653 private boolean clearApplicationUserDataLI(String packageName, int userId) { 14654 if (packageName == null) { 14655 Slog.w(TAG, "Attempt to delete null packageName."); 14656 return false; 14657 } 14658 14659 // Try finding details about the requested package 14660 PackageParser.Package pkg; 14661 synchronized (mPackages) { 14662 pkg = mPackages.get(packageName); 14663 if (pkg == null) { 14664 final PackageSetting ps = mSettings.mPackages.get(packageName); 14665 if (ps != null) { 14666 pkg = ps.pkg; 14667 } 14668 } 14669 14670 if (pkg == null) { 14671 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14672 return false; 14673 } 14674 14675 PackageSetting ps = (PackageSetting) pkg.mExtras; 14676 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14677 } 14678 14679 // Always delete data directories for package, even if we found no other 14680 // record of app. This helps users recover from UID mismatches without 14681 // resorting to a full data wipe. 14682 // TODO: triage flags as part of 26466827 14683 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14684 try { 14685 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 14686 } catch (InstallerException e) { 14687 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 14688 return false; 14689 } 14690 14691 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14692 removeKeystoreDataIfNeeded(userId, appId); 14693 14694 // Create a native library symlink only if we have native libraries 14695 // and if the native libraries are 32 bit libraries. We do not provide 14696 // this symlink for 64 bit libraries. 14697 if (pkg.applicationInfo.primaryCpuAbi != null && 14698 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 14699 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 14700 try { 14701 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 14702 nativeLibPath, userId); 14703 } catch (InstallerException e) { 14704 Slog.w(TAG, "Failed linking native library dir", e); 14705 return false; 14706 } 14707 } 14708 14709 return true; 14710 } 14711 14712 /** 14713 * Reverts user permission state changes (permissions and flags) in 14714 * all packages for a given user. 14715 * 14716 * @param userId The device user for which to do a reset. 14717 */ 14718 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 14719 final int packageCount = mPackages.size(); 14720 for (int i = 0; i < packageCount; i++) { 14721 PackageParser.Package pkg = mPackages.valueAt(i); 14722 PackageSetting ps = (PackageSetting) pkg.mExtras; 14723 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 14724 } 14725 } 14726 14727 /** 14728 * Reverts user permission state changes (permissions and flags). 14729 * 14730 * @param ps The package for which to reset. 14731 * @param userId The device user for which to do a reset. 14732 */ 14733 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 14734 final PackageSetting ps, final int userId) { 14735 if (ps.pkg == null) { 14736 return; 14737 } 14738 14739 // These are flags that can change base on user actions. 14740 final int userSettableMask = FLAG_PERMISSION_USER_SET 14741 | FLAG_PERMISSION_USER_FIXED 14742 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 14743 | FLAG_PERMISSION_REVIEW_REQUIRED; 14744 14745 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 14746 | FLAG_PERMISSION_POLICY_FIXED; 14747 14748 boolean writeInstallPermissions = false; 14749 boolean writeRuntimePermissions = false; 14750 14751 final int permissionCount = ps.pkg.requestedPermissions.size(); 14752 for (int i = 0; i < permissionCount; i++) { 14753 String permission = ps.pkg.requestedPermissions.get(i); 14754 14755 BasePermission bp = mSettings.mPermissions.get(permission); 14756 if (bp == null) { 14757 continue; 14758 } 14759 14760 // If shared user we just reset the state to which only this app contributed. 14761 if (ps.sharedUser != null) { 14762 boolean used = false; 14763 final int packageCount = ps.sharedUser.packages.size(); 14764 for (int j = 0; j < packageCount; j++) { 14765 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 14766 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 14767 && pkg.pkg.requestedPermissions.contains(permission)) { 14768 used = true; 14769 break; 14770 } 14771 } 14772 if (used) { 14773 continue; 14774 } 14775 } 14776 14777 PermissionsState permissionsState = ps.getPermissionsState(); 14778 14779 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 14780 14781 // Always clear the user settable flags. 14782 final boolean hasInstallState = permissionsState.getInstallPermissionState( 14783 bp.name) != null; 14784 // If permission review is enabled and this is a legacy app, mark the 14785 // permission as requiring a review as this is the initial state. 14786 int flags = 0; 14787 if (Build.PERMISSIONS_REVIEW_REQUIRED 14788 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 14789 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 14790 } 14791 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 14792 if (hasInstallState) { 14793 writeInstallPermissions = true; 14794 } else { 14795 writeRuntimePermissions = true; 14796 } 14797 } 14798 14799 // Below is only runtime permission handling. 14800 if (!bp.isRuntime()) { 14801 continue; 14802 } 14803 14804 // Never clobber system or policy. 14805 if ((oldFlags & policyOrSystemFlags) != 0) { 14806 continue; 14807 } 14808 14809 // If this permission was granted by default, make sure it is. 14810 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 14811 if (permissionsState.grantRuntimePermission(bp, userId) 14812 != PERMISSION_OPERATION_FAILURE) { 14813 writeRuntimePermissions = true; 14814 } 14815 // If permission review is enabled the permissions for a legacy apps 14816 // are represented as constantly granted runtime ones, so don't revoke. 14817 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 14818 // Otherwise, reset the permission. 14819 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 14820 switch (revokeResult) { 14821 case PERMISSION_OPERATION_SUCCESS: { 14822 writeRuntimePermissions = true; 14823 } break; 14824 14825 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 14826 writeRuntimePermissions = true; 14827 final int appId = ps.appId; 14828 mHandler.post(new Runnable() { 14829 @Override 14830 public void run() { 14831 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 14832 } 14833 }); 14834 } break; 14835 } 14836 } 14837 } 14838 14839 // Synchronously write as we are taking permissions away. 14840 if (writeRuntimePermissions) { 14841 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 14842 } 14843 14844 // Synchronously write as we are taking permissions away. 14845 if (writeInstallPermissions) { 14846 mSettings.writeLPr(); 14847 } 14848 } 14849 14850 /** 14851 * Remove entries from the keystore daemon. Will only remove it if the 14852 * {@code appId} is valid. 14853 */ 14854 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 14855 if (appId < 0) { 14856 return; 14857 } 14858 14859 final KeyStore keyStore = KeyStore.getInstance(); 14860 if (keyStore != null) { 14861 if (userId == UserHandle.USER_ALL) { 14862 for (final int individual : sUserManager.getUserIds()) { 14863 keyStore.clearUid(UserHandle.getUid(individual, appId)); 14864 } 14865 } else { 14866 keyStore.clearUid(UserHandle.getUid(userId, appId)); 14867 } 14868 } else { 14869 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 14870 } 14871 } 14872 14873 @Override 14874 public void deleteApplicationCacheFiles(final String packageName, 14875 final IPackageDataObserver observer) { 14876 mContext.enforceCallingOrSelfPermission( 14877 android.Manifest.permission.DELETE_CACHE_FILES, null); 14878 // Queue up an async operation since the package deletion may take a little while. 14879 final int userId = UserHandle.getCallingUserId(); 14880 mHandler.post(new Runnable() { 14881 public void run() { 14882 mHandler.removeCallbacks(this); 14883 final boolean succeded; 14884 synchronized (mInstallLock) { 14885 succeded = deleteApplicationCacheFilesLI(packageName, userId); 14886 } 14887 clearExternalStorageDataSync(packageName, userId, false); 14888 if (observer != null) { 14889 try { 14890 observer.onRemoveCompleted(packageName, succeded); 14891 } catch (RemoteException e) { 14892 Log.i(TAG, "Observer no longer exists."); 14893 } 14894 } //end if observer 14895 } //end run 14896 }); 14897 } 14898 14899 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 14900 if (packageName == null) { 14901 Slog.w(TAG, "Attempt to delete null packageName."); 14902 return false; 14903 } 14904 PackageParser.Package p; 14905 synchronized (mPackages) { 14906 p = mPackages.get(packageName); 14907 } 14908 if (p == null) { 14909 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14910 return false; 14911 } 14912 final ApplicationInfo applicationInfo = p.applicationInfo; 14913 if (applicationInfo == null) { 14914 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14915 return false; 14916 } 14917 // TODO: triage flags as part of 26466827 14918 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 14919 try { 14920 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 14921 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 14922 } catch (InstallerException e) { 14923 Slog.w(TAG, "Couldn't remove cache files for package " 14924 + packageName + " u" + userId, e); 14925 return false; 14926 } 14927 return true; 14928 } 14929 14930 @Override 14931 public void getPackageSizeInfo(final String packageName, int userHandle, 14932 final IPackageStatsObserver observer) { 14933 mContext.enforceCallingOrSelfPermission( 14934 android.Manifest.permission.GET_PACKAGE_SIZE, null); 14935 if (packageName == null) { 14936 throw new IllegalArgumentException("Attempt to get size of null packageName"); 14937 } 14938 14939 PackageStats stats = new PackageStats(packageName, userHandle); 14940 14941 /* 14942 * Queue up an async operation since the package measurement may take a 14943 * little while. 14944 */ 14945 Message msg = mHandler.obtainMessage(INIT_COPY); 14946 msg.obj = new MeasureParams(stats, observer); 14947 mHandler.sendMessage(msg); 14948 } 14949 14950 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 14951 PackageStats pStats) { 14952 if (packageName == null) { 14953 Slog.w(TAG, "Attempt to get size of null packageName."); 14954 return false; 14955 } 14956 PackageParser.Package p; 14957 boolean dataOnly = false; 14958 String libDirRoot = null; 14959 String asecPath = null; 14960 PackageSetting ps = null; 14961 synchronized (mPackages) { 14962 p = mPackages.get(packageName); 14963 ps = mSettings.mPackages.get(packageName); 14964 if(p == null) { 14965 dataOnly = true; 14966 if((ps == null) || (ps.pkg == null)) { 14967 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 14968 return false; 14969 } 14970 p = ps.pkg; 14971 } 14972 if (ps != null) { 14973 libDirRoot = ps.legacyNativeLibraryPathString; 14974 } 14975 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 14976 final long token = Binder.clearCallingIdentity(); 14977 try { 14978 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 14979 if (secureContainerId != null) { 14980 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 14981 } 14982 } finally { 14983 Binder.restoreCallingIdentity(token); 14984 } 14985 } 14986 } 14987 String publicSrcDir = null; 14988 if(!dataOnly) { 14989 final ApplicationInfo applicationInfo = p.applicationInfo; 14990 if (applicationInfo == null) { 14991 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 14992 return false; 14993 } 14994 if (p.isForwardLocked()) { 14995 publicSrcDir = applicationInfo.getBaseResourcePath(); 14996 } 14997 } 14998 // TODO: extend to measure size of split APKs 14999 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15000 // not just the first level. 15001 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15002 // just the primary. 15003 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15004 15005 String apkPath; 15006 File packageDir = new File(p.codePath); 15007 15008 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15009 apkPath = packageDir.getAbsolutePath(); 15010 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15011 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15012 libDirRoot = null; 15013 } 15014 } else { 15015 apkPath = p.baseCodePath; 15016 } 15017 15018 // TODO: triage flags as part of 26466827 15019 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15020 try { 15021 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15022 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15023 } catch (InstallerException e) { 15024 return false; 15025 } 15026 15027 // Fix-up for forward-locked applications in ASEC containers. 15028 if (!isExternal(p)) { 15029 pStats.codeSize += pStats.externalCodeSize; 15030 pStats.externalCodeSize = 0L; 15031 } 15032 15033 return true; 15034 } 15035 15036 15037 @Override 15038 public void addPackageToPreferred(String packageName) { 15039 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 15040 } 15041 15042 @Override 15043 public void removePackageFromPreferred(String packageName) { 15044 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 15045 } 15046 15047 @Override 15048 public List<PackageInfo> getPreferredPackages(int flags) { 15049 return new ArrayList<PackageInfo>(); 15050 } 15051 15052 private int getUidTargetSdkVersionLockedLPr(int uid) { 15053 Object obj = mSettings.getUserIdLPr(uid); 15054 if (obj instanceof SharedUserSetting) { 15055 final SharedUserSetting sus = (SharedUserSetting) obj; 15056 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15057 final Iterator<PackageSetting> it = sus.packages.iterator(); 15058 while (it.hasNext()) { 15059 final PackageSetting ps = it.next(); 15060 if (ps.pkg != null) { 15061 int v = ps.pkg.applicationInfo.targetSdkVersion; 15062 if (v < vers) vers = v; 15063 } 15064 } 15065 return vers; 15066 } else if (obj instanceof PackageSetting) { 15067 final PackageSetting ps = (PackageSetting) obj; 15068 if (ps.pkg != null) { 15069 return ps.pkg.applicationInfo.targetSdkVersion; 15070 } 15071 } 15072 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15073 } 15074 15075 @Override 15076 public void addPreferredActivity(IntentFilter filter, int match, 15077 ComponentName[] set, ComponentName activity, int userId) { 15078 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15079 "Adding preferred"); 15080 } 15081 15082 private void addPreferredActivityInternal(IntentFilter filter, int match, 15083 ComponentName[] set, ComponentName activity, boolean always, int userId, 15084 String opname) { 15085 // writer 15086 int callingUid = Binder.getCallingUid(); 15087 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 15088 if (filter.countActions() == 0) { 15089 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15090 return; 15091 } 15092 synchronized (mPackages) { 15093 if (mContext.checkCallingOrSelfPermission( 15094 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15095 != PackageManager.PERMISSION_GRANTED) { 15096 if (getUidTargetSdkVersionLockedLPr(callingUid) 15097 < Build.VERSION_CODES.FROYO) { 15098 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15099 + callingUid); 15100 return; 15101 } 15102 mContext.enforceCallingOrSelfPermission( 15103 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15104 } 15105 15106 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15107 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15108 + userId + ":"); 15109 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15110 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15111 scheduleWritePackageRestrictionsLocked(userId); 15112 } 15113 } 15114 15115 @Override 15116 public void replacePreferredActivity(IntentFilter filter, int match, 15117 ComponentName[] set, ComponentName activity, int userId) { 15118 if (filter.countActions() != 1) { 15119 throw new IllegalArgumentException( 15120 "replacePreferredActivity expects filter to have only 1 action."); 15121 } 15122 if (filter.countDataAuthorities() != 0 15123 || filter.countDataPaths() != 0 15124 || filter.countDataSchemes() > 1 15125 || filter.countDataTypes() != 0) { 15126 throw new IllegalArgumentException( 15127 "replacePreferredActivity expects filter to have no data authorities, " + 15128 "paths, or types; and at most one scheme."); 15129 } 15130 15131 final int callingUid = Binder.getCallingUid(); 15132 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 15133 synchronized (mPackages) { 15134 if (mContext.checkCallingOrSelfPermission( 15135 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15136 != PackageManager.PERMISSION_GRANTED) { 15137 if (getUidTargetSdkVersionLockedLPr(callingUid) 15138 < Build.VERSION_CODES.FROYO) { 15139 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15140 + Binder.getCallingUid()); 15141 return; 15142 } 15143 mContext.enforceCallingOrSelfPermission( 15144 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15145 } 15146 15147 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15148 if (pir != null) { 15149 // Get all of the existing entries that exactly match this filter. 15150 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15151 if (existing != null && existing.size() == 1) { 15152 PreferredActivity cur = existing.get(0); 15153 if (DEBUG_PREFERRED) { 15154 Slog.i(TAG, "Checking replace of preferred:"); 15155 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15156 if (!cur.mPref.mAlways) { 15157 Slog.i(TAG, " -- CUR; not mAlways!"); 15158 } else { 15159 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15160 Slog.i(TAG, " -- CUR: mSet=" 15161 + Arrays.toString(cur.mPref.mSetComponents)); 15162 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15163 Slog.i(TAG, " -- NEW: mMatch=" 15164 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15165 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15166 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15167 } 15168 } 15169 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15170 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15171 && cur.mPref.sameSet(set)) { 15172 // Setting the preferred activity to what it happens to be already 15173 if (DEBUG_PREFERRED) { 15174 Slog.i(TAG, "Replacing with same preferred activity " 15175 + cur.mPref.mShortComponent + " for user " 15176 + userId + ":"); 15177 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15178 } 15179 return; 15180 } 15181 } 15182 15183 if (existing != null) { 15184 if (DEBUG_PREFERRED) { 15185 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15186 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15187 } 15188 for (int i = 0; i < existing.size(); i++) { 15189 PreferredActivity pa = existing.get(i); 15190 if (DEBUG_PREFERRED) { 15191 Slog.i(TAG, "Removing existing preferred activity " 15192 + pa.mPref.mComponent + ":"); 15193 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15194 } 15195 pir.removeFilter(pa); 15196 } 15197 } 15198 } 15199 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15200 "Replacing preferred"); 15201 } 15202 } 15203 15204 @Override 15205 public void clearPackagePreferredActivities(String packageName) { 15206 final int uid = Binder.getCallingUid(); 15207 // writer 15208 synchronized (mPackages) { 15209 PackageParser.Package pkg = mPackages.get(packageName); 15210 if (pkg == null || pkg.applicationInfo.uid != uid) { 15211 if (mContext.checkCallingOrSelfPermission( 15212 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15213 != PackageManager.PERMISSION_GRANTED) { 15214 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15215 < Build.VERSION_CODES.FROYO) { 15216 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15217 + Binder.getCallingUid()); 15218 return; 15219 } 15220 mContext.enforceCallingOrSelfPermission( 15221 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15222 } 15223 } 15224 15225 int user = UserHandle.getCallingUserId(); 15226 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15227 scheduleWritePackageRestrictionsLocked(user); 15228 } 15229 } 15230 } 15231 15232 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15233 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15234 ArrayList<PreferredActivity> removed = null; 15235 boolean changed = false; 15236 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15237 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15238 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15239 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15240 continue; 15241 } 15242 Iterator<PreferredActivity> it = pir.filterIterator(); 15243 while (it.hasNext()) { 15244 PreferredActivity pa = it.next(); 15245 // Mark entry for removal only if it matches the package name 15246 // and the entry is of type "always". 15247 if (packageName == null || 15248 (pa.mPref.mComponent.getPackageName().equals(packageName) 15249 && pa.mPref.mAlways)) { 15250 if (removed == null) { 15251 removed = new ArrayList<PreferredActivity>(); 15252 } 15253 removed.add(pa); 15254 } 15255 } 15256 if (removed != null) { 15257 for (int j=0; j<removed.size(); j++) { 15258 PreferredActivity pa = removed.get(j); 15259 pir.removeFilter(pa); 15260 } 15261 changed = true; 15262 } 15263 } 15264 return changed; 15265 } 15266 15267 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15268 private void clearIntentFilterVerificationsLPw(int userId) { 15269 final int packageCount = mPackages.size(); 15270 for (int i = 0; i < packageCount; i++) { 15271 PackageParser.Package pkg = mPackages.valueAt(i); 15272 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15273 } 15274 } 15275 15276 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15277 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15278 if (userId == UserHandle.USER_ALL) { 15279 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15280 sUserManager.getUserIds())) { 15281 for (int oneUserId : sUserManager.getUserIds()) { 15282 scheduleWritePackageRestrictionsLocked(oneUserId); 15283 } 15284 } 15285 } else { 15286 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15287 scheduleWritePackageRestrictionsLocked(userId); 15288 } 15289 } 15290 } 15291 15292 void clearDefaultBrowserIfNeeded(String packageName) { 15293 for (int oneUserId : sUserManager.getUserIds()) { 15294 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15295 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15296 if (packageName.equals(defaultBrowserPackageName)) { 15297 setDefaultBrowserPackageName(null, oneUserId); 15298 } 15299 } 15300 } 15301 15302 @Override 15303 public void resetApplicationPreferences(int userId) { 15304 mContext.enforceCallingOrSelfPermission( 15305 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15306 // writer 15307 synchronized (mPackages) { 15308 final long identity = Binder.clearCallingIdentity(); 15309 try { 15310 clearPackagePreferredActivitiesLPw(null, userId); 15311 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15312 // TODO: We have to reset the default SMS and Phone. This requires 15313 // significant refactoring to keep all default apps in the package 15314 // manager (cleaner but more work) or have the services provide 15315 // callbacks to the package manager to request a default app reset. 15316 applyFactoryDefaultBrowserLPw(userId); 15317 clearIntentFilterVerificationsLPw(userId); 15318 primeDomainVerificationsLPw(userId); 15319 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15320 scheduleWritePackageRestrictionsLocked(userId); 15321 } finally { 15322 Binder.restoreCallingIdentity(identity); 15323 } 15324 } 15325 } 15326 15327 @Override 15328 public int getPreferredActivities(List<IntentFilter> outFilters, 15329 List<ComponentName> outActivities, String packageName) { 15330 15331 int num = 0; 15332 final int userId = UserHandle.getCallingUserId(); 15333 // reader 15334 synchronized (mPackages) { 15335 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15336 if (pir != null) { 15337 final Iterator<PreferredActivity> it = pir.filterIterator(); 15338 while (it.hasNext()) { 15339 final PreferredActivity pa = it.next(); 15340 if (packageName == null 15341 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15342 && pa.mPref.mAlways)) { 15343 if (outFilters != null) { 15344 outFilters.add(new IntentFilter(pa)); 15345 } 15346 if (outActivities != null) { 15347 outActivities.add(pa.mPref.mComponent); 15348 } 15349 } 15350 } 15351 } 15352 } 15353 15354 return num; 15355 } 15356 15357 @Override 15358 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15359 int userId) { 15360 int callingUid = Binder.getCallingUid(); 15361 if (callingUid != Process.SYSTEM_UID) { 15362 throw new SecurityException( 15363 "addPersistentPreferredActivity can only be run by the system"); 15364 } 15365 if (filter.countActions() == 0) { 15366 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15367 return; 15368 } 15369 synchronized (mPackages) { 15370 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15371 ":"); 15372 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15373 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15374 new PersistentPreferredActivity(filter, activity)); 15375 scheduleWritePackageRestrictionsLocked(userId); 15376 } 15377 } 15378 15379 @Override 15380 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15381 int callingUid = Binder.getCallingUid(); 15382 if (callingUid != Process.SYSTEM_UID) { 15383 throw new SecurityException( 15384 "clearPackagePersistentPreferredActivities can only be run by the system"); 15385 } 15386 ArrayList<PersistentPreferredActivity> removed = null; 15387 boolean changed = false; 15388 synchronized (mPackages) { 15389 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15390 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15391 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15392 .valueAt(i); 15393 if (userId != thisUserId) { 15394 continue; 15395 } 15396 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15397 while (it.hasNext()) { 15398 PersistentPreferredActivity ppa = it.next(); 15399 // Mark entry for removal only if it matches the package name. 15400 if (ppa.mComponent.getPackageName().equals(packageName)) { 15401 if (removed == null) { 15402 removed = new ArrayList<PersistentPreferredActivity>(); 15403 } 15404 removed.add(ppa); 15405 } 15406 } 15407 if (removed != null) { 15408 for (int j=0; j<removed.size(); j++) { 15409 PersistentPreferredActivity ppa = removed.get(j); 15410 ppir.removeFilter(ppa); 15411 } 15412 changed = true; 15413 } 15414 } 15415 15416 if (changed) { 15417 scheduleWritePackageRestrictionsLocked(userId); 15418 } 15419 } 15420 } 15421 15422 /** 15423 * Common machinery for picking apart a restored XML blob and passing 15424 * it to a caller-supplied functor to be applied to the running system. 15425 */ 15426 private void restoreFromXml(XmlPullParser parser, int userId, 15427 String expectedStartTag, BlobXmlRestorer functor) 15428 throws IOException, XmlPullParserException { 15429 int type; 15430 while ((type = parser.next()) != XmlPullParser.START_TAG 15431 && type != XmlPullParser.END_DOCUMENT) { 15432 } 15433 if (type != XmlPullParser.START_TAG) { 15434 // oops didn't find a start tag?! 15435 if (DEBUG_BACKUP) { 15436 Slog.e(TAG, "Didn't find start tag during restore"); 15437 } 15438 return; 15439 } 15440Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15441 // this is supposed to be TAG_PREFERRED_BACKUP 15442 if (!expectedStartTag.equals(parser.getName())) { 15443 if (DEBUG_BACKUP) { 15444 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15445 } 15446 return; 15447 } 15448 15449 // skip interfering stuff, then we're aligned with the backing implementation 15450 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15451Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15452 functor.apply(parser, userId); 15453 } 15454 15455 private interface BlobXmlRestorer { 15456 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15457 } 15458 15459 /** 15460 * Non-Binder method, support for the backup/restore mechanism: write the 15461 * full set of preferred activities in its canonical XML format. Returns the 15462 * XML output as a byte array, or null if there is none. 15463 */ 15464 @Override 15465 public byte[] getPreferredActivityBackup(int userId) { 15466 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15467 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15468 } 15469 15470 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15471 try { 15472 final XmlSerializer serializer = new FastXmlSerializer(); 15473 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15474 serializer.startDocument(null, true); 15475 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15476 15477 synchronized (mPackages) { 15478 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15479 } 15480 15481 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15482 serializer.endDocument(); 15483 serializer.flush(); 15484 } catch (Exception e) { 15485 if (DEBUG_BACKUP) { 15486 Slog.e(TAG, "Unable to write preferred activities for backup", e); 15487 } 15488 return null; 15489 } 15490 15491 return dataStream.toByteArray(); 15492 } 15493 15494 @Override 15495 public void restorePreferredActivities(byte[] backup, int userId) { 15496 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15497 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15498 } 15499 15500 try { 15501 final XmlPullParser parser = Xml.newPullParser(); 15502 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15503 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 15504 new BlobXmlRestorer() { 15505 @Override 15506 public void apply(XmlPullParser parser, int userId) 15507 throws XmlPullParserException, IOException { 15508 synchronized (mPackages) { 15509 mSettings.readPreferredActivitiesLPw(parser, userId); 15510 } 15511 } 15512 } ); 15513 } catch (Exception e) { 15514 if (DEBUG_BACKUP) { 15515 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15516 } 15517 } 15518 } 15519 15520 /** 15521 * Non-Binder method, support for the backup/restore mechanism: write the 15522 * default browser (etc) settings in its canonical XML format. Returns the default 15523 * browser XML representation as a byte array, or null if there is none. 15524 */ 15525 @Override 15526 public byte[] getDefaultAppsBackup(int userId) { 15527 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15528 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 15529 } 15530 15531 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15532 try { 15533 final XmlSerializer serializer = new FastXmlSerializer(); 15534 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15535 serializer.startDocument(null, true); 15536 serializer.startTag(null, TAG_DEFAULT_APPS); 15537 15538 synchronized (mPackages) { 15539 mSettings.writeDefaultAppsLPr(serializer, userId); 15540 } 15541 15542 serializer.endTag(null, TAG_DEFAULT_APPS); 15543 serializer.endDocument(); 15544 serializer.flush(); 15545 } catch (Exception e) { 15546 if (DEBUG_BACKUP) { 15547 Slog.e(TAG, "Unable to write default apps for backup", e); 15548 } 15549 return null; 15550 } 15551 15552 return dataStream.toByteArray(); 15553 } 15554 15555 @Override 15556 public void restoreDefaultApps(byte[] backup, int userId) { 15557 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15558 throw new SecurityException("Only the system may call restoreDefaultApps()"); 15559 } 15560 15561 try { 15562 final XmlPullParser parser = Xml.newPullParser(); 15563 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15564 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 15565 new BlobXmlRestorer() { 15566 @Override 15567 public void apply(XmlPullParser parser, int userId) 15568 throws XmlPullParserException, IOException { 15569 synchronized (mPackages) { 15570 mSettings.readDefaultAppsLPw(parser, userId); 15571 } 15572 } 15573 } ); 15574 } catch (Exception e) { 15575 if (DEBUG_BACKUP) { 15576 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 15577 } 15578 } 15579 } 15580 15581 @Override 15582 public byte[] getIntentFilterVerificationBackup(int userId) { 15583 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15584 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 15585 } 15586 15587 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15588 try { 15589 final XmlSerializer serializer = new FastXmlSerializer(); 15590 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15591 serializer.startDocument(null, true); 15592 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 15593 15594 synchronized (mPackages) { 15595 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 15596 } 15597 15598 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 15599 serializer.endDocument(); 15600 serializer.flush(); 15601 } catch (Exception e) { 15602 if (DEBUG_BACKUP) { 15603 Slog.e(TAG, "Unable to write default apps for backup", e); 15604 } 15605 return null; 15606 } 15607 15608 return dataStream.toByteArray(); 15609 } 15610 15611 @Override 15612 public void restoreIntentFilterVerification(byte[] backup, int userId) { 15613 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15614 throw new SecurityException("Only the system may call restorePreferredActivities()"); 15615 } 15616 15617 try { 15618 final XmlPullParser parser = Xml.newPullParser(); 15619 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15620 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 15621 new BlobXmlRestorer() { 15622 @Override 15623 public void apply(XmlPullParser parser, int userId) 15624 throws XmlPullParserException, IOException { 15625 synchronized (mPackages) { 15626 mSettings.readAllDomainVerificationsLPr(parser, userId); 15627 mSettings.writeLPr(); 15628 } 15629 } 15630 } ); 15631 } catch (Exception e) { 15632 if (DEBUG_BACKUP) { 15633 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15634 } 15635 } 15636 } 15637 15638 @Override 15639 public byte[] getPermissionGrantBackup(int userId) { 15640 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15641 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 15642 } 15643 15644 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15645 try { 15646 final XmlSerializer serializer = new FastXmlSerializer(); 15647 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15648 serializer.startDocument(null, true); 15649 serializer.startTag(null, TAG_PERMISSION_BACKUP); 15650 15651 synchronized (mPackages) { 15652 serializeRuntimePermissionGrantsLPr(serializer, userId); 15653 } 15654 15655 serializer.endTag(null, TAG_PERMISSION_BACKUP); 15656 serializer.endDocument(); 15657 serializer.flush(); 15658 } catch (Exception e) { 15659 if (DEBUG_BACKUP) { 15660 Slog.e(TAG, "Unable to write default apps for backup", e); 15661 } 15662 return null; 15663 } 15664 15665 return dataStream.toByteArray(); 15666 } 15667 15668 @Override 15669 public void restorePermissionGrants(byte[] backup, int userId) { 15670 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15671 throw new SecurityException("Only the system may call restorePermissionGrants()"); 15672 } 15673 15674 try { 15675 final XmlPullParser parser = Xml.newPullParser(); 15676 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 15677 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 15678 new BlobXmlRestorer() { 15679 @Override 15680 public void apply(XmlPullParser parser, int userId) 15681 throws XmlPullParserException, IOException { 15682 synchronized (mPackages) { 15683 processRestoredPermissionGrantsLPr(parser, userId); 15684 } 15685 } 15686 } ); 15687 } catch (Exception e) { 15688 if (DEBUG_BACKUP) { 15689 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 15690 } 15691 } 15692 } 15693 15694 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 15695 throws IOException { 15696 serializer.startTag(null, TAG_ALL_GRANTS); 15697 15698 final int N = mSettings.mPackages.size(); 15699 for (int i = 0; i < N; i++) { 15700 final PackageSetting ps = mSettings.mPackages.valueAt(i); 15701 boolean pkgGrantsKnown = false; 15702 15703 PermissionsState packagePerms = ps.getPermissionsState(); 15704 15705 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 15706 final int grantFlags = state.getFlags(); 15707 // only look at grants that are not system/policy fixed 15708 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 15709 final boolean isGranted = state.isGranted(); 15710 // And only back up the user-twiddled state bits 15711 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 15712 final String packageName = mSettings.mPackages.keyAt(i); 15713 if (!pkgGrantsKnown) { 15714 serializer.startTag(null, TAG_GRANT); 15715 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 15716 pkgGrantsKnown = true; 15717 } 15718 15719 final boolean userSet = 15720 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 15721 final boolean userFixed = 15722 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 15723 final boolean revoke = 15724 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 15725 15726 serializer.startTag(null, TAG_PERMISSION); 15727 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 15728 if (isGranted) { 15729 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 15730 } 15731 if (userSet) { 15732 serializer.attribute(null, ATTR_USER_SET, "true"); 15733 } 15734 if (userFixed) { 15735 serializer.attribute(null, ATTR_USER_FIXED, "true"); 15736 } 15737 if (revoke) { 15738 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 15739 } 15740 serializer.endTag(null, TAG_PERMISSION); 15741 } 15742 } 15743 } 15744 15745 if (pkgGrantsKnown) { 15746 serializer.endTag(null, TAG_GRANT); 15747 } 15748 } 15749 15750 serializer.endTag(null, TAG_ALL_GRANTS); 15751 } 15752 15753 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 15754 throws XmlPullParserException, IOException { 15755 String pkgName = null; 15756 int outerDepth = parser.getDepth(); 15757 int type; 15758 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 15759 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 15760 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 15761 continue; 15762 } 15763 15764 final String tagName = parser.getName(); 15765 if (tagName.equals(TAG_GRANT)) { 15766 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 15767 if (DEBUG_BACKUP) { 15768 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 15769 } 15770 } else if (tagName.equals(TAG_PERMISSION)) { 15771 15772 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 15773 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 15774 15775 int newFlagSet = 0; 15776 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 15777 newFlagSet |= FLAG_PERMISSION_USER_SET; 15778 } 15779 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 15780 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 15781 } 15782 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 15783 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 15784 } 15785 if (DEBUG_BACKUP) { 15786 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 15787 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 15788 } 15789 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15790 if (ps != null) { 15791 // Already installed so we apply the grant immediately 15792 if (DEBUG_BACKUP) { 15793 Slog.v(TAG, " + already installed; applying"); 15794 } 15795 PermissionsState perms = ps.getPermissionsState(); 15796 BasePermission bp = mSettings.mPermissions.get(permName); 15797 if (bp != null) { 15798 if (isGranted) { 15799 perms.grantRuntimePermission(bp, userId); 15800 } 15801 if (newFlagSet != 0) { 15802 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 15803 } 15804 } 15805 } else { 15806 // Need to wait for post-restore install to apply the grant 15807 if (DEBUG_BACKUP) { 15808 Slog.v(TAG, " - not yet installed; saving for later"); 15809 } 15810 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 15811 isGranted, newFlagSet, userId); 15812 } 15813 } else { 15814 PackageManagerService.reportSettingsProblem(Log.WARN, 15815 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 15816 XmlUtils.skipCurrentTag(parser); 15817 } 15818 } 15819 15820 scheduleWriteSettingsLocked(); 15821 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15822 } 15823 15824 @Override 15825 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 15826 int sourceUserId, int targetUserId, int flags) { 15827 mContext.enforceCallingOrSelfPermission( 15828 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15829 int callingUid = Binder.getCallingUid(); 15830 enforceOwnerRights(ownerPackage, callingUid); 15831 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15832 if (intentFilter.countActions() == 0) { 15833 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 15834 return; 15835 } 15836 synchronized (mPackages) { 15837 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 15838 ownerPackage, targetUserId, flags); 15839 CrossProfileIntentResolver resolver = 15840 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15841 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 15842 // We have all those whose filter is equal. Now checking if the rest is equal as well. 15843 if (existing != null) { 15844 int size = existing.size(); 15845 for (int i = 0; i < size; i++) { 15846 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 15847 return; 15848 } 15849 } 15850 } 15851 resolver.addFilter(newFilter); 15852 scheduleWritePackageRestrictionsLocked(sourceUserId); 15853 } 15854 } 15855 15856 @Override 15857 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 15858 mContext.enforceCallingOrSelfPermission( 15859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 15860 int callingUid = Binder.getCallingUid(); 15861 enforceOwnerRights(ownerPackage, callingUid); 15862 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 15863 synchronized (mPackages) { 15864 CrossProfileIntentResolver resolver = 15865 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 15866 ArraySet<CrossProfileIntentFilter> set = 15867 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 15868 for (CrossProfileIntentFilter filter : set) { 15869 if (filter.getOwnerPackage().equals(ownerPackage)) { 15870 resolver.removeFilter(filter); 15871 } 15872 } 15873 scheduleWritePackageRestrictionsLocked(sourceUserId); 15874 } 15875 } 15876 15877 // Enforcing that callingUid is owning pkg on userId 15878 private void enforceOwnerRights(String pkg, int callingUid) { 15879 // The system owns everything. 15880 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 15881 return; 15882 } 15883 int callingUserId = UserHandle.getUserId(callingUid); 15884 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 15885 if (pi == null) { 15886 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 15887 + callingUserId); 15888 } 15889 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 15890 throw new SecurityException("Calling uid " + callingUid 15891 + " does not own package " + pkg); 15892 } 15893 } 15894 15895 @Override 15896 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 15897 Intent intent = new Intent(Intent.ACTION_MAIN); 15898 intent.addCategory(Intent.CATEGORY_HOME); 15899 15900 final int callingUserId = UserHandle.getCallingUserId(); 15901 List<ResolveInfo> list = queryIntentActivities(intent, null, 15902 PackageManager.GET_META_DATA, callingUserId); 15903 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 15904 true, false, false, callingUserId); 15905 15906 allHomeCandidates.clear(); 15907 if (list != null) { 15908 for (ResolveInfo ri : list) { 15909 allHomeCandidates.add(ri); 15910 } 15911 } 15912 return (preferred == null || preferred.activityInfo == null) 15913 ? null 15914 : new ComponentName(preferred.activityInfo.packageName, 15915 preferred.activityInfo.name); 15916 } 15917 15918 @Override 15919 public void setApplicationEnabledSetting(String appPackageName, 15920 int newState, int flags, int userId, String callingPackage) { 15921 if (!sUserManager.exists(userId)) return; 15922 if (callingPackage == null) { 15923 callingPackage = Integer.toString(Binder.getCallingUid()); 15924 } 15925 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 15926 } 15927 15928 @Override 15929 public void setComponentEnabledSetting(ComponentName componentName, 15930 int newState, int flags, int userId) { 15931 if (!sUserManager.exists(userId)) return; 15932 setEnabledSetting(componentName.getPackageName(), 15933 componentName.getClassName(), newState, flags, userId, null); 15934 } 15935 15936 private void setEnabledSetting(final String packageName, String className, int newState, 15937 final int flags, int userId, String callingPackage) { 15938 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 15939 || newState == COMPONENT_ENABLED_STATE_ENABLED 15940 || newState == COMPONENT_ENABLED_STATE_DISABLED 15941 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 15942 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 15943 throw new IllegalArgumentException("Invalid new component state: " 15944 + newState); 15945 } 15946 PackageSetting pkgSetting; 15947 final int uid = Binder.getCallingUid(); 15948 final int permission = mContext.checkCallingOrSelfPermission( 15949 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 15950 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 15951 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 15952 boolean sendNow = false; 15953 boolean isApp = (className == null); 15954 String componentName = isApp ? packageName : className; 15955 int packageUid = -1; 15956 ArrayList<String> components; 15957 15958 // writer 15959 synchronized (mPackages) { 15960 pkgSetting = mSettings.mPackages.get(packageName); 15961 if (pkgSetting == null) { 15962 if (className == null) { 15963 throw new IllegalArgumentException("Unknown package: " + packageName); 15964 } 15965 throw new IllegalArgumentException( 15966 "Unknown component: " + packageName + "/" + className); 15967 } 15968 // Allow root and verify that userId is not being specified by a different user 15969 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 15970 throw new SecurityException( 15971 "Permission Denial: attempt to change component state from pid=" 15972 + Binder.getCallingPid() 15973 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 15974 } 15975 if (className == null) { 15976 // We're dealing with an application/package level state change 15977 if (pkgSetting.getEnabled(userId) == newState) { 15978 // Nothing to do 15979 return; 15980 } 15981 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 15982 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 15983 // Don't care about who enables an app. 15984 callingPackage = null; 15985 } 15986 pkgSetting.setEnabled(newState, userId, callingPackage); 15987 // pkgSetting.pkg.mSetEnabled = newState; 15988 } else { 15989 // We're dealing with a component level state change 15990 // First, verify that this is a valid class name. 15991 PackageParser.Package pkg = pkgSetting.pkg; 15992 if (pkg == null || !pkg.hasComponentClassName(className)) { 15993 if (pkg != null && 15994 pkg.applicationInfo.targetSdkVersion >= 15995 Build.VERSION_CODES.JELLY_BEAN) { 15996 throw new IllegalArgumentException("Component class " + className 15997 + " does not exist in " + packageName); 15998 } else { 15999 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16000 + className + " does not exist in " + packageName); 16001 } 16002 } 16003 switch (newState) { 16004 case COMPONENT_ENABLED_STATE_ENABLED: 16005 if (!pkgSetting.enableComponentLPw(className, userId)) { 16006 return; 16007 } 16008 break; 16009 case COMPONENT_ENABLED_STATE_DISABLED: 16010 if (!pkgSetting.disableComponentLPw(className, userId)) { 16011 return; 16012 } 16013 break; 16014 case COMPONENT_ENABLED_STATE_DEFAULT: 16015 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16016 return; 16017 } 16018 break; 16019 default: 16020 Slog.e(TAG, "Invalid new component state: " + newState); 16021 return; 16022 } 16023 } 16024 scheduleWritePackageRestrictionsLocked(userId); 16025 components = mPendingBroadcasts.get(userId, packageName); 16026 final boolean newPackage = components == null; 16027 if (newPackage) { 16028 components = new ArrayList<String>(); 16029 } 16030 if (!components.contains(componentName)) { 16031 components.add(componentName); 16032 } 16033 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16034 sendNow = true; 16035 // Purge entry from pending broadcast list if another one exists already 16036 // since we are sending one right away. 16037 mPendingBroadcasts.remove(userId, packageName); 16038 } else { 16039 if (newPackage) { 16040 mPendingBroadcasts.put(userId, packageName, components); 16041 } 16042 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16043 // Schedule a message 16044 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16045 } 16046 } 16047 } 16048 16049 long callingId = Binder.clearCallingIdentity(); 16050 try { 16051 if (sendNow) { 16052 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16053 sendPackageChangedBroadcast(packageName, 16054 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16055 } 16056 } finally { 16057 Binder.restoreCallingIdentity(callingId); 16058 } 16059 } 16060 16061 private void sendPackageChangedBroadcast(String packageName, 16062 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16063 if (DEBUG_INSTALL) 16064 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16065 + componentNames); 16066 Bundle extras = new Bundle(4); 16067 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16068 String nameList[] = new String[componentNames.size()]; 16069 componentNames.toArray(nameList); 16070 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16071 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16072 extras.putInt(Intent.EXTRA_UID, packageUid); 16073 // If this is not reporting a change of the overall package, then only send it 16074 // to registered receivers. We don't want to launch a swath of apps for every 16075 // little component state change. 16076 final int flags = !componentNames.contains(packageName) 16077 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16078 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16079 new int[] {UserHandle.getUserId(packageUid)}); 16080 } 16081 16082 @Override 16083 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16084 if (!sUserManager.exists(userId)) return; 16085 final int uid = Binder.getCallingUid(); 16086 final int permission = mContext.checkCallingOrSelfPermission( 16087 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16088 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16089 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 16090 // writer 16091 synchronized (mPackages) { 16092 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16093 allowedByPermission, uid, userId)) { 16094 scheduleWritePackageRestrictionsLocked(userId); 16095 } 16096 } 16097 } 16098 16099 @Override 16100 public String getInstallerPackageName(String packageName) { 16101 // reader 16102 synchronized (mPackages) { 16103 return mSettings.getInstallerPackageNameLPr(packageName); 16104 } 16105 } 16106 16107 @Override 16108 public int getApplicationEnabledSetting(String packageName, int userId) { 16109 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16110 int uid = Binder.getCallingUid(); 16111 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 16112 // reader 16113 synchronized (mPackages) { 16114 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16115 } 16116 } 16117 16118 @Override 16119 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16120 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16121 int uid = Binder.getCallingUid(); 16122 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 16123 // reader 16124 synchronized (mPackages) { 16125 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16126 } 16127 } 16128 16129 @Override 16130 public void enterSafeMode() { 16131 enforceSystemOrRoot("Only the system can request entering safe mode"); 16132 16133 if (!mSystemReady) { 16134 mSafeMode = true; 16135 } 16136 } 16137 16138 @Override 16139 public void systemReady() { 16140 mSystemReady = true; 16141 16142 // Read the compatibilty setting when the system is ready. 16143 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16144 mContext.getContentResolver(), 16145 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16146 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16147 if (DEBUG_SETTINGS) { 16148 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16149 } 16150 16151 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16152 16153 synchronized (mPackages) { 16154 // Verify that all of the preferred activity components actually 16155 // exist. It is possible for applications to be updated and at 16156 // that point remove a previously declared activity component that 16157 // had been set as a preferred activity. We try to clean this up 16158 // the next time we encounter that preferred activity, but it is 16159 // possible for the user flow to never be able to return to that 16160 // situation so here we do a sanity check to make sure we haven't 16161 // left any junk around. 16162 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16163 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16164 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16165 removed.clear(); 16166 for (PreferredActivity pa : pir.filterSet()) { 16167 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16168 removed.add(pa); 16169 } 16170 } 16171 if (removed.size() > 0) { 16172 for (int r=0; r<removed.size(); r++) { 16173 PreferredActivity pa = removed.get(r); 16174 Slog.w(TAG, "Removing dangling preferred activity: " 16175 + pa.mPref.mComponent); 16176 pir.removeFilter(pa); 16177 } 16178 mSettings.writePackageRestrictionsLPr( 16179 mSettings.mPreferredActivities.keyAt(i)); 16180 } 16181 } 16182 16183 for (int userId : UserManagerService.getInstance().getUserIds()) { 16184 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16185 grantPermissionsUserIds = ArrayUtils.appendInt( 16186 grantPermissionsUserIds, userId); 16187 } 16188 } 16189 } 16190 sUserManager.systemReady(); 16191 16192 // If we upgraded grant all default permissions before kicking off. 16193 for (int userId : grantPermissionsUserIds) { 16194 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16195 } 16196 16197 // Kick off any messages waiting for system ready 16198 if (mPostSystemReadyMessages != null) { 16199 for (Message msg : mPostSystemReadyMessages) { 16200 msg.sendToTarget(); 16201 } 16202 mPostSystemReadyMessages = null; 16203 } 16204 16205 // Watch for external volumes that come and go over time 16206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16207 storage.registerListener(mStorageListener); 16208 16209 mInstallerService.systemReady(); 16210 mPackageDexOptimizer.systemReady(); 16211 16212 MountServiceInternal mountServiceInternal = LocalServices.getService( 16213 MountServiceInternal.class); 16214 mountServiceInternal.addExternalStoragePolicy( 16215 new MountServiceInternal.ExternalStorageMountPolicy() { 16216 @Override 16217 public int getMountMode(int uid, String packageName) { 16218 if (Process.isIsolated(uid)) { 16219 return Zygote.MOUNT_EXTERNAL_NONE; 16220 } 16221 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16222 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16223 } 16224 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16225 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16226 } 16227 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16228 return Zygote.MOUNT_EXTERNAL_READ; 16229 } 16230 return Zygote.MOUNT_EXTERNAL_WRITE; 16231 } 16232 16233 @Override 16234 public boolean hasExternalStorage(int uid, String packageName) { 16235 return true; 16236 } 16237 }); 16238 } 16239 16240 @Override 16241 public boolean isSafeMode() { 16242 return mSafeMode; 16243 } 16244 16245 @Override 16246 public boolean hasSystemUidErrors() { 16247 return mHasSystemUidErrors; 16248 } 16249 16250 static String arrayToString(int[] array) { 16251 StringBuffer buf = new StringBuffer(128); 16252 buf.append('['); 16253 if (array != null) { 16254 for (int i=0; i<array.length; i++) { 16255 if (i > 0) buf.append(", "); 16256 buf.append(array[i]); 16257 } 16258 } 16259 buf.append(']'); 16260 return buf.toString(); 16261 } 16262 16263 static class DumpState { 16264 public static final int DUMP_LIBS = 1 << 0; 16265 public static final int DUMP_FEATURES = 1 << 1; 16266 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16267 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16268 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16269 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16270 public static final int DUMP_PERMISSIONS = 1 << 6; 16271 public static final int DUMP_PACKAGES = 1 << 7; 16272 public static final int DUMP_SHARED_USERS = 1 << 8; 16273 public static final int DUMP_MESSAGES = 1 << 9; 16274 public static final int DUMP_PROVIDERS = 1 << 10; 16275 public static final int DUMP_VERIFIERS = 1 << 11; 16276 public static final int DUMP_PREFERRED = 1 << 12; 16277 public static final int DUMP_PREFERRED_XML = 1 << 13; 16278 public static final int DUMP_KEYSETS = 1 << 14; 16279 public static final int DUMP_VERSION = 1 << 15; 16280 public static final int DUMP_INSTALLS = 1 << 16; 16281 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16282 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16283 16284 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16285 16286 private int mTypes; 16287 16288 private int mOptions; 16289 16290 private boolean mTitlePrinted; 16291 16292 private SharedUserSetting mSharedUser; 16293 16294 public boolean isDumping(int type) { 16295 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16296 return true; 16297 } 16298 16299 return (mTypes & type) != 0; 16300 } 16301 16302 public void setDump(int type) { 16303 mTypes |= type; 16304 } 16305 16306 public boolean isOptionEnabled(int option) { 16307 return (mOptions & option) != 0; 16308 } 16309 16310 public void setOptionEnabled(int option) { 16311 mOptions |= option; 16312 } 16313 16314 public boolean onTitlePrinted() { 16315 final boolean printed = mTitlePrinted; 16316 mTitlePrinted = true; 16317 return printed; 16318 } 16319 16320 public boolean getTitlePrinted() { 16321 return mTitlePrinted; 16322 } 16323 16324 public void setTitlePrinted(boolean enabled) { 16325 mTitlePrinted = enabled; 16326 } 16327 16328 public SharedUserSetting getSharedUser() { 16329 return mSharedUser; 16330 } 16331 16332 public void setSharedUser(SharedUserSetting user) { 16333 mSharedUser = user; 16334 } 16335 } 16336 16337 @Override 16338 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16339 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16340 (new PackageManagerShellCommand(this)).exec( 16341 this, in, out, err, args, resultReceiver); 16342 } 16343 16344 @Override 16345 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16346 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16347 != PackageManager.PERMISSION_GRANTED) { 16348 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16349 + Binder.getCallingPid() 16350 + ", uid=" + Binder.getCallingUid() 16351 + " without permission " 16352 + android.Manifest.permission.DUMP); 16353 return; 16354 } 16355 16356 DumpState dumpState = new DumpState(); 16357 boolean fullPreferred = false; 16358 boolean checkin = false; 16359 16360 String packageName = null; 16361 ArraySet<String> permissionNames = null; 16362 16363 int opti = 0; 16364 while (opti < args.length) { 16365 String opt = args[opti]; 16366 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16367 break; 16368 } 16369 opti++; 16370 16371 if ("-a".equals(opt)) { 16372 // Right now we only know how to print all. 16373 } else if ("-h".equals(opt)) { 16374 pw.println("Package manager dump options:"); 16375 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16376 pw.println(" --checkin: dump for a checkin"); 16377 pw.println(" -f: print details of intent filters"); 16378 pw.println(" -h: print this help"); 16379 pw.println(" cmd may be one of:"); 16380 pw.println(" l[ibraries]: list known shared libraries"); 16381 pw.println(" f[eatures]: list device features"); 16382 pw.println(" k[eysets]: print known keysets"); 16383 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16384 pw.println(" perm[issions]: dump permissions"); 16385 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16386 pw.println(" pref[erred]: print preferred package settings"); 16387 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16388 pw.println(" prov[iders]: dump content providers"); 16389 pw.println(" p[ackages]: dump installed packages"); 16390 pw.println(" s[hared-users]: dump shared user IDs"); 16391 pw.println(" m[essages]: print collected runtime messages"); 16392 pw.println(" v[erifiers]: print package verifier info"); 16393 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16394 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16395 pw.println(" version: print database version info"); 16396 pw.println(" write: write current settings now"); 16397 pw.println(" installs: details about install sessions"); 16398 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16399 pw.println(" <package.name>: info about given package"); 16400 return; 16401 } else if ("--checkin".equals(opt)) { 16402 checkin = true; 16403 } else if ("-f".equals(opt)) { 16404 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16405 } else { 16406 pw.println("Unknown argument: " + opt + "; use -h for help"); 16407 } 16408 } 16409 16410 // Is the caller requesting to dump a particular piece of data? 16411 if (opti < args.length) { 16412 String cmd = args[opti]; 16413 opti++; 16414 // Is this a package name? 16415 if ("android".equals(cmd) || cmd.contains(".")) { 16416 packageName = cmd; 16417 // When dumping a single package, we always dump all of its 16418 // filter information since the amount of data will be reasonable. 16419 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16420 } else if ("check-permission".equals(cmd)) { 16421 if (opti >= args.length) { 16422 pw.println("Error: check-permission missing permission argument"); 16423 return; 16424 } 16425 String perm = args[opti]; 16426 opti++; 16427 if (opti >= args.length) { 16428 pw.println("Error: check-permission missing package argument"); 16429 return; 16430 } 16431 String pkg = args[opti]; 16432 opti++; 16433 int user = UserHandle.getUserId(Binder.getCallingUid()); 16434 if (opti < args.length) { 16435 try { 16436 user = Integer.parseInt(args[opti]); 16437 } catch (NumberFormatException e) { 16438 pw.println("Error: check-permission user argument is not a number: " 16439 + args[opti]); 16440 return; 16441 } 16442 } 16443 pw.println(checkPermission(perm, pkg, user)); 16444 return; 16445 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16446 dumpState.setDump(DumpState.DUMP_LIBS); 16447 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16448 dumpState.setDump(DumpState.DUMP_FEATURES); 16449 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16450 if (opti >= args.length) { 16451 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16452 | DumpState.DUMP_SERVICE_RESOLVERS 16453 | DumpState.DUMP_RECEIVER_RESOLVERS 16454 | DumpState.DUMP_CONTENT_RESOLVERS); 16455 } else { 16456 while (opti < args.length) { 16457 String name = args[opti]; 16458 if ("a".equals(name) || "activity".equals(name)) { 16459 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16460 } else if ("s".equals(name) || "service".equals(name)) { 16461 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16462 } else if ("r".equals(name) || "receiver".equals(name)) { 16463 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16464 } else if ("c".equals(name) || "content".equals(name)) { 16465 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16466 } else { 16467 pw.println("Error: unknown resolver table type: " + name); 16468 return; 16469 } 16470 opti++; 16471 } 16472 } 16473 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16474 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16475 } else if ("permission".equals(cmd)) { 16476 if (opti >= args.length) { 16477 pw.println("Error: permission requires permission name"); 16478 return; 16479 } 16480 permissionNames = new ArraySet<>(); 16481 while (opti < args.length) { 16482 permissionNames.add(args[opti]); 16483 opti++; 16484 } 16485 dumpState.setDump(DumpState.DUMP_PERMISSIONS 16486 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 16487 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 16488 dumpState.setDump(DumpState.DUMP_PREFERRED); 16489 } else if ("preferred-xml".equals(cmd)) { 16490 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 16491 if (opti < args.length && "--full".equals(args[opti])) { 16492 fullPreferred = true; 16493 opti++; 16494 } 16495 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 16496 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 16497 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 16498 dumpState.setDump(DumpState.DUMP_PACKAGES); 16499 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 16500 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 16501 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 16502 dumpState.setDump(DumpState.DUMP_PROVIDERS); 16503 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 16504 dumpState.setDump(DumpState.DUMP_MESSAGES); 16505 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 16506 dumpState.setDump(DumpState.DUMP_VERIFIERS); 16507 } else if ("i".equals(cmd) || "ifv".equals(cmd) 16508 || "intent-filter-verifiers".equals(cmd)) { 16509 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 16510 } else if ("version".equals(cmd)) { 16511 dumpState.setDump(DumpState.DUMP_VERSION); 16512 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 16513 dumpState.setDump(DumpState.DUMP_KEYSETS); 16514 } else if ("installs".equals(cmd)) { 16515 dumpState.setDump(DumpState.DUMP_INSTALLS); 16516 } else if ("write".equals(cmd)) { 16517 synchronized (mPackages) { 16518 mSettings.writeLPr(); 16519 pw.println("Settings written."); 16520 return; 16521 } 16522 } 16523 } 16524 16525 if (checkin) { 16526 pw.println("vers,1"); 16527 } 16528 16529 // reader 16530 synchronized (mPackages) { 16531 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 16532 if (!checkin) { 16533 if (dumpState.onTitlePrinted()) 16534 pw.println(); 16535 pw.println("Database versions:"); 16536 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 16537 } 16538 } 16539 16540 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 16541 if (!checkin) { 16542 if (dumpState.onTitlePrinted()) 16543 pw.println(); 16544 pw.println("Verifiers:"); 16545 pw.print(" Required: "); 16546 pw.print(mRequiredVerifierPackage); 16547 pw.print(" (uid="); 16548 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16549 UserHandle.USER_SYSTEM)); 16550 pw.println(")"); 16551 } else if (mRequiredVerifierPackage != null) { 16552 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 16553 pw.print(","); 16554 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 16555 UserHandle.USER_SYSTEM)); 16556 } 16557 } 16558 16559 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 16560 packageName == null) { 16561 if (mIntentFilterVerifierComponent != null) { 16562 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 16563 if (!checkin) { 16564 if (dumpState.onTitlePrinted()) 16565 pw.println(); 16566 pw.println("Intent Filter Verifier:"); 16567 pw.print(" Using: "); 16568 pw.print(verifierPackageName); 16569 pw.print(" (uid="); 16570 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16571 UserHandle.USER_SYSTEM)); 16572 pw.println(")"); 16573 } else if (verifierPackageName != null) { 16574 pw.print("ifv,"); pw.print(verifierPackageName); 16575 pw.print(","); 16576 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 16577 UserHandle.USER_SYSTEM)); 16578 } 16579 } else { 16580 pw.println(); 16581 pw.println("No Intent Filter Verifier available!"); 16582 } 16583 } 16584 16585 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 16586 boolean printedHeader = false; 16587 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 16588 while (it.hasNext()) { 16589 String name = it.next(); 16590 SharedLibraryEntry ent = mSharedLibraries.get(name); 16591 if (!checkin) { 16592 if (!printedHeader) { 16593 if (dumpState.onTitlePrinted()) 16594 pw.println(); 16595 pw.println("Libraries:"); 16596 printedHeader = true; 16597 } 16598 pw.print(" "); 16599 } else { 16600 pw.print("lib,"); 16601 } 16602 pw.print(name); 16603 if (!checkin) { 16604 pw.print(" -> "); 16605 } 16606 if (ent.path != null) { 16607 if (!checkin) { 16608 pw.print("(jar) "); 16609 pw.print(ent.path); 16610 } else { 16611 pw.print(",jar,"); 16612 pw.print(ent.path); 16613 } 16614 } else { 16615 if (!checkin) { 16616 pw.print("(apk) "); 16617 pw.print(ent.apk); 16618 } else { 16619 pw.print(",apk,"); 16620 pw.print(ent.apk); 16621 } 16622 } 16623 pw.println(); 16624 } 16625 } 16626 16627 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 16628 if (dumpState.onTitlePrinted()) 16629 pw.println(); 16630 if (!checkin) { 16631 pw.println("Features:"); 16632 } 16633 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 16634 while (it.hasNext()) { 16635 String name = it.next(); 16636 if (!checkin) { 16637 pw.print(" "); 16638 } else { 16639 pw.print("feat,"); 16640 } 16641 pw.println(name); 16642 } 16643 } 16644 16645 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 16646 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 16647 : "Activity Resolver Table:", " ", packageName, 16648 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16649 dumpState.setTitlePrinted(true); 16650 } 16651 } 16652 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 16653 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 16654 : "Receiver Resolver Table:", " ", packageName, 16655 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16656 dumpState.setTitlePrinted(true); 16657 } 16658 } 16659 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 16660 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 16661 : "Service Resolver Table:", " ", packageName, 16662 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16663 dumpState.setTitlePrinted(true); 16664 } 16665 } 16666 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 16667 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 16668 : "Provider Resolver Table:", " ", packageName, 16669 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 16670 dumpState.setTitlePrinted(true); 16671 } 16672 } 16673 16674 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 16675 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16676 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16677 int user = mSettings.mPreferredActivities.keyAt(i); 16678 if (pir.dump(pw, 16679 dumpState.getTitlePrinted() 16680 ? "\nPreferred Activities User " + user + ":" 16681 : "Preferred Activities User " + user + ":", " ", 16682 packageName, true, false)) { 16683 dumpState.setTitlePrinted(true); 16684 } 16685 } 16686 } 16687 16688 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 16689 pw.flush(); 16690 FileOutputStream fout = new FileOutputStream(fd); 16691 BufferedOutputStream str = new BufferedOutputStream(fout); 16692 XmlSerializer serializer = new FastXmlSerializer(); 16693 try { 16694 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 16695 serializer.startDocument(null, true); 16696 serializer.setFeature( 16697 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 16698 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 16699 serializer.endDocument(); 16700 serializer.flush(); 16701 } catch (IllegalArgumentException e) { 16702 pw.println("Failed writing: " + e); 16703 } catch (IllegalStateException e) { 16704 pw.println("Failed writing: " + e); 16705 } catch (IOException e) { 16706 pw.println("Failed writing: " + e); 16707 } 16708 } 16709 16710 if (!checkin 16711 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 16712 && packageName == null) { 16713 pw.println(); 16714 int count = mSettings.mPackages.size(); 16715 if (count == 0) { 16716 pw.println("No applications!"); 16717 pw.println(); 16718 } else { 16719 final String prefix = " "; 16720 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 16721 if (allPackageSettings.size() == 0) { 16722 pw.println("No domain preferred apps!"); 16723 pw.println(); 16724 } else { 16725 pw.println("App verification status:"); 16726 pw.println(); 16727 count = 0; 16728 for (PackageSetting ps : allPackageSettings) { 16729 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 16730 if (ivi == null || ivi.getPackageName() == null) continue; 16731 pw.println(prefix + "Package: " + ivi.getPackageName()); 16732 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 16733 pw.println(prefix + "Status: " + ivi.getStatusString()); 16734 pw.println(); 16735 count++; 16736 } 16737 if (count == 0) { 16738 pw.println(prefix + "No app verification established."); 16739 pw.println(); 16740 } 16741 for (int userId : sUserManager.getUserIds()) { 16742 pw.println("App linkages for user " + userId + ":"); 16743 pw.println(); 16744 count = 0; 16745 for (PackageSetting ps : allPackageSettings) { 16746 final long status = ps.getDomainVerificationStatusForUser(userId); 16747 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 16748 continue; 16749 } 16750 pw.println(prefix + "Package: " + ps.name); 16751 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 16752 String statusStr = IntentFilterVerificationInfo. 16753 getStatusStringFromValue(status); 16754 pw.println(prefix + "Status: " + statusStr); 16755 pw.println(); 16756 count++; 16757 } 16758 if (count == 0) { 16759 pw.println(prefix + "No configured app linkages."); 16760 pw.println(); 16761 } 16762 } 16763 } 16764 } 16765 } 16766 16767 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 16768 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 16769 if (packageName == null && permissionNames == null) { 16770 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 16771 if (iperm == 0) { 16772 if (dumpState.onTitlePrinted()) 16773 pw.println(); 16774 pw.println("AppOp Permissions:"); 16775 } 16776 pw.print(" AppOp Permission "); 16777 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 16778 pw.println(":"); 16779 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 16780 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 16781 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 16782 } 16783 } 16784 } 16785 } 16786 16787 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 16788 boolean printedSomething = false; 16789 for (PackageParser.Provider p : mProviders.mProviders.values()) { 16790 if (packageName != null && !packageName.equals(p.info.packageName)) { 16791 continue; 16792 } 16793 if (!printedSomething) { 16794 if (dumpState.onTitlePrinted()) 16795 pw.println(); 16796 pw.println("Registered ContentProviders:"); 16797 printedSomething = true; 16798 } 16799 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 16800 pw.print(" "); pw.println(p.toString()); 16801 } 16802 printedSomething = false; 16803 for (Map.Entry<String, PackageParser.Provider> entry : 16804 mProvidersByAuthority.entrySet()) { 16805 PackageParser.Provider p = entry.getValue(); 16806 if (packageName != null && !packageName.equals(p.info.packageName)) { 16807 continue; 16808 } 16809 if (!printedSomething) { 16810 if (dumpState.onTitlePrinted()) 16811 pw.println(); 16812 pw.println("ContentProvider Authorities:"); 16813 printedSomething = true; 16814 } 16815 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 16816 pw.print(" "); pw.println(p.toString()); 16817 if (p.info != null && p.info.applicationInfo != null) { 16818 final String appInfo = p.info.applicationInfo.toString(); 16819 pw.print(" applicationInfo="); pw.println(appInfo); 16820 } 16821 } 16822 } 16823 16824 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 16825 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 16826 } 16827 16828 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 16829 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 16830 } 16831 16832 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 16833 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 16834 } 16835 16836 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 16837 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 16838 } 16839 16840 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 16841 // XXX should handle packageName != null by dumping only install data that 16842 // the given package is involved with. 16843 if (dumpState.onTitlePrinted()) pw.println(); 16844 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 16845 } 16846 16847 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 16848 if (dumpState.onTitlePrinted()) pw.println(); 16849 mSettings.dumpReadMessagesLPr(pw, dumpState); 16850 16851 pw.println(); 16852 pw.println("Package warning messages:"); 16853 BufferedReader in = null; 16854 String line = null; 16855 try { 16856 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16857 while ((line = in.readLine()) != null) { 16858 if (line.contains("ignored: updated version")) continue; 16859 pw.println(line); 16860 } 16861 } catch (IOException ignored) { 16862 } finally { 16863 IoUtils.closeQuietly(in); 16864 } 16865 } 16866 16867 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 16868 BufferedReader in = null; 16869 String line = null; 16870 try { 16871 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 16872 while ((line = in.readLine()) != null) { 16873 if (line.contains("ignored: updated version")) continue; 16874 pw.print("msg,"); 16875 pw.println(line); 16876 } 16877 } catch (IOException ignored) { 16878 } finally { 16879 IoUtils.closeQuietly(in); 16880 } 16881 } 16882 } 16883 } 16884 16885 private String dumpDomainString(String packageName) { 16886 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName); 16887 List<IntentFilter> filters = getAllIntentFilters(packageName); 16888 16889 ArraySet<String> result = new ArraySet<>(); 16890 if (iviList.size() > 0) { 16891 for (IntentFilterVerificationInfo ivi : iviList) { 16892 for (String host : ivi.getDomains()) { 16893 result.add(host); 16894 } 16895 } 16896 } 16897 if (filters != null && filters.size() > 0) { 16898 for (IntentFilter filter : filters) { 16899 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 16900 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 16901 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 16902 result.addAll(filter.getHostsList()); 16903 } 16904 } 16905 } 16906 16907 StringBuilder sb = new StringBuilder(result.size() * 16); 16908 for (String domain : result) { 16909 if (sb.length() > 0) sb.append(" "); 16910 sb.append(domain); 16911 } 16912 return sb.toString(); 16913 } 16914 16915 // ------- apps on sdcard specific code ------- 16916 static final boolean DEBUG_SD_INSTALL = false; 16917 16918 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 16919 16920 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 16921 16922 private boolean mMediaMounted = false; 16923 16924 static String getEncryptKey() { 16925 try { 16926 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 16927 SD_ENCRYPTION_KEYSTORE_NAME); 16928 if (sdEncKey == null) { 16929 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 16930 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 16931 if (sdEncKey == null) { 16932 Slog.e(TAG, "Failed to create encryption keys"); 16933 return null; 16934 } 16935 } 16936 return sdEncKey; 16937 } catch (NoSuchAlgorithmException nsae) { 16938 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 16939 return null; 16940 } catch (IOException ioe) { 16941 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 16942 return null; 16943 } 16944 } 16945 16946 /* 16947 * Update media status on PackageManager. 16948 */ 16949 @Override 16950 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 16951 int callingUid = Binder.getCallingUid(); 16952 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 16953 throw new SecurityException("Media status can only be updated by the system"); 16954 } 16955 // reader; this apparently protects mMediaMounted, but should probably 16956 // be a different lock in that case. 16957 synchronized (mPackages) { 16958 Log.i(TAG, "Updating external media status from " 16959 + (mMediaMounted ? "mounted" : "unmounted") + " to " 16960 + (mediaStatus ? "mounted" : "unmounted")); 16961 if (DEBUG_SD_INSTALL) 16962 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 16963 + ", mMediaMounted=" + mMediaMounted); 16964 if (mediaStatus == mMediaMounted) { 16965 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 16966 : 0, -1); 16967 mHandler.sendMessage(msg); 16968 return; 16969 } 16970 mMediaMounted = mediaStatus; 16971 } 16972 // Queue up an async operation since the package installation may take a 16973 // little while. 16974 mHandler.post(new Runnable() { 16975 public void run() { 16976 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 16977 } 16978 }); 16979 } 16980 16981 /** 16982 * Called by MountService when the initial ASECs to scan are available. 16983 * Should block until all the ASEC containers are finished being scanned. 16984 */ 16985 public void scanAvailableAsecs() { 16986 updateExternalMediaStatusInner(true, false, false); 16987 } 16988 16989 /* 16990 * Collect information of applications on external media, map them against 16991 * existing containers and update information based on current mount status. 16992 * Please note that we always have to report status if reportStatus has been 16993 * set to true especially when unloading packages. 16994 */ 16995 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 16996 boolean externalStorage) { 16997 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 16998 int[] uidArr = EmptyArray.INT; 16999 17000 final String[] list = PackageHelper.getSecureContainerList(); 17001 if (ArrayUtils.isEmpty(list)) { 17002 Log.i(TAG, "No secure containers found"); 17003 } else { 17004 // Process list of secure containers and categorize them 17005 // as active or stale based on their package internal state. 17006 17007 // reader 17008 synchronized (mPackages) { 17009 for (String cid : list) { 17010 // Leave stages untouched for now; installer service owns them 17011 if (PackageInstallerService.isStageName(cid)) continue; 17012 17013 if (DEBUG_SD_INSTALL) 17014 Log.i(TAG, "Processing container " + cid); 17015 String pkgName = getAsecPackageName(cid); 17016 if (pkgName == null) { 17017 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17018 continue; 17019 } 17020 if (DEBUG_SD_INSTALL) 17021 Log.i(TAG, "Looking for pkg : " + pkgName); 17022 17023 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17024 if (ps == null) { 17025 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17026 continue; 17027 } 17028 17029 /* 17030 * Skip packages that are not external if we're unmounting 17031 * external storage. 17032 */ 17033 if (externalStorage && !isMounted && !isExternal(ps)) { 17034 continue; 17035 } 17036 17037 final AsecInstallArgs args = new AsecInstallArgs(cid, 17038 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17039 // The package status is changed only if the code path 17040 // matches between settings and the container id. 17041 if (ps.codePathString != null 17042 && ps.codePathString.startsWith(args.getCodePath())) { 17043 if (DEBUG_SD_INSTALL) { 17044 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17045 + " at code path: " + ps.codePathString); 17046 } 17047 17048 // We do have a valid package installed on sdcard 17049 processCids.put(args, ps.codePathString); 17050 final int uid = ps.appId; 17051 if (uid != -1) { 17052 uidArr = ArrayUtils.appendInt(uidArr, uid); 17053 } 17054 } else { 17055 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17056 + ps.codePathString); 17057 } 17058 } 17059 } 17060 17061 Arrays.sort(uidArr); 17062 } 17063 17064 // Process packages with valid entries. 17065 if (isMounted) { 17066 if (DEBUG_SD_INSTALL) 17067 Log.i(TAG, "Loading packages"); 17068 loadMediaPackages(processCids, uidArr, externalStorage); 17069 startCleaningPackages(); 17070 mInstallerService.onSecureContainersAvailable(); 17071 } else { 17072 if (DEBUG_SD_INSTALL) 17073 Log.i(TAG, "Unloading packages"); 17074 unloadMediaPackages(processCids, uidArr, reportStatus); 17075 } 17076 } 17077 17078 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17079 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17080 final int size = infos.size(); 17081 final String[] packageNames = new String[size]; 17082 final int[] packageUids = new int[size]; 17083 for (int i = 0; i < size; i++) { 17084 final ApplicationInfo info = infos.get(i); 17085 packageNames[i] = info.packageName; 17086 packageUids[i] = info.uid; 17087 } 17088 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17089 finishedReceiver); 17090 } 17091 17092 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17093 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17094 sendResourcesChangedBroadcast(mediaStatus, replacing, 17095 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17096 } 17097 17098 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17099 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17100 int size = pkgList.length; 17101 if (size > 0) { 17102 // Send broadcasts here 17103 Bundle extras = new Bundle(); 17104 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17105 if (uidArr != null) { 17106 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17107 } 17108 if (replacing) { 17109 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17110 } 17111 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17112 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17113 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17114 } 17115 } 17116 17117 /* 17118 * Look at potentially valid container ids from processCids If package 17119 * information doesn't match the one on record or package scanning fails, 17120 * the cid is added to list of removeCids. We currently don't delete stale 17121 * containers. 17122 */ 17123 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17124 boolean externalStorage) { 17125 ArrayList<String> pkgList = new ArrayList<String>(); 17126 Set<AsecInstallArgs> keys = processCids.keySet(); 17127 17128 for (AsecInstallArgs args : keys) { 17129 String codePath = processCids.get(args); 17130 if (DEBUG_SD_INSTALL) 17131 Log.i(TAG, "Loading container : " + args.cid); 17132 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17133 try { 17134 // Make sure there are no container errors first. 17135 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17136 Slog.e(TAG, "Failed to mount cid : " + args.cid 17137 + " when installing from sdcard"); 17138 continue; 17139 } 17140 // Check code path here. 17141 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17142 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17143 + " does not match one in settings " + codePath); 17144 continue; 17145 } 17146 // Parse package 17147 int parseFlags = mDefParseFlags; 17148 if (args.isExternalAsec()) { 17149 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17150 } 17151 if (args.isFwdLocked()) { 17152 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17153 } 17154 17155 synchronized (mInstallLock) { 17156 PackageParser.Package pkg = null; 17157 try { 17158 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17159 } catch (PackageManagerException e) { 17160 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17161 } 17162 // Scan the package 17163 if (pkg != null) { 17164 /* 17165 * TODO why is the lock being held? doPostInstall is 17166 * called in other places without the lock. This needs 17167 * to be straightened out. 17168 */ 17169 // writer 17170 synchronized (mPackages) { 17171 retCode = PackageManager.INSTALL_SUCCEEDED; 17172 pkgList.add(pkg.packageName); 17173 // Post process args 17174 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17175 pkg.applicationInfo.uid); 17176 } 17177 } else { 17178 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17179 } 17180 } 17181 17182 } finally { 17183 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17184 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17185 } 17186 } 17187 } 17188 // writer 17189 synchronized (mPackages) { 17190 // If the platform SDK has changed since the last time we booted, 17191 // we need to re-grant app permission to catch any new ones that 17192 // appear. This is really a hack, and means that apps can in some 17193 // cases get permissions that the user didn't initially explicitly 17194 // allow... it would be nice to have some better way to handle 17195 // this situation. 17196 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17197 : mSettings.getInternalVersion(); 17198 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17199 : StorageManager.UUID_PRIVATE_INTERNAL; 17200 17201 int updateFlags = UPDATE_PERMISSIONS_ALL; 17202 if (ver.sdkVersion != mSdkVersion) { 17203 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17204 + mSdkVersion + "; regranting permissions for external"); 17205 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17206 } 17207 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17208 17209 // Yay, everything is now upgraded 17210 ver.forceCurrent(); 17211 17212 // can downgrade to reader 17213 // Persist settings 17214 mSettings.writeLPr(); 17215 } 17216 // Send a broadcast to let everyone know we are done processing 17217 if (pkgList.size() > 0) { 17218 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17219 } 17220 } 17221 17222 /* 17223 * Utility method to unload a list of specified containers 17224 */ 17225 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17226 // Just unmount all valid containers. 17227 for (AsecInstallArgs arg : cidArgs) { 17228 synchronized (mInstallLock) { 17229 arg.doPostDeleteLI(false); 17230 } 17231 } 17232 } 17233 17234 /* 17235 * Unload packages mounted on external media. This involves deleting package 17236 * data from internal structures, sending broadcasts about disabled packages, 17237 * gc'ing to free up references, unmounting all secure containers 17238 * corresponding to packages on external media, and posting a 17239 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17240 * that we always have to post this message if status has been requested no 17241 * matter what. 17242 */ 17243 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17244 final boolean reportStatus) { 17245 if (DEBUG_SD_INSTALL) 17246 Log.i(TAG, "unloading media packages"); 17247 ArrayList<String> pkgList = new ArrayList<String>(); 17248 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17249 final Set<AsecInstallArgs> keys = processCids.keySet(); 17250 for (AsecInstallArgs args : keys) { 17251 String pkgName = args.getPackageName(); 17252 if (DEBUG_SD_INSTALL) 17253 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17254 // Delete package internally 17255 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17256 synchronized (mInstallLock) { 17257 boolean res = deletePackageLI(pkgName, null, false, null, null, 17258 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17259 if (res) { 17260 pkgList.add(pkgName); 17261 } else { 17262 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17263 failedList.add(args); 17264 } 17265 } 17266 } 17267 17268 // reader 17269 synchronized (mPackages) { 17270 // We didn't update the settings after removing each package; 17271 // write them now for all packages. 17272 mSettings.writeLPr(); 17273 } 17274 17275 // We have to absolutely send UPDATED_MEDIA_STATUS only 17276 // after confirming that all the receivers processed the ordered 17277 // broadcast when packages get disabled, force a gc to clean things up. 17278 // and unload all the containers. 17279 if (pkgList.size() > 0) { 17280 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17281 new IIntentReceiver.Stub() { 17282 public void performReceive(Intent intent, int resultCode, String data, 17283 Bundle extras, boolean ordered, boolean sticky, 17284 int sendingUser) throws RemoteException { 17285 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17286 reportStatus ? 1 : 0, 1, keys); 17287 mHandler.sendMessage(msg); 17288 } 17289 }); 17290 } else { 17291 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17292 keys); 17293 mHandler.sendMessage(msg); 17294 } 17295 } 17296 17297 private void loadPrivatePackages(final VolumeInfo vol) { 17298 mHandler.post(new Runnable() { 17299 @Override 17300 public void run() { 17301 loadPrivatePackagesInner(vol); 17302 } 17303 }); 17304 } 17305 17306 private void loadPrivatePackagesInner(VolumeInfo vol) { 17307 final String volumeUuid = vol.fsUuid; 17308 if (TextUtils.isEmpty(volumeUuid)) { 17309 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17310 return; 17311 } 17312 17313 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17314 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17315 17316 final VersionInfo ver; 17317 final List<PackageSetting> packages; 17318 synchronized (mPackages) { 17319 ver = mSettings.findOrCreateVersion(volumeUuid); 17320 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17321 } 17322 17323 // TODO: introduce a new concept similar to "frozen" to prevent these 17324 // apps from being launched until after data has been fully reconciled 17325 for (PackageSetting ps : packages) { 17326 synchronized (mInstallLock) { 17327 final PackageParser.Package pkg; 17328 try { 17329 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17330 loaded.add(pkg.applicationInfo); 17331 17332 } catch (PackageManagerException e) { 17333 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17334 } 17335 17336 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17337 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17338 } 17339 } 17340 } 17341 17342 // Reconcile app data for all started/unlocked users 17343 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17344 final UserManager um = mContext.getSystemService(UserManager.class); 17345 for (UserInfo user : um.getUsers()) { 17346 final int flags; 17347 if (um.isUserUnlocked(user.id)) { 17348 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17349 } else if (um.isUserRunning(user.id)) { 17350 flags = StorageManager.FLAG_STORAGE_DE; 17351 } else { 17352 continue; 17353 } 17354 17355 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17356 reconcileAppsData(volumeUuid, user.id, flags); 17357 } 17358 17359 synchronized (mPackages) { 17360 int updateFlags = UPDATE_PERMISSIONS_ALL; 17361 if (ver.sdkVersion != mSdkVersion) { 17362 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17363 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17364 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17365 } 17366 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17367 17368 // Yay, everything is now upgraded 17369 ver.forceCurrent(); 17370 17371 mSettings.writeLPr(); 17372 } 17373 17374 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17375 sendResourcesChangedBroadcast(true, false, loaded, null); 17376 } 17377 17378 private void unloadPrivatePackages(final VolumeInfo vol) { 17379 mHandler.post(new Runnable() { 17380 @Override 17381 public void run() { 17382 unloadPrivatePackagesInner(vol); 17383 } 17384 }); 17385 } 17386 17387 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17388 final String volumeUuid = vol.fsUuid; 17389 if (TextUtils.isEmpty(volumeUuid)) { 17390 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17391 return; 17392 } 17393 17394 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17395 synchronized (mInstallLock) { 17396 synchronized (mPackages) { 17397 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17398 for (PackageSetting ps : packages) { 17399 if (ps.pkg == null) continue; 17400 17401 final ApplicationInfo info = ps.pkg.applicationInfo; 17402 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17403 if (deletePackageLI(ps.name, null, false, null, null, 17404 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17405 unloaded.add(info); 17406 } else { 17407 Slog.w(TAG, "Failed to unload " + ps.codePath); 17408 } 17409 } 17410 17411 mSettings.writeLPr(); 17412 } 17413 } 17414 17415 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17416 sendResourcesChangedBroadcast(false, false, unloaded, null); 17417 } 17418 17419 /** 17420 * Examine all users present on given mounted volume, and destroy data 17421 * belonging to users that are no longer valid, or whose user ID has been 17422 * recycled. 17423 */ 17424 private void reconcileUsers(String volumeUuid) { 17425 final File[] files = FileUtils 17426 .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid)); 17427 for (File file : files) { 17428 if (!file.isDirectory()) continue; 17429 17430 final int userId; 17431 final UserInfo info; 17432 try { 17433 userId = Integer.parseInt(file.getName()); 17434 info = sUserManager.getUserInfo(userId); 17435 } catch (NumberFormatException e) { 17436 Slog.w(TAG, "Invalid user directory " + file); 17437 continue; 17438 } 17439 17440 boolean destroyUser = false; 17441 if (info == null) { 17442 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17443 + " because no matching user was found"); 17444 destroyUser = true; 17445 } else { 17446 try { 17447 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17448 } catch (IOException e) { 17449 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17450 + " because we failed to enforce serial number: " + e); 17451 destroyUser = true; 17452 } 17453 } 17454 17455 if (destroyUser) { 17456 synchronized (mInstallLock) { 17457 try { 17458 mInstaller.removeUserDataDirs(volumeUuid, userId); 17459 } catch (InstallerException e) { 17460 Slog.w(TAG, "Failed to clean up user dirs", e); 17461 } 17462 } 17463 } 17464 } 17465 } 17466 17467 private void assertPackageKnown(String volumeUuid, String packageName) 17468 throws PackageManagerException { 17469 synchronized (mPackages) { 17470 final PackageSetting ps = mSettings.mPackages.get(packageName); 17471 if (ps == null) { 17472 throw new PackageManagerException("Package " + packageName + " is unknown"); 17473 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17474 throw new PackageManagerException( 17475 "Package " + packageName + " found on unknown volume " + volumeUuid 17476 + "; expected volume " + ps.volumeUuid); 17477 } 17478 } 17479 } 17480 17481 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 17482 throws PackageManagerException { 17483 synchronized (mPackages) { 17484 final PackageSetting ps = mSettings.mPackages.get(packageName); 17485 if (ps == null) { 17486 throw new PackageManagerException("Package " + packageName + " is unknown"); 17487 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 17488 throw new PackageManagerException( 17489 "Package " + packageName + " found on unknown volume " + volumeUuid 17490 + "; expected volume " + ps.volumeUuid); 17491 } else if (!ps.getInstalled(userId)) { 17492 throw new PackageManagerException( 17493 "Package " + packageName + " not installed for user " + userId); 17494 } 17495 } 17496 } 17497 17498 /** 17499 * Examine all apps present on given mounted volume, and destroy apps that 17500 * aren't expected, either due to uninstallation or reinstallation on 17501 * another volume. 17502 */ 17503 private void reconcileApps(String volumeUuid) { 17504 final File[] files = FileUtils 17505 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 17506 for (File file : files) { 17507 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 17508 && !PackageInstallerService.isStageName(file.getName()); 17509 if (!isPackage) { 17510 // Ignore entries which are not packages 17511 continue; 17512 } 17513 17514 try { 17515 final PackageLite pkg = PackageParser.parsePackageLite(file, 17516 PackageParser.PARSE_MUST_BE_APK); 17517 assertPackageKnown(volumeUuid, pkg.packageName); 17518 17519 } catch (PackageParserException | PackageManagerException e) { 17520 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17521 synchronized (mInstallLock) { 17522 removeCodePathLI(file); 17523 } 17524 } 17525 } 17526 } 17527 17528 /** 17529 * Reconcile all app data for the given user. 17530 * <p> 17531 * Verifies that directories exist and that ownership and labeling is 17532 * correct for all installed apps on all mounted volumes. 17533 */ 17534 void reconcileAppsData(int userId, int flags) { 17535 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17536 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 17537 final String volumeUuid = vol.getFsUuid(); 17538 reconcileAppsData(volumeUuid, userId, flags); 17539 } 17540 } 17541 17542 /** 17543 * Reconcile all app data on given mounted volume. 17544 * <p> 17545 * Destroys app data that isn't expected, either due to uninstallation or 17546 * reinstallation on another volume. 17547 * <p> 17548 * Verifies that directories exist and that ownership and labeling is 17549 * correct for all installed apps. 17550 */ 17551 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 17552 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 17553 + Integer.toHexString(flags)); 17554 17555 final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId); 17556 final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId); 17557 17558 boolean restoreconNeeded = false; 17559 17560 // First look for stale data that doesn't belong, and check if things 17561 // have changed since we did our last restorecon 17562 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17563 if (!isUserKeyUnlocked(userId)) { 17564 throw new RuntimeException( 17565 "Yikes, someone asked us to reconcile CE storage while " + userId 17566 + " was still locked; this would have caused massive data loss!"); 17567 } 17568 17569 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 17570 17571 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 17572 for (File file : files) { 17573 final String packageName = file.getName(); 17574 try { 17575 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17576 } catch (PackageManagerException e) { 17577 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17578 synchronized (mInstallLock) { 17579 destroyAppDataLI(volumeUuid, packageName, userId, 17580 StorageManager.FLAG_STORAGE_CE); 17581 } 17582 } 17583 } 17584 } 17585 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17586 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 17587 17588 final File[] files = FileUtils.listFilesOrEmpty(deDir); 17589 for (File file : files) { 17590 final String packageName = file.getName(); 17591 try { 17592 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 17593 } catch (PackageManagerException e) { 17594 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 17595 synchronized (mInstallLock) { 17596 destroyAppDataLI(volumeUuid, packageName, userId, 17597 StorageManager.FLAG_STORAGE_DE); 17598 } 17599 } 17600 } 17601 } 17602 17603 // Ensure that data directories are ready to roll for all packages 17604 // installed for this volume and user 17605 final List<PackageSetting> packages; 17606 synchronized (mPackages) { 17607 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17608 } 17609 int preparedCount = 0; 17610 for (PackageSetting ps : packages) { 17611 final String packageName = ps.name; 17612 if (ps.pkg == null) { 17613 Slog.w(TAG, "Odd, missing scanned package " + packageName); 17614 // TODO: might be due to legacy ASEC apps; we should circle back 17615 // and reconcile again once they're scanned 17616 continue; 17617 } 17618 17619 if (ps.getInstalled(userId)) { 17620 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 17621 preparedCount++; 17622 } 17623 } 17624 17625 if (restoreconNeeded) { 17626 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17627 SELinuxMMAC.setRestoreconDone(ceDir); 17628 } 17629 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 17630 SELinuxMMAC.setRestoreconDone(deDir); 17631 } 17632 } 17633 17634 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 17635 + " packages; restoreconNeeded was " + restoreconNeeded); 17636 } 17637 17638 /** 17639 * Prepare app data for the given app just after it was installed or 17640 * upgraded. This method carefully only touches users that it's installed 17641 * for, and it forces a restorecon to handle any seinfo changes. 17642 * <p> 17643 * Verifies that directories exist and that ownership and labeling is 17644 * correct for all installed apps. If there is an ownership mismatch, it 17645 * will try recovering system apps by wiping data; third-party app data is 17646 * left intact. 17647 */ 17648 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 17649 prepareAppDataAfterInstallInternal(pkg); 17650 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17651 for (int i = 0; i < childCount; i++) { 17652 PackageParser.Package childPackage = pkg.childPackages.get(i); 17653 prepareAppDataAfterInstallInternal(childPackage); 17654 } 17655 } 17656 17657 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 17658 final PackageSetting ps; 17659 synchronized (mPackages) { 17660 ps = mSettings.mPackages.get(pkg.packageName); 17661 } 17662 17663 final UserManager um = mContext.getSystemService(UserManager.class); 17664 for (UserInfo user : um.getUsers()) { 17665 final int flags; 17666 if (um.isUserUnlocked(user.id)) { 17667 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17668 } else if (um.isUserRunning(user.id)) { 17669 flags = StorageManager.FLAG_STORAGE_DE; 17670 } else { 17671 continue; 17672 } 17673 17674 if (ps.getInstalled(user.id)) { 17675 // Whenever an app changes, force a restorecon of its data 17676 // TODO: when user data is locked, mark that we're still dirty 17677 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 17678 } 17679 } 17680 } 17681 17682 /** 17683 * Prepare app data for the given app. 17684 * <p> 17685 * Verifies that directories exist and that ownership and labeling is 17686 * correct for all installed apps. If there is an ownership mismatch, this 17687 * will try recovering system apps by wiping data; third-party app data is 17688 * left intact. 17689 */ 17690 private void prepareAppData(String volumeUuid, int userId, int flags, 17691 PackageParser.Package pkg, boolean restoreconNeeded) { 17692 if (DEBUG_APP_DATA) { 17693 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 17694 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 17695 } 17696 17697 final String packageName = pkg.packageName; 17698 final ApplicationInfo app = pkg.applicationInfo; 17699 final int appId = UserHandle.getAppId(app.uid); 17700 17701 Preconditions.checkNotNull(app.seinfo); 17702 17703 synchronized (mInstallLock) { 17704 try { 17705 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17706 appId, app.seinfo, app.targetSdkVersion); 17707 } catch (InstallerException e) { 17708 if (app.isSystemApp()) { 17709 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 17710 + ", but trying to recover: " + e); 17711 destroyAppDataLI(volumeUuid, packageName, userId, flags); 17712 try { 17713 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 17714 appId, app.seinfo, app.targetSdkVersion); 17715 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 17716 } catch (InstallerException e2) { 17717 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 17718 } 17719 } else { 17720 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 17721 } 17722 } 17723 17724 if (restoreconNeeded) { 17725 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 17726 } 17727 17728 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 17729 // Create a native library symlink only if we have native libraries 17730 // and if the native libraries are 32 bit libraries. We do not provide 17731 // this symlink for 64 bit libraries. 17732 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 17733 final String nativeLibPath = app.nativeLibraryDir; 17734 try { 17735 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 17736 nativeLibPath, userId); 17737 } catch (InstallerException e) { 17738 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 17739 } 17740 } 17741 } 17742 } 17743 } 17744 17745 private void unfreezePackage(String packageName) { 17746 synchronized (mPackages) { 17747 final PackageSetting ps = mSettings.mPackages.get(packageName); 17748 if (ps != null) { 17749 ps.frozen = false; 17750 } 17751 } 17752 } 17753 17754 @Override 17755 public int movePackage(final String packageName, final String volumeUuid) { 17756 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17757 17758 final int moveId = mNextMoveId.getAndIncrement(); 17759 mHandler.post(new Runnable() { 17760 @Override 17761 public void run() { 17762 try { 17763 movePackageInternal(packageName, volumeUuid, moveId); 17764 } catch (PackageManagerException e) { 17765 Slog.w(TAG, "Failed to move " + packageName, e); 17766 mMoveCallbacks.notifyStatusChanged(moveId, 17767 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17768 } 17769 } 17770 }); 17771 return moveId; 17772 } 17773 17774 private void movePackageInternal(final String packageName, final String volumeUuid, 17775 final int moveId) throws PackageManagerException { 17776 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 17777 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17778 final PackageManager pm = mContext.getPackageManager(); 17779 17780 final boolean currentAsec; 17781 final String currentVolumeUuid; 17782 final File codeFile; 17783 final String installerPackageName; 17784 final String packageAbiOverride; 17785 final int appId; 17786 final String seinfo; 17787 final String label; 17788 final int targetSdkVersion; 17789 17790 // reader 17791 synchronized (mPackages) { 17792 final PackageParser.Package pkg = mPackages.get(packageName); 17793 final PackageSetting ps = mSettings.mPackages.get(packageName); 17794 if (pkg == null || ps == null) { 17795 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 17796 } 17797 17798 if (pkg.applicationInfo.isSystemApp()) { 17799 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 17800 "Cannot move system application"); 17801 } 17802 17803 if (pkg.applicationInfo.isExternalAsec()) { 17804 currentAsec = true; 17805 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 17806 } else if (pkg.applicationInfo.isForwardLocked()) { 17807 currentAsec = true; 17808 currentVolumeUuid = "forward_locked"; 17809 } else { 17810 currentAsec = false; 17811 currentVolumeUuid = ps.volumeUuid; 17812 17813 final File probe = new File(pkg.codePath); 17814 final File probeOat = new File(probe, "oat"); 17815 if (!probe.isDirectory() || !probeOat.isDirectory()) { 17816 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17817 "Move only supported for modern cluster style installs"); 17818 } 17819 } 17820 17821 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 17822 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17823 "Package already moved to " + volumeUuid); 17824 } 17825 17826 if (ps.frozen) { 17827 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 17828 "Failed to move already frozen package"); 17829 } 17830 ps.frozen = true; 17831 17832 codeFile = new File(pkg.codePath); 17833 installerPackageName = ps.installerPackageName; 17834 packageAbiOverride = ps.cpuAbiOverrideString; 17835 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17836 seinfo = pkg.applicationInfo.seinfo; 17837 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 17838 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 17839 } 17840 17841 // Now that we're guarded by frozen state, kill app during move 17842 final long token = Binder.clearCallingIdentity(); 17843 try { 17844 killApplication(packageName, appId, "move pkg"); 17845 } finally { 17846 Binder.restoreCallingIdentity(token); 17847 } 17848 17849 final Bundle extras = new Bundle(); 17850 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 17851 extras.putString(Intent.EXTRA_TITLE, label); 17852 mMoveCallbacks.notifyCreated(moveId, extras); 17853 17854 int installFlags; 17855 final boolean moveCompleteApp; 17856 final File measurePath; 17857 17858 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 17859 installFlags = INSTALL_INTERNAL; 17860 moveCompleteApp = !currentAsec; 17861 measurePath = Environment.getDataAppDirectory(volumeUuid); 17862 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 17863 installFlags = INSTALL_EXTERNAL; 17864 moveCompleteApp = false; 17865 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 17866 } else { 17867 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 17868 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 17869 || !volume.isMountedWritable()) { 17870 unfreezePackage(packageName); 17871 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17872 "Move location not mounted private volume"); 17873 } 17874 17875 Preconditions.checkState(!currentAsec); 17876 17877 installFlags = INSTALL_INTERNAL; 17878 moveCompleteApp = true; 17879 measurePath = Environment.getDataAppDirectory(volumeUuid); 17880 } 17881 17882 final PackageStats stats = new PackageStats(null, -1); 17883 synchronized (mInstaller) { 17884 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 17885 unfreezePackage(packageName); 17886 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17887 "Failed to measure package size"); 17888 } 17889 } 17890 17891 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 17892 + stats.dataSize); 17893 17894 final long startFreeBytes = measurePath.getFreeSpace(); 17895 final long sizeBytes; 17896 if (moveCompleteApp) { 17897 sizeBytes = stats.codeSize + stats.dataSize; 17898 } else { 17899 sizeBytes = stats.codeSize; 17900 } 17901 17902 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 17903 unfreezePackage(packageName); 17904 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 17905 "Not enough free space to move"); 17906 } 17907 17908 mMoveCallbacks.notifyStatusChanged(moveId, 10); 17909 17910 final CountDownLatch installedLatch = new CountDownLatch(1); 17911 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 17912 @Override 17913 public void onUserActionRequired(Intent intent) throws RemoteException { 17914 throw new IllegalStateException(); 17915 } 17916 17917 @Override 17918 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 17919 Bundle extras) throws RemoteException { 17920 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 17921 + PackageManager.installStatusToString(returnCode, msg)); 17922 17923 installedLatch.countDown(); 17924 17925 // Regardless of success or failure of the move operation, 17926 // always unfreeze the package 17927 unfreezePackage(packageName); 17928 17929 final int status = PackageManager.installStatusToPublicStatus(returnCode); 17930 switch (status) { 17931 case PackageInstaller.STATUS_SUCCESS: 17932 mMoveCallbacks.notifyStatusChanged(moveId, 17933 PackageManager.MOVE_SUCCEEDED); 17934 break; 17935 case PackageInstaller.STATUS_FAILURE_STORAGE: 17936 mMoveCallbacks.notifyStatusChanged(moveId, 17937 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 17938 break; 17939 default: 17940 mMoveCallbacks.notifyStatusChanged(moveId, 17941 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 17942 break; 17943 } 17944 } 17945 }; 17946 17947 final MoveInfo move; 17948 if (moveCompleteApp) { 17949 // Kick off a thread to report progress estimates 17950 new Thread() { 17951 @Override 17952 public void run() { 17953 while (true) { 17954 try { 17955 if (installedLatch.await(1, TimeUnit.SECONDS)) { 17956 break; 17957 } 17958 } catch (InterruptedException ignored) { 17959 } 17960 17961 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 17962 final int progress = 10 + (int) MathUtils.constrain( 17963 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 17964 mMoveCallbacks.notifyStatusChanged(moveId, progress); 17965 } 17966 } 17967 }.start(); 17968 17969 final String dataAppName = codeFile.getName(); 17970 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 17971 dataAppName, appId, seinfo, targetSdkVersion); 17972 } else { 17973 move = null; 17974 } 17975 17976 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 17977 17978 final Message msg = mHandler.obtainMessage(INIT_COPY); 17979 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 17980 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 17981 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 17982 packageAbiOverride, null); 17983 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 17984 msg.obj = params; 17985 17986 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 17987 System.identityHashCode(msg.obj)); 17988 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 17989 System.identityHashCode(msg.obj)); 17990 17991 mHandler.sendMessage(msg); 17992 } 17993 17994 @Override 17995 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 17996 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 17997 17998 final int realMoveId = mNextMoveId.getAndIncrement(); 17999 final Bundle extras = new Bundle(); 18000 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18001 mMoveCallbacks.notifyCreated(realMoveId, extras); 18002 18003 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18004 @Override 18005 public void onCreated(int moveId, Bundle extras) { 18006 // Ignored 18007 } 18008 18009 @Override 18010 public void onStatusChanged(int moveId, int status, long estMillis) { 18011 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18012 } 18013 }; 18014 18015 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18016 storage.setPrimaryStorageUuid(volumeUuid, callback); 18017 return realMoveId; 18018 } 18019 18020 @Override 18021 public int getMoveStatus(int moveId) { 18022 mContext.enforceCallingOrSelfPermission( 18023 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18024 return mMoveCallbacks.mLastStatus.get(moveId); 18025 } 18026 18027 @Override 18028 public void registerMoveCallback(IPackageMoveObserver callback) { 18029 mContext.enforceCallingOrSelfPermission( 18030 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18031 mMoveCallbacks.register(callback); 18032 } 18033 18034 @Override 18035 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18036 mContext.enforceCallingOrSelfPermission( 18037 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18038 mMoveCallbacks.unregister(callback); 18039 } 18040 18041 @Override 18042 public boolean setInstallLocation(int loc) { 18043 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18044 null); 18045 if (getInstallLocation() == loc) { 18046 return true; 18047 } 18048 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18049 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18050 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18051 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18052 return true; 18053 } 18054 return false; 18055 } 18056 18057 @Override 18058 public int getInstallLocation() { 18059 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18060 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18061 PackageHelper.APP_INSTALL_AUTO); 18062 } 18063 18064 /** Called by UserManagerService */ 18065 void cleanUpUser(UserManagerService userManager, int userHandle) { 18066 synchronized (mPackages) { 18067 mDirtyUsers.remove(userHandle); 18068 mUserNeedsBadging.delete(userHandle); 18069 mSettings.removeUserLPw(userHandle); 18070 mPendingBroadcasts.remove(userHandle); 18071 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18072 } 18073 synchronized (mInstallLock) { 18074 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18075 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18076 final String volumeUuid = vol.getFsUuid(); 18077 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18078 try { 18079 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18080 } catch (InstallerException e) { 18081 Slog.w(TAG, "Failed to remove user data", e); 18082 } 18083 } 18084 synchronized (mPackages) { 18085 removeUnusedPackagesLILPw(userManager, userHandle); 18086 } 18087 } 18088 } 18089 18090 /** 18091 * We're removing userHandle and would like to remove any downloaded packages 18092 * that are no longer in use by any other user. 18093 * @param userHandle the user being removed 18094 */ 18095 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18096 final boolean DEBUG_CLEAN_APKS = false; 18097 int [] users = userManager.getUserIds(); 18098 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18099 while (psit.hasNext()) { 18100 PackageSetting ps = psit.next(); 18101 if (ps.pkg == null) { 18102 continue; 18103 } 18104 final String packageName = ps.pkg.packageName; 18105 // Skip over if system app 18106 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18107 continue; 18108 } 18109 if (DEBUG_CLEAN_APKS) { 18110 Slog.i(TAG, "Checking package " + packageName); 18111 } 18112 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18113 if (keep) { 18114 if (DEBUG_CLEAN_APKS) { 18115 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18116 } 18117 } else { 18118 for (int i = 0; i < users.length; i++) { 18119 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18120 keep = true; 18121 if (DEBUG_CLEAN_APKS) { 18122 Slog.i(TAG, " Keeping package " + packageName + " for user " 18123 + users[i]); 18124 } 18125 break; 18126 } 18127 } 18128 } 18129 if (!keep) { 18130 if (DEBUG_CLEAN_APKS) { 18131 Slog.i(TAG, " Removing package " + packageName); 18132 } 18133 mHandler.post(new Runnable() { 18134 public void run() { 18135 deletePackageX(packageName, userHandle, 0); 18136 } //end run 18137 }); 18138 } 18139 } 18140 } 18141 18142 /** Called by UserManagerService */ 18143 void createNewUser(int userHandle) { 18144 synchronized (mInstallLock) { 18145 try { 18146 mInstaller.createUserConfig(userHandle); 18147 } catch (InstallerException e) { 18148 Slog.w(TAG, "Failed to create user config", e); 18149 } 18150 mSettings.createNewUserLI(this, mInstaller, userHandle); 18151 } 18152 synchronized (mPackages) { 18153 applyFactoryDefaultBrowserLPw(userHandle); 18154 primeDomainVerificationsLPw(userHandle); 18155 } 18156 } 18157 18158 void newUserCreated(final int userHandle) { 18159 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18160 // If permission review for legacy apps is required, we represent 18161 // dagerous permissions for such apps as always granted runtime 18162 // permissions to keep per user flag state whether review is needed. 18163 // Hence, if a new user is added we have to propagate dangerous 18164 // permission grants for these legacy apps. 18165 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18166 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18167 | UPDATE_PERMISSIONS_REPLACE_ALL); 18168 } 18169 } 18170 18171 @Override 18172 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18173 mContext.enforceCallingOrSelfPermission( 18174 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18175 "Only package verification agents can read the verifier device identity"); 18176 18177 synchronized (mPackages) { 18178 return mSettings.getVerifierDeviceIdentityLPw(); 18179 } 18180 } 18181 18182 @Override 18183 public void setPermissionEnforced(String permission, boolean enforced) { 18184 // TODO: Now that we no longer change GID for storage, this should to away. 18185 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18186 "setPermissionEnforced"); 18187 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18188 synchronized (mPackages) { 18189 if (mSettings.mReadExternalStorageEnforced == null 18190 || mSettings.mReadExternalStorageEnforced != enforced) { 18191 mSettings.mReadExternalStorageEnforced = enforced; 18192 mSettings.writeLPr(); 18193 } 18194 } 18195 // kill any non-foreground processes so we restart them and 18196 // grant/revoke the GID. 18197 final IActivityManager am = ActivityManagerNative.getDefault(); 18198 if (am != null) { 18199 final long token = Binder.clearCallingIdentity(); 18200 try { 18201 am.killProcessesBelowForeground("setPermissionEnforcement"); 18202 } catch (RemoteException e) { 18203 } finally { 18204 Binder.restoreCallingIdentity(token); 18205 } 18206 } 18207 } else { 18208 throw new IllegalArgumentException("No selective enforcement for " + permission); 18209 } 18210 } 18211 18212 @Override 18213 @Deprecated 18214 public boolean isPermissionEnforced(String permission) { 18215 return true; 18216 } 18217 18218 @Override 18219 public boolean isStorageLow() { 18220 final long token = Binder.clearCallingIdentity(); 18221 try { 18222 final DeviceStorageMonitorInternal 18223 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18224 if (dsm != null) { 18225 return dsm.isMemoryLow(); 18226 } else { 18227 return false; 18228 } 18229 } finally { 18230 Binder.restoreCallingIdentity(token); 18231 } 18232 } 18233 18234 @Override 18235 public IPackageInstaller getPackageInstaller() { 18236 return mInstallerService; 18237 } 18238 18239 private boolean userNeedsBadging(int userId) { 18240 int index = mUserNeedsBadging.indexOfKey(userId); 18241 if (index < 0) { 18242 final UserInfo userInfo; 18243 final long token = Binder.clearCallingIdentity(); 18244 try { 18245 userInfo = sUserManager.getUserInfo(userId); 18246 } finally { 18247 Binder.restoreCallingIdentity(token); 18248 } 18249 final boolean b; 18250 if (userInfo != null && userInfo.isManagedProfile()) { 18251 b = true; 18252 } else { 18253 b = false; 18254 } 18255 mUserNeedsBadging.put(userId, b); 18256 return b; 18257 } 18258 return mUserNeedsBadging.valueAt(index); 18259 } 18260 18261 @Override 18262 public KeySet getKeySetByAlias(String packageName, String alias) { 18263 if (packageName == null || alias == null) { 18264 return null; 18265 } 18266 synchronized(mPackages) { 18267 final PackageParser.Package pkg = mPackages.get(packageName); 18268 if (pkg == null) { 18269 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18270 throw new IllegalArgumentException("Unknown package: " + packageName); 18271 } 18272 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18273 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18274 } 18275 } 18276 18277 @Override 18278 public KeySet getSigningKeySet(String packageName) { 18279 if (packageName == null) { 18280 return null; 18281 } 18282 synchronized(mPackages) { 18283 final PackageParser.Package pkg = mPackages.get(packageName); 18284 if (pkg == null) { 18285 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18286 throw new IllegalArgumentException("Unknown package: " + packageName); 18287 } 18288 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18289 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18290 throw new SecurityException("May not access signing KeySet of other apps."); 18291 } 18292 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18293 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18294 } 18295 } 18296 18297 @Override 18298 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18299 if (packageName == null || ks == null) { 18300 return false; 18301 } 18302 synchronized(mPackages) { 18303 final PackageParser.Package pkg = mPackages.get(packageName); 18304 if (pkg == null) { 18305 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18306 throw new IllegalArgumentException("Unknown package: " + packageName); 18307 } 18308 IBinder ksh = ks.getToken(); 18309 if (ksh instanceof KeySetHandle) { 18310 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18311 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18312 } 18313 return false; 18314 } 18315 } 18316 18317 @Override 18318 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18319 if (packageName == null || ks == null) { 18320 return false; 18321 } 18322 synchronized(mPackages) { 18323 final PackageParser.Package pkg = mPackages.get(packageName); 18324 if (pkg == null) { 18325 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18326 throw new IllegalArgumentException("Unknown package: " + packageName); 18327 } 18328 IBinder ksh = ks.getToken(); 18329 if (ksh instanceof KeySetHandle) { 18330 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18331 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18332 } 18333 return false; 18334 } 18335 } 18336 18337 private void deletePackageIfUnusedLPr(final String packageName) { 18338 PackageSetting ps = mSettings.mPackages.get(packageName); 18339 if (ps == null) { 18340 return; 18341 } 18342 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18343 // TODO Implement atomic delete if package is unused 18344 // It is currently possible that the package will be deleted even if it is installed 18345 // after this method returns. 18346 mHandler.post(new Runnable() { 18347 public void run() { 18348 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18349 } 18350 }); 18351 } 18352 } 18353 18354 /** 18355 * Check and throw if the given before/after packages would be considered a 18356 * downgrade. 18357 */ 18358 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18359 throws PackageManagerException { 18360 if (after.versionCode < before.mVersionCode) { 18361 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18362 "Update version code " + after.versionCode + " is older than current " 18363 + before.mVersionCode); 18364 } else if (after.versionCode == before.mVersionCode) { 18365 if (after.baseRevisionCode < before.baseRevisionCode) { 18366 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18367 "Update base revision code " + after.baseRevisionCode 18368 + " is older than current " + before.baseRevisionCode); 18369 } 18370 18371 if (!ArrayUtils.isEmpty(after.splitNames)) { 18372 for (int i = 0; i < after.splitNames.length; i++) { 18373 final String splitName = after.splitNames[i]; 18374 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18375 if (j != -1) { 18376 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18377 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18378 "Update split " + splitName + " revision code " 18379 + after.splitRevisionCodes[i] + " is older than current " 18380 + before.splitRevisionCodes[j]); 18381 } 18382 } 18383 } 18384 } 18385 } 18386 } 18387 18388 private static class MoveCallbacks extends Handler { 18389 private static final int MSG_CREATED = 1; 18390 private static final int MSG_STATUS_CHANGED = 2; 18391 18392 private final RemoteCallbackList<IPackageMoveObserver> 18393 mCallbacks = new RemoteCallbackList<>(); 18394 18395 private final SparseIntArray mLastStatus = new SparseIntArray(); 18396 18397 public MoveCallbacks(Looper looper) { 18398 super(looper); 18399 } 18400 18401 public void register(IPackageMoveObserver callback) { 18402 mCallbacks.register(callback); 18403 } 18404 18405 public void unregister(IPackageMoveObserver callback) { 18406 mCallbacks.unregister(callback); 18407 } 18408 18409 @Override 18410 public void handleMessage(Message msg) { 18411 final SomeArgs args = (SomeArgs) msg.obj; 18412 final int n = mCallbacks.beginBroadcast(); 18413 for (int i = 0; i < n; i++) { 18414 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18415 try { 18416 invokeCallback(callback, msg.what, args); 18417 } catch (RemoteException ignored) { 18418 } 18419 } 18420 mCallbacks.finishBroadcast(); 18421 args.recycle(); 18422 } 18423 18424 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18425 throws RemoteException { 18426 switch (what) { 18427 case MSG_CREATED: { 18428 callback.onCreated(args.argi1, (Bundle) args.arg2); 18429 break; 18430 } 18431 case MSG_STATUS_CHANGED: { 18432 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 18433 break; 18434 } 18435 } 18436 } 18437 18438 private void notifyCreated(int moveId, Bundle extras) { 18439 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 18440 18441 final SomeArgs args = SomeArgs.obtain(); 18442 args.argi1 = moveId; 18443 args.arg2 = extras; 18444 obtainMessage(MSG_CREATED, args).sendToTarget(); 18445 } 18446 18447 private void notifyStatusChanged(int moveId, int status) { 18448 notifyStatusChanged(moveId, status, -1); 18449 } 18450 18451 private void notifyStatusChanged(int moveId, int status, long estMillis) { 18452 Slog.v(TAG, "Move " + moveId + " status " + status); 18453 18454 final SomeArgs args = SomeArgs.obtain(); 18455 args.argi1 = moveId; 18456 args.argi2 = status; 18457 args.arg3 = estMillis; 18458 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 18459 18460 synchronized (mLastStatus) { 18461 mLastStatus.put(moveId, status); 18462 } 18463 } 18464 } 18465 18466 private final static class OnPermissionChangeListeners extends Handler { 18467 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 18468 18469 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 18470 new RemoteCallbackList<>(); 18471 18472 public OnPermissionChangeListeners(Looper looper) { 18473 super(looper); 18474 } 18475 18476 @Override 18477 public void handleMessage(Message msg) { 18478 switch (msg.what) { 18479 case MSG_ON_PERMISSIONS_CHANGED: { 18480 final int uid = msg.arg1; 18481 handleOnPermissionsChanged(uid); 18482 } break; 18483 } 18484 } 18485 18486 public void addListenerLocked(IOnPermissionsChangeListener listener) { 18487 mPermissionListeners.register(listener); 18488 18489 } 18490 18491 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 18492 mPermissionListeners.unregister(listener); 18493 } 18494 18495 public void onPermissionsChanged(int uid) { 18496 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 18497 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 18498 } 18499 } 18500 18501 private void handleOnPermissionsChanged(int uid) { 18502 final int count = mPermissionListeners.beginBroadcast(); 18503 try { 18504 for (int i = 0; i < count; i++) { 18505 IOnPermissionsChangeListener callback = mPermissionListeners 18506 .getBroadcastItem(i); 18507 try { 18508 callback.onPermissionsChanged(uid); 18509 } catch (RemoteException e) { 18510 Log.e(TAG, "Permission listener is dead", e); 18511 } 18512 } 18513 } finally { 18514 mPermissionListeners.finishBroadcast(); 18515 } 18516 } 18517 } 18518 18519 private class PackageManagerInternalImpl extends PackageManagerInternal { 18520 @Override 18521 public void setLocationPackagesProvider(PackagesProvider provider) { 18522 synchronized (mPackages) { 18523 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 18524 } 18525 } 18526 18527 @Override 18528 public void setImePackagesProvider(PackagesProvider provider) { 18529 synchronized (mPackages) { 18530 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 18531 } 18532 } 18533 18534 @Override 18535 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 18536 synchronized (mPackages) { 18537 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 18538 } 18539 } 18540 18541 @Override 18542 public void setSmsAppPackagesProvider(PackagesProvider provider) { 18543 synchronized (mPackages) { 18544 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 18545 } 18546 } 18547 18548 @Override 18549 public void setDialerAppPackagesProvider(PackagesProvider provider) { 18550 synchronized (mPackages) { 18551 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 18552 } 18553 } 18554 18555 @Override 18556 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 18557 synchronized (mPackages) { 18558 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 18559 } 18560 } 18561 18562 @Override 18563 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 18564 synchronized (mPackages) { 18565 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 18566 } 18567 } 18568 18569 @Override 18570 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 18571 synchronized (mPackages) { 18572 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 18573 packageName, userId); 18574 } 18575 } 18576 18577 @Override 18578 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 18579 synchronized (mPackages) { 18580 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 18581 packageName, userId); 18582 } 18583 } 18584 18585 @Override 18586 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 18587 synchronized (mPackages) { 18588 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 18589 packageName, userId); 18590 } 18591 } 18592 18593 @Override 18594 public void setKeepUninstalledPackages(final List<String> packageList) { 18595 Preconditions.checkNotNull(packageList); 18596 List<String> removedFromList = null; 18597 synchronized (mPackages) { 18598 if (mKeepUninstalledPackages != null) { 18599 final int packagesCount = mKeepUninstalledPackages.size(); 18600 for (int i = 0; i < packagesCount; i++) { 18601 String oldPackage = mKeepUninstalledPackages.get(i); 18602 if (packageList != null && packageList.contains(oldPackage)) { 18603 continue; 18604 } 18605 if (removedFromList == null) { 18606 removedFromList = new ArrayList<>(); 18607 } 18608 removedFromList.add(oldPackage); 18609 } 18610 } 18611 mKeepUninstalledPackages = new ArrayList<>(packageList); 18612 if (removedFromList != null) { 18613 final int removedCount = removedFromList.size(); 18614 for (int i = 0; i < removedCount; i++) { 18615 deletePackageIfUnusedLPr(removedFromList.get(i)); 18616 } 18617 } 18618 } 18619 } 18620 18621 @Override 18622 public boolean isPermissionsReviewRequired(String packageName, int userId) { 18623 synchronized (mPackages) { 18624 // If we do not support permission review, done. 18625 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 18626 return false; 18627 } 18628 18629 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 18630 if (packageSetting == null) { 18631 return false; 18632 } 18633 18634 // Permission review applies only to apps not supporting the new permission model. 18635 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 18636 return false; 18637 } 18638 18639 // Legacy apps have the permission and get user consent on launch. 18640 PermissionsState permissionsState = packageSetting.getPermissionsState(); 18641 return permissionsState.isPermissionReviewRequired(userId); 18642 } 18643 } 18644 } 18645 18646 @Override 18647 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 18648 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 18649 synchronized (mPackages) { 18650 final long identity = Binder.clearCallingIdentity(); 18651 try { 18652 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 18653 packageNames, userId); 18654 } finally { 18655 Binder.restoreCallingIdentity(identity); 18656 } 18657 } 18658 } 18659 18660 private static void enforceSystemOrPhoneCaller(String tag) { 18661 int callingUid = Binder.getCallingUid(); 18662 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 18663 throw new SecurityException( 18664 "Cannot call " + tag + " from UID " + callingUid); 18665 } 18666 } 18667 18668 boolean isHistoricalPackageUsageAvailable() { 18669 return mPackageUsage.isHistoricalPackageUsageAvailable(); 18670 } 18671} 18672