PackageManagerService.java revision d5896630f6a2f21da107031cab216dc93bdcd851
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; 66import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 67import static android.content.pm.PackageManager.MATCH_ENCRYPTION_UNAWARE; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 99 100import android.Manifest; 101import android.annotation.NonNull; 102import android.annotation.Nullable; 103import android.app.ActivityManager; 104import android.app.ActivityManagerNative; 105import android.app.IActivityManager; 106import android.app.admin.IDevicePolicyManager; 107import android.app.backup.IBackupManager; 108import android.content.BroadcastReceiver; 109import android.content.ComponentName; 110import android.content.Context; 111import android.content.IIntentReceiver; 112import android.content.Intent; 113import android.content.IntentFilter; 114import android.content.IntentSender; 115import android.content.IntentSender.SendIntentException; 116import android.content.ServiceConnection; 117import android.content.pm.ActivityInfo; 118import android.content.pm.ApplicationInfo; 119import android.content.pm.AppsQueryHelper; 120import android.content.pm.ComponentInfo; 121import android.content.pm.EphemeralApplicationInfo; 122import android.content.pm.EphemeralResolveInfo; 123import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 124import android.content.pm.FeatureInfo; 125import android.content.pm.IOnPermissionsChangeListener; 126import android.content.pm.IPackageDataObserver; 127import android.content.pm.IPackageDeleteObserver; 128import android.content.pm.IPackageDeleteObserver2; 129import android.content.pm.IPackageInstallObserver2; 130import android.content.pm.IPackageInstaller; 131import android.content.pm.IPackageManager; 132import android.content.pm.IPackageMoveObserver; 133import android.content.pm.IPackageStatsObserver; 134import android.content.pm.InstrumentationInfo; 135import android.content.pm.IntentFilterVerificationInfo; 136import android.content.pm.KeySet; 137import android.content.pm.PackageCleanItem; 138import android.content.pm.PackageInfo; 139import android.content.pm.PackageInfoLite; 140import android.content.pm.PackageInstaller; 141import android.content.pm.PackageManager; 142import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 143import android.content.pm.PackageManagerInternal; 144import android.content.pm.PackageParser; 145import android.content.pm.PackageParser.ActivityIntentInfo; 146import android.content.pm.PackageParser.PackageLite; 147import android.content.pm.PackageParser.PackageParserException; 148import android.content.pm.PackageStats; 149import android.content.pm.PackageUserState; 150import android.content.pm.ParceledListSlice; 151import android.content.pm.PermissionGroupInfo; 152import android.content.pm.PermissionInfo; 153import android.content.pm.ProviderInfo; 154import android.content.pm.ResolveInfo; 155import android.content.pm.ServiceInfo; 156import android.content.pm.Signature; 157import android.content.pm.UserInfo; 158import android.content.pm.VerifierDeviceIdentity; 159import android.content.pm.VerifierInfo; 160import android.content.res.Resources; 161import android.graphics.Bitmap; 162import android.hardware.display.DisplayManager; 163import android.net.Uri; 164import android.os.Binder; 165import android.os.Build; 166import android.os.Bundle; 167import android.os.Debug; 168import android.os.Environment; 169import android.os.Environment.UserEnvironment; 170import android.os.FileUtils; 171import android.os.Handler; 172import android.os.IBinder; 173import android.os.Looper; 174import android.os.Message; 175import android.os.Parcel; 176import android.os.ParcelFileDescriptor; 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.PrintWriter; 269import java.nio.charset.StandardCharsets; 270import java.security.MessageDigest; 271import java.security.NoSuchAlgorithmException; 272import java.security.PublicKey; 273import java.security.cert.CertificateEncodingException; 274import java.security.cert.CertificateException; 275import java.text.SimpleDateFormat; 276import java.util.ArrayList; 277import java.util.Arrays; 278import java.util.Collection; 279import java.util.Collections; 280import java.util.Comparator; 281import java.util.Date; 282import java.util.HashSet; 283import java.util.Iterator; 284import java.util.List; 285import java.util.Map; 286import java.util.Objects; 287import java.util.Set; 288import java.util.concurrent.CountDownLatch; 289import java.util.concurrent.TimeUnit; 290import java.util.concurrent.atomic.AtomicBoolean; 291import java.util.concurrent.atomic.AtomicInteger; 292import java.util.concurrent.atomic.AtomicLong; 293 294/** 295 * Keep track of all those .apks everywhere. 296 * 297 * This is very central to the platform's security; please run the unit 298 * tests whenever making modifications here: 299 * 300runtest -c android.content.pm.PackageManagerTests frameworks-core 301 * 302 * {@hide} 303 */ 304public class PackageManagerService extends IPackageManager.Stub { 305 static final String TAG = "PackageManager"; 306 static final boolean DEBUG_SETTINGS = false; 307 static final boolean DEBUG_PREFERRED = false; 308 static final boolean DEBUG_UPGRADE = false; 309 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 310 private static final boolean DEBUG_BACKUP = false; 311 private static final boolean DEBUG_INSTALL = false; 312 private static final boolean DEBUG_REMOVE = false; 313 private static final boolean DEBUG_BROADCASTS = false; 314 private static final boolean DEBUG_SHOW_INFO = false; 315 private static final boolean DEBUG_PACKAGE_INFO = false; 316 private static final boolean DEBUG_INTENT_MATCHING = false; 317 private static final boolean DEBUG_PACKAGE_SCANNING = false; 318 private static final boolean DEBUG_VERIFY = false; 319 320 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 321 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 322 // user, but by default initialize to this. 323 static final boolean DEBUG_DEXOPT = false; 324 325 private static final boolean DEBUG_ABI_SELECTION = false; 326 private static final boolean DEBUG_EPHEMERAL = false; 327 private static final boolean DEBUG_TRIAGED_MISSING = false; 328 private static final boolean DEBUG_APP_DATA = false; 329 330 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 331 332 private static final boolean DISABLE_EPHEMERAL_APPS = true; 333 334 private static final int RADIO_UID = Process.PHONE_UID; 335 private static final int LOG_UID = Process.LOG_UID; 336 private static final int NFC_UID = Process.NFC_UID; 337 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 338 private static final int SHELL_UID = Process.SHELL_UID; 339 340 // Cap the size of permission trees that 3rd party apps can define 341 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 342 343 // Suffix used during package installation when copying/moving 344 // package apks to install directory. 345 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 346 347 static final int SCAN_NO_DEX = 1<<1; 348 static final int SCAN_FORCE_DEX = 1<<2; 349 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 350 static final int SCAN_NEW_INSTALL = 1<<4; 351 static final int SCAN_NO_PATHS = 1<<5; 352 static final int SCAN_UPDATE_TIME = 1<<6; 353 static final int SCAN_DEFER_DEX = 1<<7; 354 static final int SCAN_BOOTING = 1<<8; 355 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 356 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 357 static final int SCAN_REPLACING = 1<<11; 358 static final int SCAN_REQUIRE_KNOWN = 1<<12; 359 static final int SCAN_MOVE = 1<<13; 360 static final int SCAN_INITIAL = 1<<14; 361 static final int SCAN_CHECK_ONLY = 1<<15; 362 static final int SCAN_DONT_KILL_APP = 1<<17; 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 final ArrayMap<String, Set<String>> mKnownCodebase = 503 new ArrayMap<String, Set<String>>(); 504 505 // Tracks available target package names -> overlay package paths. 506 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 507 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 508 509 /** 510 * Tracks new system packages [received in an OTA] that we expect to 511 * find updated user-installed versions. Keys are package name, values 512 * are package location. 513 */ 514 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 515 516 /** 517 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 518 */ 519 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 520 /** 521 * Whether or not system app permissions should be promoted from install to runtime. 522 */ 523 boolean mPromoteSystemApps; 524 525 final Settings mSettings; 526 boolean mRestoredSettings; 527 528 // System configuration read by SystemConfig. 529 final int[] mGlobalGids; 530 final SparseArray<ArraySet<String>> mSystemPermissions; 531 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 532 533 // If mac_permissions.xml was found for seinfo labeling. 534 boolean mFoundPolicyFile; 535 536 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 537 538 public static final class SharedLibraryEntry { 539 public final String path; 540 public final String apk; 541 542 SharedLibraryEntry(String _path, String _apk) { 543 path = _path; 544 apk = _apk; 545 } 546 } 547 548 // Currently known shared libraries. 549 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 550 new ArrayMap<String, SharedLibraryEntry>(); 551 552 // All available activities, for your resolving pleasure. 553 final ActivityIntentResolver mActivities = 554 new ActivityIntentResolver(); 555 556 // All available receivers, for your resolving pleasure. 557 final ActivityIntentResolver mReceivers = 558 new ActivityIntentResolver(); 559 560 // All available services, for your resolving pleasure. 561 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 562 563 // All available providers, for your resolving pleasure. 564 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 565 566 // Mapping from provider base names (first directory in content URI codePath) 567 // to the provider information. 568 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 569 new ArrayMap<String, PackageParser.Provider>(); 570 571 // Mapping from instrumentation class names to info about them. 572 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 573 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 574 575 // Mapping from permission names to info about them. 576 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 577 new ArrayMap<String, PackageParser.PermissionGroup>(); 578 579 // Packages whose data we have transfered into another package, thus 580 // should no longer exist. 581 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 582 583 // Broadcast actions that are only available to the system. 584 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 585 586 /** List of packages waiting for verification. */ 587 final SparseArray<PackageVerificationState> mPendingVerification 588 = new SparseArray<PackageVerificationState>(); 589 590 /** Set of packages associated with each app op permission. */ 591 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 592 593 final PackageInstallerService mInstallerService; 594 595 private final PackageDexOptimizer mPackageDexOptimizer; 596 597 private AtomicInteger mNextMoveId = new AtomicInteger(); 598 private final MoveCallbacks mMoveCallbacks; 599 600 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 601 602 // Cache of users who need badging. 603 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 604 605 /** Token for keys in mPendingVerification. */ 606 private int mPendingVerificationToken = 0; 607 608 volatile boolean mSystemReady; 609 volatile boolean mSafeMode; 610 volatile boolean mHasSystemUidErrors; 611 612 ApplicationInfo mAndroidApplication; 613 final ActivityInfo mResolveActivity = new ActivityInfo(); 614 final ResolveInfo mResolveInfo = new ResolveInfo(); 615 ComponentName mResolveComponentName; 616 PackageParser.Package mPlatformPackage; 617 ComponentName mCustomResolverComponentName; 618 619 boolean mResolverReplaced = false; 620 621 private final @Nullable ComponentName mIntentFilterVerifierComponent; 622 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 623 624 private int mIntentFilterVerificationToken = 0; 625 626 /** Component that knows whether or not an ephemeral application exists */ 627 final ComponentName mEphemeralResolverComponent; 628 /** The service connection to the ephemeral resolver */ 629 final EphemeralResolverConnection mEphemeralResolverConnection; 630 631 /** Component used to install ephemeral applications */ 632 final ComponentName mEphemeralInstallerComponent; 633 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 634 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 635 636 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 637 = new SparseArray<IntentFilterVerificationState>(); 638 639 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 640 new DefaultPermissionGrantPolicy(this); 641 642 // List of packages names to keep cached, even if they are uninstalled for all users 643 private List<String> mKeepUninstalledPackages; 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 1425 if (data != null) { 1426 InstallArgs args = data.args; 1427 PackageInstalledInfo parentRes = data.res; 1428 1429 final boolean grantPermissions = (args.installFlags 1430 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1431 final boolean killApp = (args.installFlags 1432 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1433 final String[] grantedPermissions = args.installGrantPermissions; 1434 1435 // Handle the parent package 1436 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1437 grantedPermissions, args.observer); 1438 1439 // Handle the child packages 1440 final int childCount = (parentRes.addedChildPackages != null) 1441 ? parentRes.addedChildPackages.size() : 0; 1442 for (int i = 0; i < childCount; i++) { 1443 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1444 handlePackagePostInstall(childRes, grantPermissions, killApp, 1445 grantedPermissions, args.observer); 1446 } 1447 1448 // Log tracing if needed 1449 if (args.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1451 args.traceCookie); 1452 } 1453 } else { 1454 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1455 } 1456 1457 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1458 } break; 1459 case UPDATED_MEDIA_STATUS: { 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1461 boolean reportStatus = msg.arg1 == 1; 1462 boolean doGc = msg.arg2 == 1; 1463 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1464 if (doGc) { 1465 // Force a gc to clear up stale containers. 1466 Runtime.getRuntime().gc(); 1467 } 1468 if (msg.obj != null) { 1469 @SuppressWarnings("unchecked") 1470 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1471 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1472 // Unload containers 1473 unloadAllContainers(args); 1474 } 1475 if (reportStatus) { 1476 try { 1477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1478 PackageHelper.getMountService().finishMediaUpdate(); 1479 } catch (RemoteException e) { 1480 Log.e(TAG, "MountService not running?"); 1481 } 1482 } 1483 } break; 1484 case WRITE_SETTINGS: { 1485 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1486 synchronized (mPackages) { 1487 removeMessages(WRITE_SETTINGS); 1488 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1489 mSettings.writeLPr(); 1490 mDirtyUsers.clear(); 1491 } 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1493 } break; 1494 case WRITE_PACKAGE_RESTRICTIONS: { 1495 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1496 synchronized (mPackages) { 1497 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1498 for (int userId : mDirtyUsers) { 1499 mSettings.writePackageRestrictionsLPr(userId); 1500 } 1501 mDirtyUsers.clear(); 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 } break; 1505 case CHECK_PENDING_VERIFICATION: { 1506 final int verificationId = msg.arg1; 1507 final PackageVerificationState state = mPendingVerification.get(verificationId); 1508 1509 if ((state != null) && !state.timeoutExtended()) { 1510 final InstallArgs args = state.getInstallArgs(); 1511 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1512 1513 Slog.i(TAG, "Verification timed out for " + originUri); 1514 mPendingVerification.remove(verificationId); 1515 1516 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1517 1518 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1519 Slog.i(TAG, "Continuing with installation of " + originUri); 1520 state.setVerifierResponse(Binder.getCallingUid(), 1521 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1522 broadcastPackageVerified(verificationId, originUri, 1523 PackageManager.VERIFICATION_ALLOW, 1524 state.getInstallArgs().getUser()); 1525 try { 1526 ret = args.copyApk(mContainerService, true); 1527 } catch (RemoteException e) { 1528 Slog.e(TAG, "Could not contact the ContainerService"); 1529 } 1530 } else { 1531 broadcastPackageVerified(verificationId, originUri, 1532 PackageManager.VERIFICATION_REJECT, 1533 state.getInstallArgs().getUser()); 1534 } 1535 1536 Trace.asyncTraceEnd( 1537 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1538 1539 processPendingInstall(args, ret); 1540 mHandler.sendEmptyMessage(MCS_UNBIND); 1541 } 1542 break; 1543 } 1544 case PACKAGE_VERIFIED: { 1545 final int verificationId = msg.arg1; 1546 1547 final PackageVerificationState state = mPendingVerification.get(verificationId); 1548 if (state == null) { 1549 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1550 break; 1551 } 1552 1553 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1554 1555 state.setVerifierResponse(response.callerUid, response.code); 1556 1557 if (state.isVerificationComplete()) { 1558 mPendingVerification.remove(verificationId); 1559 1560 final InstallArgs args = state.getInstallArgs(); 1561 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1562 1563 int ret; 1564 if (state.isInstallAllowed()) { 1565 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1566 broadcastPackageVerified(verificationId, originUri, 1567 response.code, state.getInstallArgs().getUser()); 1568 try { 1569 ret = args.copyApk(mContainerService, true); 1570 } catch (RemoteException e) { 1571 Slog.e(TAG, "Could not contact the ContainerService"); 1572 } 1573 } else { 1574 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1575 } 1576 1577 Trace.asyncTraceEnd( 1578 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1579 1580 processPendingInstall(args, ret); 1581 mHandler.sendEmptyMessage(MCS_UNBIND); 1582 } 1583 1584 break; 1585 } 1586 case START_INTENT_FILTER_VERIFICATIONS: { 1587 IFVerificationParams params = (IFVerificationParams) msg.obj; 1588 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1589 params.replacing, params.pkg); 1590 break; 1591 } 1592 case INTENT_FILTER_VERIFIED: { 1593 final int verificationId = msg.arg1; 1594 1595 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1596 verificationId); 1597 if (state == null) { 1598 Slog.w(TAG, "Invalid IntentFilter verification token " 1599 + verificationId + " received"); 1600 break; 1601 } 1602 1603 final int userId = state.getUserId(); 1604 1605 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1606 "Processing IntentFilter verification with token:" 1607 + verificationId + " and userId:" + userId); 1608 1609 final IntentFilterVerificationResponse response = 1610 (IntentFilterVerificationResponse) msg.obj; 1611 1612 state.setVerifierResponse(response.callerUid, response.code); 1613 1614 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1615 "IntentFilter verification with token:" + verificationId 1616 + " and userId:" + userId 1617 + " is settings verifier response with response code:" 1618 + response.code); 1619 1620 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1621 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1622 + response.getFailedDomainsString()); 1623 } 1624 1625 if (state.isVerificationComplete()) { 1626 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1627 } else { 1628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1629 "IntentFilter verification with token:" + verificationId 1630 + " was not said to be complete"); 1631 } 1632 1633 break; 1634 } 1635 } 1636 } 1637 } 1638 1639 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1640 boolean killApp, String[] grantedPermissions, 1641 IPackageInstallObserver2 installObserver) { 1642 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1643 // Send the removed broadcasts 1644 if (res.removedInfo != null) { 1645 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1646 } 1647 1648 // Now that we successfully installed the package, grant runtime 1649 // permissions if requested before broadcasting the install. 1650 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1651 >= Build.VERSION_CODES.M) { 1652 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1653 } 1654 1655 final boolean update = res.removedInfo != null 1656 && res.removedInfo.removedPackage != null; 1657 1658 // If this is the first time we have child packages for a disabled privileged 1659 // app that had no children, we grant requested runtime permissions to the new 1660 // children if the parent on the system image had them already granted. 1661 if (res.pkg.parentPackage != null) { 1662 synchronized (mPackages) { 1663 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1664 } 1665 } 1666 1667 synchronized (mPackages) { 1668 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1669 } 1670 1671 final String packageName = res.pkg.applicationInfo.packageName; 1672 Bundle extras = new Bundle(1); 1673 extras.putInt(Intent.EXTRA_UID, res.uid); 1674 1675 // Determine the set of users who are adding this package for 1676 // the first time vs. those who are seeing an update. 1677 int[] firstUsers = EMPTY_INT_ARRAY; 1678 int[] updateUsers = EMPTY_INT_ARRAY; 1679 if (res.origUsers == null || res.origUsers.length == 0) { 1680 firstUsers = res.newUsers; 1681 } else { 1682 for (int newUser : res.newUsers) { 1683 boolean isNew = true; 1684 for (int origUser : res.origUsers) { 1685 if (origUser == newUser) { 1686 isNew = false; 1687 break; 1688 } 1689 } 1690 if (isNew) { 1691 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1692 } else { 1693 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1694 } 1695 } 1696 } 1697 1698 // Send installed broadcasts if the install/update is not ephemeral 1699 if (!isEphemeral(res.pkg)) { 1700 // Send added for users that see the package for the first time 1701 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1702 extras, 0 /*flags*/, null /*targetPackage*/, 1703 null /*finishedReceiver*/, firstUsers); 1704 1705 // Send added for users that don't see the package for the first time 1706 if (update) { 1707 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1708 } 1709 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1710 extras, 0 /*flags*/, null /*targetPackage*/, 1711 null /*finishedReceiver*/, updateUsers); 1712 1713 // Send replaced for users that don't see the package for the first time 1714 if (update) { 1715 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1716 packageName, extras, 0 /*flags*/, 1717 null /*targetPackage*/, null /*finishedReceiver*/, 1718 updateUsers); 1719 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1720 null /*package*/, null /*extras*/, 0 /*flags*/, 1721 packageName /*targetPackage*/, 1722 null /*finishedReceiver*/, updateUsers); 1723 } 1724 1725 // Send broadcast package appeared if forward locked/external for all users 1726 // treat asec-hosted packages like removable media on upgrade 1727 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1728 if (DEBUG_INSTALL) { 1729 Slog.i(TAG, "upgrading pkg " + res.pkg 1730 + " is ASEC-hosted -> AVAILABLE"); 1731 } 1732 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1733 ArrayList<String> pkgList = new ArrayList<>(1); 1734 pkgList.add(packageName); 1735 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1736 } 1737 } 1738 1739 // Work that needs to happen on first install within each user 1740 if (firstUsers != null && firstUsers.length > 0) { 1741 synchronized (mPackages) { 1742 for (int userId : firstUsers) { 1743 // If this app is a browser and it's newly-installed for some 1744 // users, clear any default-browser state in those users. The 1745 // app's nature doesn't depend on the user, so we can just check 1746 // its browser nature in any user and generalize. 1747 if (packageIsBrowser(packageName, userId)) { 1748 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1749 } 1750 1751 // We may also need to apply pending (restored) runtime 1752 // permission grants within these users. 1753 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1754 } 1755 } 1756 } 1757 1758 // Log current value of "unknown sources" setting 1759 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1760 getUnknownSourcesSettings()); 1761 1762 // Force a gc to clear up things 1763 Runtime.getRuntime().gc(); 1764 1765 // Remove the replaced package's older resources safely now 1766 // We delete after a gc for applications on sdcard. 1767 if (res.removedInfo != null && res.removedInfo.args != null) { 1768 synchronized (mInstallLock) { 1769 res.removedInfo.args.doPostDeleteLI(true); 1770 } 1771 } 1772 } 1773 1774 // If someone is watching installs - notify them 1775 if (installObserver != null) { 1776 try { 1777 Bundle extras = extrasForInstallResult(res); 1778 installObserver.onPackageInstalled(res.name, res.returnCode, 1779 res.returnMsg, extras); 1780 } catch (RemoteException e) { 1781 Slog.i(TAG, "Observer no longer exists."); 1782 } 1783 } 1784 } 1785 1786 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1787 PackageParser.Package pkg) { 1788 if (pkg.parentPackage == null) { 1789 return; 1790 } 1791 if (pkg.requestedPermissions == null) { 1792 return; 1793 } 1794 final PackageSetting disabledSysParentPs = mSettings 1795 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1796 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1797 || !disabledSysParentPs.isPrivileged() 1798 || (disabledSysParentPs.childPackageNames != null 1799 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1800 return; 1801 } 1802 final int[] allUserIds = sUserManager.getUserIds(); 1803 final int permCount = pkg.requestedPermissions.size(); 1804 for (int i = 0; i < permCount; i++) { 1805 String permission = pkg.requestedPermissions.get(i); 1806 BasePermission bp = mSettings.mPermissions.get(permission); 1807 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1808 continue; 1809 } 1810 for (int userId : allUserIds) { 1811 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1812 permission, userId)) { 1813 grantRuntimePermission(pkg.packageName, permission, userId); 1814 } 1815 } 1816 } 1817 } 1818 1819 private StorageEventListener mStorageListener = new StorageEventListener() { 1820 @Override 1821 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1822 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1823 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1824 final String volumeUuid = vol.getFsUuid(); 1825 1826 // Clean up any users or apps that were removed or recreated 1827 // while this volume was missing 1828 reconcileUsers(volumeUuid); 1829 reconcileApps(volumeUuid); 1830 1831 // Clean up any install sessions that expired or were 1832 // cancelled while this volume was missing 1833 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1834 1835 loadPrivatePackages(vol); 1836 1837 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1838 unloadPrivatePackages(vol); 1839 } 1840 } 1841 1842 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1843 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1844 updateExternalMediaStatus(true, false); 1845 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1846 updateExternalMediaStatus(false, false); 1847 } 1848 } 1849 } 1850 1851 @Override 1852 public void onVolumeForgotten(String fsUuid) { 1853 if (TextUtils.isEmpty(fsUuid)) { 1854 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1855 return; 1856 } 1857 1858 // Remove any apps installed on the forgotten volume 1859 synchronized (mPackages) { 1860 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1861 for (PackageSetting ps : packages) { 1862 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1863 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1864 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1865 } 1866 1867 mSettings.onVolumeForgotten(fsUuid); 1868 mSettings.writeLPr(); 1869 } 1870 } 1871 }; 1872 1873 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1874 String[] grantedPermissions) { 1875 for (int userId : userIds) { 1876 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1877 } 1878 1879 // We could have touched GID membership, so flush out packages.list 1880 synchronized (mPackages) { 1881 mSettings.writePackageListLPr(); 1882 } 1883 } 1884 1885 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1886 String[] grantedPermissions) { 1887 SettingBase sb = (SettingBase) pkg.mExtras; 1888 if (sb == null) { 1889 return; 1890 } 1891 1892 PermissionsState permissionsState = sb.getPermissionsState(); 1893 1894 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1895 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1896 1897 synchronized (mPackages) { 1898 for (String permission : pkg.requestedPermissions) { 1899 BasePermission bp = mSettings.mPermissions.get(permission); 1900 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1901 && (grantedPermissions == null 1902 || ArrayUtils.contains(grantedPermissions, permission))) { 1903 final int flags = permissionsState.getPermissionFlags(permission, userId); 1904 // Installer cannot change immutable permissions. 1905 if ((flags & immutableFlags) == 0) { 1906 grantRuntimePermission(pkg.packageName, permission, userId); 1907 } 1908 } 1909 } 1910 } 1911 } 1912 1913 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1914 Bundle extras = null; 1915 switch (res.returnCode) { 1916 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1917 extras = new Bundle(); 1918 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1919 res.origPermission); 1920 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1921 res.origPackage); 1922 break; 1923 } 1924 case PackageManager.INSTALL_SUCCEEDED: { 1925 extras = new Bundle(); 1926 extras.putBoolean(Intent.EXTRA_REPLACING, 1927 res.removedInfo != null && res.removedInfo.removedPackage != null); 1928 break; 1929 } 1930 } 1931 return extras; 1932 } 1933 1934 void scheduleWriteSettingsLocked() { 1935 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1936 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1937 } 1938 } 1939 1940 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1941 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1942 scheduleWritePackageRestrictionsLocked(userId); 1943 } 1944 1945 void scheduleWritePackageRestrictionsLocked(int userId) { 1946 final int[] userIds = (userId == UserHandle.USER_ALL) 1947 ? sUserManager.getUserIds() : new int[]{userId}; 1948 for (int nextUserId : userIds) { 1949 if (!sUserManager.exists(nextUserId)) return; 1950 mDirtyUsers.add(nextUserId); 1951 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1952 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1953 } 1954 } 1955 } 1956 1957 public static PackageManagerService main(Context context, Installer installer, 1958 boolean factoryTest, boolean onlyCore) { 1959 PackageManagerService m = new PackageManagerService(context, installer, 1960 factoryTest, onlyCore); 1961 m.enableSystemUserPackages(); 1962 ServiceManager.addService("package", m); 1963 return m; 1964 } 1965 1966 private void enableSystemUserPackages() { 1967 if (!UserManager.isSplitSystemUser()) { 1968 return; 1969 } 1970 // For system user, enable apps based on the following conditions: 1971 // - app is whitelisted or belong to one of these groups: 1972 // -- system app which has no launcher icons 1973 // -- system app which has INTERACT_ACROSS_USERS permission 1974 // -- system IME app 1975 // - app is not in the blacklist 1976 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1977 Set<String> enableApps = new ArraySet<>(); 1978 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1979 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1980 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1981 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1982 enableApps.addAll(wlApps); 1983 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1984 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1985 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1986 enableApps.removeAll(blApps); 1987 Log.i(TAG, "Applications installed for system user: " + enableApps); 1988 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1989 UserHandle.SYSTEM); 1990 final int allAppsSize = allAps.size(); 1991 synchronized (mPackages) { 1992 for (int i = 0; i < allAppsSize; i++) { 1993 String pName = allAps.get(i); 1994 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1995 // Should not happen, but we shouldn't be failing if it does 1996 if (pkgSetting == null) { 1997 continue; 1998 } 1999 boolean install = enableApps.contains(pName); 2000 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2001 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2002 + " for system user"); 2003 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2004 } 2005 } 2006 } 2007 } 2008 2009 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2010 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2011 Context.DISPLAY_SERVICE); 2012 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2013 } 2014 2015 public PackageManagerService(Context context, Installer installer, 2016 boolean factoryTest, boolean onlyCore) { 2017 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2018 SystemClock.uptimeMillis()); 2019 2020 if (mSdkVersion <= 0) { 2021 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2022 } 2023 2024 mContext = context; 2025 mFactoryTest = factoryTest; 2026 mOnlyCore = onlyCore; 2027 mMetrics = new DisplayMetrics(); 2028 mSettings = new Settings(mPackages); 2029 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2030 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2031 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2032 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2033 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2034 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2035 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2036 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2037 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2038 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2039 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2040 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2041 2042 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2043 if (separateProcesses != null && separateProcesses.length() > 0) { 2044 if ("*".equals(separateProcesses)) { 2045 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2046 mSeparateProcesses = null; 2047 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2048 } else { 2049 mDefParseFlags = 0; 2050 mSeparateProcesses = separateProcesses.split(","); 2051 Slog.w(TAG, "Running with debug.separate_processes: " 2052 + separateProcesses); 2053 } 2054 } else { 2055 mDefParseFlags = 0; 2056 mSeparateProcesses = null; 2057 } 2058 2059 mInstaller = installer; 2060 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2061 "*dexopt*"); 2062 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2063 2064 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2065 FgThread.get().getLooper()); 2066 2067 getDefaultDisplayMetrics(context, mMetrics); 2068 2069 SystemConfig systemConfig = SystemConfig.getInstance(); 2070 mGlobalGids = systemConfig.getGlobalGids(); 2071 mSystemPermissions = systemConfig.getSystemPermissions(); 2072 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2073 2074 synchronized (mInstallLock) { 2075 // writer 2076 synchronized (mPackages) { 2077 mHandlerThread = new ServiceThread(TAG, 2078 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2079 mHandlerThread.start(); 2080 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2081 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2082 2083 File dataDir = Environment.getDataDirectory(); 2084 mAppInstallDir = new File(dataDir, "app"); 2085 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2086 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2087 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2088 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2089 2090 sUserManager = new UserManagerService(context, this, mPackages); 2091 2092 // Propagate permission configuration in to package manager. 2093 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2094 = systemConfig.getPermissions(); 2095 for (int i=0; i<permConfig.size(); i++) { 2096 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2097 BasePermission bp = mSettings.mPermissions.get(perm.name); 2098 if (bp == null) { 2099 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2100 mSettings.mPermissions.put(perm.name, bp); 2101 } 2102 if (perm.gids != null) { 2103 bp.setGids(perm.gids, perm.perUser); 2104 } 2105 } 2106 2107 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2108 for (int i=0; i<libConfig.size(); i++) { 2109 mSharedLibraries.put(libConfig.keyAt(i), 2110 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2111 } 2112 2113 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2114 2115 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2116 2117 String customResolverActivity = Resources.getSystem().getString( 2118 R.string.config_customResolverActivity); 2119 if (TextUtils.isEmpty(customResolverActivity)) { 2120 customResolverActivity = null; 2121 } else { 2122 mCustomResolverComponentName = ComponentName.unflattenFromString( 2123 customResolverActivity); 2124 } 2125 2126 long startTime = SystemClock.uptimeMillis(); 2127 2128 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2129 startTime); 2130 2131 // Set flag to monitor and not change apk file paths when 2132 // scanning install directories. 2133 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2134 2135 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2136 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2137 2138 if (bootClassPath == null) { 2139 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2140 } 2141 2142 if (systemServerClassPath == null) { 2143 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2144 } 2145 2146 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2147 final String[] dexCodeInstructionSets = 2148 getDexCodeInstructionSets( 2149 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2150 2151 /** 2152 * Ensure all external libraries have had dexopt run on them. 2153 */ 2154 if (mSharedLibraries.size() > 0) { 2155 // NOTE: For now, we're compiling these system "shared libraries" 2156 // (and framework jars) into all available architectures. It's possible 2157 // to compile them only when we come across an app that uses them (there's 2158 // already logic for that in scanPackageLI) but that adds some complexity. 2159 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2160 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2161 final String lib = libEntry.path; 2162 if (lib == null) { 2163 continue; 2164 } 2165 2166 try { 2167 // Shared libraries do not have profiles so we perform a full 2168 // AOT compilation (if needed). 2169 int dexoptNeeded = DexFile.getDexOptNeeded( 2170 lib, dexCodeInstructionSet, 2171 DexFile.COMPILATION_TYPE_FULL); 2172 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2173 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2174 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2175 StorageManager.UUID_PRIVATE_INTERNAL, 2176 false /*useProfiles*/); 2177 } 2178 } catch (FileNotFoundException e) { 2179 Slog.w(TAG, "Library not found: " + lib); 2180 } catch (IOException | InstallerException e) { 2181 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2182 + e.getMessage()); 2183 } 2184 } 2185 } 2186 } 2187 2188 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2189 2190 final VersionInfo ver = mSettings.getInternalVersion(); 2191 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2192 // when upgrading from pre-M, promote system app permissions from install to runtime 2193 mPromoteSystemApps = 2194 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2195 2196 // save off the names of pre-existing system packages prior to scanning; we don't 2197 // want to automatically grant runtime permissions for new system apps 2198 if (mPromoteSystemApps) { 2199 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2200 while (pkgSettingIter.hasNext()) { 2201 PackageSetting ps = pkgSettingIter.next(); 2202 if (isSystemApp(ps)) { 2203 mExistingSystemPackages.add(ps.name); 2204 } 2205 } 2206 } 2207 2208 // Collect vendor overlay packages. 2209 // (Do this before scanning any apps.) 2210 // For security and version matching reason, only consider 2211 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2212 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2213 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2214 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2215 2216 // Find base frameworks (resource packages without code). 2217 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2218 | PackageParser.PARSE_IS_SYSTEM_DIR 2219 | PackageParser.PARSE_IS_PRIVILEGED, 2220 scanFlags | SCAN_NO_DEX, 0); 2221 2222 // Collected privileged system packages. 2223 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2224 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2225 | PackageParser.PARSE_IS_SYSTEM_DIR 2226 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2227 2228 // Collect ordinary system packages. 2229 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2230 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2231 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2232 2233 // Collect all vendor packages. 2234 File vendorAppDir = new File("/vendor/app"); 2235 try { 2236 vendorAppDir = vendorAppDir.getCanonicalFile(); 2237 } catch (IOException e) { 2238 // failed to look up canonical path, continue with original one 2239 } 2240 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2241 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2242 2243 // Collect all OEM packages. 2244 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2245 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2246 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2247 2248 // Prune any system packages that no longer exist. 2249 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2250 if (!mOnlyCore) { 2251 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2252 while (psit.hasNext()) { 2253 PackageSetting ps = psit.next(); 2254 2255 /* 2256 * If this is not a system app, it can't be a 2257 * disable system app. 2258 */ 2259 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2260 continue; 2261 } 2262 2263 /* 2264 * If the package is scanned, it's not erased. 2265 */ 2266 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2267 if (scannedPkg != null) { 2268 /* 2269 * If the system app is both scanned and in the 2270 * disabled packages list, then it must have been 2271 * added via OTA. Remove it from the currently 2272 * scanned package so the previously user-installed 2273 * application can be scanned. 2274 */ 2275 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2276 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2277 + ps.name + "; removing system app. Last known codePath=" 2278 + ps.codePathString + ", installStatus=" + ps.installStatus 2279 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2280 + scannedPkg.mVersionCode); 2281 removePackageLI(scannedPkg, true); 2282 mExpectingBetter.put(ps.name, ps.codePath); 2283 } 2284 2285 continue; 2286 } 2287 2288 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2289 psit.remove(); 2290 logCriticalInfo(Log.WARN, "System package " + ps.name 2291 + " no longer exists; wiping its data"); 2292 removeDataDirsLI(null, ps.name); 2293 } else { 2294 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2295 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2296 possiblyDeletedUpdatedSystemApps.add(ps.name); 2297 } 2298 } 2299 } 2300 } 2301 2302 //look for any incomplete package installations 2303 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2304 //clean up list 2305 for(int i = 0; i < deletePkgsList.size(); i++) { 2306 //clean up here 2307 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2308 } 2309 //delete tmp files 2310 deleteTempPackageFiles(); 2311 2312 // Remove any shared userIDs that have no associated packages 2313 mSettings.pruneSharedUsersLPw(); 2314 2315 if (!mOnlyCore) { 2316 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2317 SystemClock.uptimeMillis()); 2318 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2319 2320 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2321 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2322 2323 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2324 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2325 2326 /** 2327 * Remove disable package settings for any updated system 2328 * apps that were removed via an OTA. If they're not a 2329 * previously-updated app, remove them completely. 2330 * Otherwise, just revoke their system-level permissions. 2331 */ 2332 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2333 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2334 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2335 2336 String msg; 2337 if (deletedPkg == null) { 2338 msg = "Updated system package " + deletedAppName 2339 + " no longer exists; wiping its data"; 2340 removeDataDirsLI(null, deletedAppName); 2341 } else { 2342 msg = "Updated system app + " + deletedAppName 2343 + " no longer present; removing system privileges for " 2344 + deletedAppName; 2345 2346 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2347 2348 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2349 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2350 } 2351 logCriticalInfo(Log.WARN, msg); 2352 } 2353 2354 /** 2355 * Make sure all system apps that we expected to appear on 2356 * the userdata partition actually showed up. If they never 2357 * appeared, crawl back and revive the system version. 2358 */ 2359 for (int i = 0; i < mExpectingBetter.size(); i++) { 2360 final String packageName = mExpectingBetter.keyAt(i); 2361 if (!mPackages.containsKey(packageName)) { 2362 final File scanFile = mExpectingBetter.valueAt(i); 2363 2364 logCriticalInfo(Log.WARN, "Expected better " + packageName 2365 + " but never showed up; reverting to system"); 2366 2367 final int reparseFlags; 2368 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2369 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2370 | PackageParser.PARSE_IS_SYSTEM_DIR 2371 | PackageParser.PARSE_IS_PRIVILEGED; 2372 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2373 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2374 | PackageParser.PARSE_IS_SYSTEM_DIR; 2375 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2376 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2377 | PackageParser.PARSE_IS_SYSTEM_DIR; 2378 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2379 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2380 | PackageParser.PARSE_IS_SYSTEM_DIR; 2381 } else { 2382 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2383 continue; 2384 } 2385 2386 mSettings.enableSystemPackageLPw(packageName); 2387 2388 try { 2389 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2390 } catch (PackageManagerException e) { 2391 Slog.e(TAG, "Failed to parse original system package: " 2392 + e.getMessage()); 2393 } 2394 } 2395 } 2396 } 2397 mExpectingBetter.clear(); 2398 2399 // Now that we know all of the shared libraries, update all clients to have 2400 // the correct library paths. 2401 updateAllSharedLibrariesLPw(); 2402 2403 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2404 // NOTE: We ignore potential failures here during a system scan (like 2405 // the rest of the commands above) because there's precious little we 2406 // can do about it. A settings error is reported, though. 2407 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2408 false /* boot complete */); 2409 } 2410 2411 // Now that we know all the packages we are keeping, 2412 // read and update their last usage times. 2413 mPackageUsage.readLP(); 2414 2415 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2416 SystemClock.uptimeMillis()); 2417 Slog.i(TAG, "Time to scan packages: " 2418 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2419 + " seconds"); 2420 2421 // If the platform SDK has changed since the last time we booted, 2422 // we need to re-grant app permission to catch any new ones that 2423 // appear. This is really a hack, and means that apps can in some 2424 // cases get permissions that the user didn't initially explicitly 2425 // allow... it would be nice to have some better way to handle 2426 // this situation. 2427 int updateFlags = UPDATE_PERMISSIONS_ALL; 2428 if (ver.sdkVersion != mSdkVersion) { 2429 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2430 + mSdkVersion + "; regranting permissions for internal storage"); 2431 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2432 } 2433 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2434 ver.sdkVersion = mSdkVersion; 2435 2436 // If this is the first boot or an update from pre-M, and it is a normal 2437 // boot, then we need to initialize the default preferred apps across 2438 // all defined users. 2439 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2440 for (UserInfo user : sUserManager.getUsers(true)) { 2441 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2442 applyFactoryDefaultBrowserLPw(user.id); 2443 primeDomainVerificationsLPw(user.id); 2444 } 2445 } 2446 2447 // Prepare storage for system user really early during boot, 2448 // since core system apps like SettingsProvider and SystemUI 2449 // can't wait for user to start 2450 final int storageFlags; 2451 if (StorageManager.isFileBasedEncryptionEnabled()) { 2452 storageFlags = StorageManager.FLAG_STORAGE_DE; 2453 } else { 2454 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2455 } 2456 reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2457 storageFlags); 2458 2459 // If this is first boot after an OTA, and a normal boot, then 2460 // we need to clear code cache directories. 2461 if (mIsUpgrade && !onlyCore) { 2462 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2463 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2464 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2465 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2466 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2467 } 2468 } 2469 ver.fingerprint = Build.FINGERPRINT; 2470 } 2471 2472 checkDefaultBrowser(); 2473 2474 // clear only after permissions and other defaults have been updated 2475 mExistingSystemPackages.clear(); 2476 mPromoteSystemApps = false; 2477 2478 // All the changes are done during package scanning. 2479 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2480 2481 // can downgrade to reader 2482 mSettings.writeLPr(); 2483 2484 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2485 SystemClock.uptimeMillis()); 2486 2487 if (!mOnlyCore) { 2488 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2489 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2490 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2491 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2492 mIntentFilterVerifierComponent); 2493 } else { 2494 mRequiredVerifierPackage = null; 2495 mRequiredInstallerPackage = null; 2496 mIntentFilterVerifierComponent = null; 2497 mIntentFilterVerifier = null; 2498 } 2499 2500 mInstallerService = new PackageInstallerService(context, this); 2501 2502 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2503 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2504 // both the installer and resolver must be present to enable ephemeral 2505 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2506 if (DEBUG_EPHEMERAL) { 2507 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2508 + " installer:" + ephemeralInstallerComponent); 2509 } 2510 mEphemeralResolverComponent = ephemeralResolverComponent; 2511 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2512 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2513 mEphemeralResolverConnection = 2514 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2515 } else { 2516 if (DEBUG_EPHEMERAL) { 2517 final String missingComponent = 2518 (ephemeralResolverComponent == null) 2519 ? (ephemeralInstallerComponent == null) 2520 ? "resolver and installer" 2521 : "resolver" 2522 : "installer"; 2523 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2524 } 2525 mEphemeralResolverComponent = null; 2526 mEphemeralInstallerComponent = null; 2527 mEphemeralResolverConnection = null; 2528 } 2529 2530 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2531 } // synchronized (mPackages) 2532 } // synchronized (mInstallLock) 2533 2534 // Now after opening every single application zip, make sure they 2535 // are all flushed. Not really needed, but keeps things nice and 2536 // tidy. 2537 Runtime.getRuntime().gc(); 2538 2539 // The initial scanning above does many calls into installd while 2540 // holding the mPackages lock, but we're mostly interested in yelling 2541 // once we have a booted system. 2542 mInstaller.setWarnIfHeld(mPackages); 2543 2544 // Expose private service for system components to use. 2545 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2546 } 2547 2548 @Override 2549 public boolean isFirstBoot() { 2550 return !mRestoredSettings; 2551 } 2552 2553 @Override 2554 public boolean isOnlyCoreApps() { 2555 return mOnlyCore; 2556 } 2557 2558 @Override 2559 public boolean isUpgrade() { 2560 return mIsUpgrade; 2561 } 2562 2563 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2564 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2565 2566 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2567 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2568 if (matches.size() == 1) { 2569 return matches.get(0).getComponentInfo().packageName; 2570 } else { 2571 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2572 return null; 2573 } 2574 } 2575 2576 private @NonNull String getRequiredInstallerLPr() { 2577 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2578 intent.addCategory(Intent.CATEGORY_DEFAULT); 2579 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2580 2581 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2582 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2583 if (matches.size() == 1) { 2584 return matches.get(0).getComponentInfo().packageName; 2585 } else { 2586 throw new RuntimeException("There must be exactly one installer; found " + matches); 2587 } 2588 } 2589 2590 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2591 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2592 2593 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2594 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2595 ResolveInfo best = null; 2596 final int N = matches.size(); 2597 for (int i = 0; i < N; i++) { 2598 final ResolveInfo cur = matches.get(i); 2599 final String packageName = cur.getComponentInfo().packageName; 2600 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2601 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2602 continue; 2603 } 2604 2605 if (best == null || cur.priority > best.priority) { 2606 best = cur; 2607 } 2608 } 2609 2610 if (best != null) { 2611 return best.getComponentInfo().getComponentName(); 2612 } else { 2613 throw new RuntimeException("There must be at least one intent filter verifier"); 2614 } 2615 } 2616 2617 private @Nullable ComponentName getEphemeralResolverLPr() { 2618 final String[] packageArray = 2619 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2620 if (packageArray.length == 0) { 2621 if (DEBUG_EPHEMERAL) { 2622 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2623 } 2624 return null; 2625 } 2626 2627 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2628 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2629 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2630 2631 final int N = resolvers.size(); 2632 if (N == 0) { 2633 if (DEBUG_EPHEMERAL) { 2634 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2635 } 2636 return null; 2637 } 2638 2639 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2640 for (int i = 0; i < N; i++) { 2641 final ResolveInfo info = resolvers.get(i); 2642 2643 if (info.serviceInfo == null) { 2644 continue; 2645 } 2646 2647 final String packageName = info.serviceInfo.packageName; 2648 if (!possiblePackages.contains(packageName)) { 2649 if (DEBUG_EPHEMERAL) { 2650 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2651 + " pkg: " + packageName + ", info:" + info); 2652 } 2653 continue; 2654 } 2655 2656 if (DEBUG_EPHEMERAL) { 2657 Slog.v(TAG, "Ephemeral resolver found;" 2658 + " pkg: " + packageName + ", info:" + info); 2659 } 2660 return new ComponentName(packageName, info.serviceInfo.name); 2661 } 2662 if (DEBUG_EPHEMERAL) { 2663 Slog.v(TAG, "Ephemeral resolver NOT found"); 2664 } 2665 return null; 2666 } 2667 2668 private @Nullable ComponentName getEphemeralInstallerLPr() { 2669 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2670 intent.addCategory(Intent.CATEGORY_DEFAULT); 2671 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2672 2673 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2674 MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM); 2675 if (matches.size() == 0) { 2676 return null; 2677 } else if (matches.size() == 1) { 2678 return matches.get(0).getComponentInfo().getComponentName(); 2679 } else { 2680 throw new RuntimeException( 2681 "There must be at most one ephemeral installer; found " + matches); 2682 } 2683 } 2684 2685 private void primeDomainVerificationsLPw(int userId) { 2686 if (DEBUG_DOMAIN_VERIFICATION) { 2687 Slog.d(TAG, "Priming domain verifications in user " + userId); 2688 } 2689 2690 SystemConfig systemConfig = SystemConfig.getInstance(); 2691 ArraySet<String> packages = systemConfig.getLinkedApps(); 2692 ArraySet<String> domains = new ArraySet<String>(); 2693 2694 for (String packageName : packages) { 2695 PackageParser.Package pkg = mPackages.get(packageName); 2696 if (pkg != null) { 2697 if (!pkg.isSystemApp()) { 2698 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2699 continue; 2700 } 2701 2702 domains.clear(); 2703 for (PackageParser.Activity a : pkg.activities) { 2704 for (ActivityIntentInfo filter : a.intents) { 2705 if (hasValidDomains(filter)) { 2706 domains.addAll(filter.getHostsList()); 2707 } 2708 } 2709 } 2710 2711 if (domains.size() > 0) { 2712 if (DEBUG_DOMAIN_VERIFICATION) { 2713 Slog.v(TAG, " + " + packageName); 2714 } 2715 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2716 // state w.r.t. the formal app-linkage "no verification attempted" state; 2717 // and then 'always' in the per-user state actually used for intent resolution. 2718 final IntentFilterVerificationInfo ivi; 2719 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2720 new ArrayList<String>(domains)); 2721 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2722 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2723 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2724 } else { 2725 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2726 + "' does not handle web links"); 2727 } 2728 } else { 2729 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2730 } 2731 } 2732 2733 scheduleWritePackageRestrictionsLocked(userId); 2734 scheduleWriteSettingsLocked(); 2735 } 2736 2737 private void applyFactoryDefaultBrowserLPw(int userId) { 2738 // The default browser app's package name is stored in a string resource, 2739 // with a product-specific overlay used for vendor customization. 2740 String browserPkg = mContext.getResources().getString( 2741 com.android.internal.R.string.default_browser); 2742 if (!TextUtils.isEmpty(browserPkg)) { 2743 // non-empty string => required to be a known package 2744 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2745 if (ps == null) { 2746 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2747 browserPkg = null; 2748 } else { 2749 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2750 } 2751 } 2752 2753 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2754 // default. If there's more than one, just leave everything alone. 2755 if (browserPkg == null) { 2756 calculateDefaultBrowserLPw(userId); 2757 } 2758 } 2759 2760 private void calculateDefaultBrowserLPw(int userId) { 2761 List<String> allBrowsers = resolveAllBrowserApps(userId); 2762 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2763 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2764 } 2765 2766 private List<String> resolveAllBrowserApps(int userId) { 2767 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2768 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2769 PackageManager.MATCH_ALL, userId); 2770 2771 final int count = list.size(); 2772 List<String> result = new ArrayList<String>(count); 2773 for (int i=0; i<count; i++) { 2774 ResolveInfo info = list.get(i); 2775 if (info.activityInfo == null 2776 || !info.handleAllWebDataURI 2777 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2778 || result.contains(info.activityInfo.packageName)) { 2779 continue; 2780 } 2781 result.add(info.activityInfo.packageName); 2782 } 2783 2784 return result; 2785 } 2786 2787 private boolean packageIsBrowser(String packageName, int userId) { 2788 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2789 PackageManager.MATCH_ALL, userId); 2790 final int N = list.size(); 2791 for (int i = 0; i < N; i++) { 2792 ResolveInfo info = list.get(i); 2793 if (packageName.equals(info.activityInfo.packageName)) { 2794 return true; 2795 } 2796 } 2797 return false; 2798 } 2799 2800 private void checkDefaultBrowser() { 2801 final int myUserId = UserHandle.myUserId(); 2802 final String packageName = getDefaultBrowserPackageName(myUserId); 2803 if (packageName != null) { 2804 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2805 if (info == null) { 2806 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2807 synchronized (mPackages) { 2808 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2809 } 2810 } 2811 } 2812 } 2813 2814 @Override 2815 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2816 throws RemoteException { 2817 try { 2818 return super.onTransact(code, data, reply, flags); 2819 } catch (RuntimeException e) { 2820 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2821 Slog.wtf(TAG, "Package Manager Crash", e); 2822 } 2823 throw e; 2824 } 2825 } 2826 2827 void cleanupInstallFailedPackage(PackageSetting ps) { 2828 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2829 2830 removeDataDirsLI(ps.volumeUuid, ps.name); 2831 if (ps.codePath != null) { 2832 removeCodePathLI(ps.codePath); 2833 } 2834 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2835 if (ps.resourcePath.isDirectory()) { 2836 FileUtils.deleteContents(ps.resourcePath); 2837 } 2838 ps.resourcePath.delete(); 2839 } 2840 mSettings.removePackageLPw(ps.name); 2841 } 2842 2843 static int[] appendInts(int[] cur, int[] add) { 2844 if (add == null) return cur; 2845 if (cur == null) return add; 2846 final int N = add.length; 2847 for (int i=0; i<N; i++) { 2848 cur = appendInt(cur, add[i]); 2849 } 2850 return cur; 2851 } 2852 2853 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2854 if (!sUserManager.exists(userId)) return null; 2855 final PackageSetting ps = (PackageSetting) p.mExtras; 2856 if (ps == null) { 2857 return null; 2858 } 2859 2860 final PermissionsState permissionsState = ps.getPermissionsState(); 2861 2862 final int[] gids = permissionsState.computeGids(userId); 2863 final Set<String> permissions = permissionsState.getPermissions(userId); 2864 final PackageUserState state = ps.readUserState(userId); 2865 2866 return PackageParser.generatePackageInfo(p, gids, flags, 2867 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2868 } 2869 2870 @Override 2871 public void checkPackageStartable(String packageName, int userId) { 2872 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 2873 2874 synchronized (mPackages) { 2875 final PackageSetting ps = mSettings.mPackages.get(packageName); 2876 if (ps == null) { 2877 throw new SecurityException("Package " + packageName + " was not found!"); 2878 } 2879 2880 if (mSafeMode && !ps.isSystem()) { 2881 throw new SecurityException("Package " + packageName + " not a system app!"); 2882 } 2883 2884 if (ps.frozen) { 2885 throw new SecurityException("Package " + packageName + " is currently frozen!"); 2886 } 2887 2888 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware() 2889 || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) { 2890 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 2891 } 2892 } 2893 } 2894 2895 @Override 2896 public boolean isPackageAvailable(String packageName, int userId) { 2897 if (!sUserManager.exists(userId)) return false; 2898 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2899 false /* requireFullPermission */, false /* checkShell */, "is package available"); 2900 synchronized (mPackages) { 2901 PackageParser.Package p = mPackages.get(packageName); 2902 if (p != null) { 2903 final PackageSetting ps = (PackageSetting) p.mExtras; 2904 if (ps != null) { 2905 final PackageUserState state = ps.readUserState(userId); 2906 if (state != null) { 2907 return PackageParser.isAvailable(state); 2908 } 2909 } 2910 } 2911 } 2912 return false; 2913 } 2914 2915 @Override 2916 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2917 if (!sUserManager.exists(userId)) return null; 2918 flags = updateFlagsForPackage(flags, userId, packageName); 2919 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2920 false /* requireFullPermission */, false /* checkShell */, "get package info"); 2921 // reader 2922 synchronized (mPackages) { 2923 PackageParser.Package p = mPackages.get(packageName); 2924 if (DEBUG_PACKAGE_INFO) 2925 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2926 if (p != null) { 2927 return generatePackageInfo(p, flags, userId); 2928 } 2929 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2930 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2931 } 2932 } 2933 return null; 2934 } 2935 2936 @Override 2937 public String[] currentToCanonicalPackageNames(String[] names) { 2938 String[] out = new String[names.length]; 2939 // reader 2940 synchronized (mPackages) { 2941 for (int i=names.length-1; i>=0; i--) { 2942 PackageSetting ps = mSettings.mPackages.get(names[i]); 2943 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2944 } 2945 } 2946 return out; 2947 } 2948 2949 @Override 2950 public String[] canonicalToCurrentPackageNames(String[] names) { 2951 String[] out = new String[names.length]; 2952 // reader 2953 synchronized (mPackages) { 2954 for (int i=names.length-1; i>=0; i--) { 2955 String cur = mSettings.mRenamedPackages.get(names[i]); 2956 out[i] = cur != null ? cur : names[i]; 2957 } 2958 } 2959 return out; 2960 } 2961 2962 @Override 2963 public int getPackageUid(String packageName, int flags, int userId) { 2964 if (!sUserManager.exists(userId)) return -1; 2965 flags = updateFlagsForPackage(flags, userId, packageName); 2966 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2967 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 2968 2969 // reader 2970 synchronized (mPackages) { 2971 final PackageParser.Package p = mPackages.get(packageName); 2972 if (p != null && p.isMatch(flags)) { 2973 return UserHandle.getUid(userId, p.applicationInfo.uid); 2974 } 2975 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 2976 final PackageSetting ps = mSettings.mPackages.get(packageName); 2977 if (ps != null && ps.isMatch(flags)) { 2978 return UserHandle.getUid(userId, ps.appId); 2979 } 2980 } 2981 } 2982 2983 return -1; 2984 } 2985 2986 @Override 2987 public int[] getPackageGids(String packageName, int flags, int userId) { 2988 if (!sUserManager.exists(userId)) return null; 2989 flags = updateFlagsForPackage(flags, userId, packageName); 2990 enforceCrossUserPermission(Binder.getCallingUid(), userId, 2991 false /* requireFullPermission */, false /* checkShell */, 2992 "getPackageGids"); 2993 2994 // reader 2995 synchronized (mPackages) { 2996 final PackageParser.Package p = mPackages.get(packageName); 2997 if (p != null && p.isMatch(flags)) { 2998 PackageSetting ps = (PackageSetting) p.mExtras; 2999 return ps.getPermissionsState().computeGids(userId); 3000 } 3001 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3002 final PackageSetting ps = mSettings.mPackages.get(packageName); 3003 if (ps != null && ps.isMatch(flags)) { 3004 return ps.getPermissionsState().computeGids(userId); 3005 } 3006 } 3007 } 3008 3009 return null; 3010 } 3011 3012 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3013 if (bp.perm != null) { 3014 return PackageParser.generatePermissionInfo(bp.perm, flags); 3015 } 3016 PermissionInfo pi = new PermissionInfo(); 3017 pi.name = bp.name; 3018 pi.packageName = bp.sourcePackage; 3019 pi.nonLocalizedLabel = bp.name; 3020 pi.protectionLevel = bp.protectionLevel; 3021 return pi; 3022 } 3023 3024 @Override 3025 public PermissionInfo getPermissionInfo(String name, int flags) { 3026 // reader 3027 synchronized (mPackages) { 3028 final BasePermission p = mSettings.mPermissions.get(name); 3029 if (p != null) { 3030 return generatePermissionInfo(p, flags); 3031 } 3032 return null; 3033 } 3034 } 3035 3036 @Override 3037 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3038 int flags) { 3039 // reader 3040 synchronized (mPackages) { 3041 if (group != null && !mPermissionGroups.containsKey(group)) { 3042 // This is thrown as NameNotFoundException 3043 return null; 3044 } 3045 3046 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3047 for (BasePermission p : mSettings.mPermissions.values()) { 3048 if (group == null) { 3049 if (p.perm == null || p.perm.info.group == null) { 3050 out.add(generatePermissionInfo(p, flags)); 3051 } 3052 } else { 3053 if (p.perm != null && group.equals(p.perm.info.group)) { 3054 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3055 } 3056 } 3057 } 3058 return new ParceledListSlice<>(out); 3059 } 3060 } 3061 3062 @Override 3063 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3064 // reader 3065 synchronized (mPackages) { 3066 return PackageParser.generatePermissionGroupInfo( 3067 mPermissionGroups.get(name), flags); 3068 } 3069 } 3070 3071 @Override 3072 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3073 // reader 3074 synchronized (mPackages) { 3075 final int N = mPermissionGroups.size(); 3076 ArrayList<PermissionGroupInfo> out 3077 = new ArrayList<PermissionGroupInfo>(N); 3078 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3079 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3080 } 3081 return new ParceledListSlice<>(out); 3082 } 3083 } 3084 3085 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3086 int userId) { 3087 if (!sUserManager.exists(userId)) return null; 3088 PackageSetting ps = mSettings.mPackages.get(packageName); 3089 if (ps != null) { 3090 if (ps.pkg == null) { 3091 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 3092 flags, userId); 3093 if (pInfo != null) { 3094 return pInfo.applicationInfo; 3095 } 3096 return null; 3097 } 3098 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3099 ps.readUserState(userId), userId); 3100 } 3101 return null; 3102 } 3103 3104 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 3105 int userId) { 3106 if (!sUserManager.exists(userId)) return null; 3107 PackageSetting ps = mSettings.mPackages.get(packageName); 3108 if (ps != null) { 3109 PackageParser.Package pkg = ps.pkg; 3110 if (pkg == null) { 3111 if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) { 3112 return null; 3113 } 3114 // Only data remains, so we aren't worried about code paths 3115 pkg = new PackageParser.Package(packageName); 3116 pkg.applicationInfo.packageName = packageName; 3117 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 3118 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 3119 pkg.applicationInfo.uid = ps.appId; 3120 pkg.applicationInfo.initForUser(userId); 3121 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 3122 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 3123 } 3124 return generatePackageInfo(pkg, flags, userId); 3125 } 3126 return null; 3127 } 3128 3129 @Override 3130 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3131 if (!sUserManager.exists(userId)) return null; 3132 flags = updateFlagsForApplication(flags, userId, packageName); 3133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3134 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3135 // writer 3136 synchronized (mPackages) { 3137 PackageParser.Package p = mPackages.get(packageName); 3138 if (DEBUG_PACKAGE_INFO) Log.v( 3139 TAG, "getApplicationInfo " + packageName 3140 + ": " + p); 3141 if (p != null) { 3142 PackageSetting ps = mSettings.mPackages.get(packageName); 3143 if (ps == null) return null; 3144 // Note: isEnabledLP() does not apply here - always return info 3145 return PackageParser.generateApplicationInfo( 3146 p, flags, ps.readUserState(userId), userId); 3147 } 3148 if ("android".equals(packageName)||"system".equals(packageName)) { 3149 return mAndroidApplication; 3150 } 3151 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3152 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3153 } 3154 } 3155 return null; 3156 } 3157 3158 @Override 3159 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3160 final IPackageDataObserver observer) { 3161 mContext.enforceCallingOrSelfPermission( 3162 android.Manifest.permission.CLEAR_APP_CACHE, null); 3163 // Queue up an async operation since clearing cache may take a little while. 3164 mHandler.post(new Runnable() { 3165 public void run() { 3166 mHandler.removeCallbacks(this); 3167 boolean success = true; 3168 synchronized (mInstallLock) { 3169 try { 3170 mInstaller.freeCache(volumeUuid, freeStorageSize); 3171 } catch (InstallerException e) { 3172 Slog.w(TAG, "Couldn't clear application caches: " + e); 3173 success = false; 3174 } 3175 } 3176 if (observer != null) { 3177 try { 3178 observer.onRemoveCompleted(null, success); 3179 } catch (RemoteException e) { 3180 Slog.w(TAG, "RemoveException when invoking call back"); 3181 } 3182 } 3183 } 3184 }); 3185 } 3186 3187 @Override 3188 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3189 final IntentSender pi) { 3190 mContext.enforceCallingOrSelfPermission( 3191 android.Manifest.permission.CLEAR_APP_CACHE, null); 3192 // Queue up an async operation since clearing cache may take a little while. 3193 mHandler.post(new Runnable() { 3194 public void run() { 3195 mHandler.removeCallbacks(this); 3196 boolean success = true; 3197 synchronized (mInstallLock) { 3198 try { 3199 mInstaller.freeCache(volumeUuid, freeStorageSize); 3200 } catch (InstallerException e) { 3201 Slog.w(TAG, "Couldn't clear application caches: " + e); 3202 success = false; 3203 } 3204 } 3205 if(pi != null) { 3206 try { 3207 // Callback via pending intent 3208 int code = success ? 1 : 0; 3209 pi.sendIntent(null, code, null, 3210 null, null); 3211 } catch (SendIntentException e1) { 3212 Slog.i(TAG, "Failed to send pending intent"); 3213 } 3214 } 3215 } 3216 }); 3217 } 3218 3219 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3220 synchronized (mInstallLock) { 3221 try { 3222 mInstaller.freeCache(volumeUuid, freeStorageSize); 3223 } catch (InstallerException e) { 3224 throw new IOException("Failed to free enough space", e); 3225 } 3226 } 3227 } 3228 3229 /** 3230 * Return if the user key is currently unlocked. 3231 */ 3232 private boolean isUserKeyUnlocked(int userId) { 3233 if (StorageManager.isFileBasedEncryptionEnabled()) { 3234 final IMountService mount = IMountService.Stub 3235 .asInterface(ServiceManager.getService("mount")); 3236 if (mount == null) { 3237 Slog.w(TAG, "Early during boot, assuming locked"); 3238 return false; 3239 } 3240 final long token = Binder.clearCallingIdentity(); 3241 try { 3242 return mount.isUserKeyUnlocked(userId); 3243 } catch (RemoteException e) { 3244 throw e.rethrowAsRuntimeException(); 3245 } finally { 3246 Binder.restoreCallingIdentity(token); 3247 } 3248 } else { 3249 return true; 3250 } 3251 } 3252 3253 /** 3254 * Update given flags based on encryption status of current user. 3255 */ 3256 private int updateFlags(int flags, int userId) { 3257 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3258 | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) { 3259 // Caller expressed an explicit opinion about what encryption 3260 // aware/unaware components they want to see, so fall through and 3261 // give them what they want 3262 } else { 3263 // Caller expressed no opinion, so match based on user state 3264 if (isUserKeyUnlocked(userId)) { 3265 flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE; 3266 } else { 3267 flags |= PackageManager.MATCH_ENCRYPTION_AWARE; 3268 } 3269 } 3270 return flags; 3271 } 3272 3273 /** 3274 * Update given flags when being used to request {@link PackageInfo}. 3275 */ 3276 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3277 boolean triaged = true; 3278 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3279 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3280 // Caller is asking for component details, so they'd better be 3281 // asking for specific encryption matching behavior, or be triaged 3282 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3283 | PackageManager.MATCH_ENCRYPTION_AWARE 3284 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3285 triaged = false; 3286 } 3287 } 3288 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3289 | PackageManager.MATCH_SYSTEM_ONLY 3290 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3291 triaged = false; 3292 } 3293 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3294 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3295 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3296 } 3297 return updateFlags(flags, userId); 3298 } 3299 3300 /** 3301 * Update given flags when being used to request {@link ApplicationInfo}. 3302 */ 3303 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3304 return updateFlagsForPackage(flags, userId, cookie); 3305 } 3306 3307 /** 3308 * Update given flags when being used to request {@link ComponentInfo}. 3309 */ 3310 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3311 if (cookie instanceof Intent) { 3312 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3313 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3314 } 3315 } 3316 3317 boolean triaged = true; 3318 // Caller is asking for component details, so they'd better be 3319 // asking for specific encryption matching behavior, or be triaged 3320 if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE 3321 | PackageManager.MATCH_ENCRYPTION_AWARE 3322 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3323 triaged = false; 3324 } 3325 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3326 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3327 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3328 } 3329 3330 return updateFlags(flags, userId); 3331 } 3332 3333 /** 3334 * Update given flags when being used to request {@link ResolveInfo}. 3335 */ 3336 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3337 // Safe mode means we shouldn't match any third-party components 3338 if (mSafeMode) { 3339 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3340 } 3341 3342 return updateFlagsForComponent(flags, userId, cookie); 3343 } 3344 3345 @Override 3346 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3347 if (!sUserManager.exists(userId)) return null; 3348 flags = updateFlagsForComponent(flags, userId, component); 3349 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3350 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3351 synchronized (mPackages) { 3352 PackageParser.Activity a = mActivities.mActivities.get(component); 3353 3354 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3355 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3357 if (ps == null) return null; 3358 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3359 userId); 3360 } 3361 if (mResolveComponentName.equals(component)) { 3362 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3363 new PackageUserState(), userId); 3364 } 3365 } 3366 return null; 3367 } 3368 3369 @Override 3370 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3371 String resolvedType) { 3372 synchronized (mPackages) { 3373 if (component.equals(mResolveComponentName)) { 3374 // The resolver supports EVERYTHING! 3375 return true; 3376 } 3377 PackageParser.Activity a = mActivities.mActivities.get(component); 3378 if (a == null) { 3379 return false; 3380 } 3381 for (int i=0; i<a.intents.size(); i++) { 3382 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3383 intent.getData(), intent.getCategories(), TAG) >= 0) { 3384 return true; 3385 } 3386 } 3387 return false; 3388 } 3389 } 3390 3391 @Override 3392 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3393 if (!sUserManager.exists(userId)) return null; 3394 flags = updateFlagsForComponent(flags, userId, component); 3395 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3396 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3397 synchronized (mPackages) { 3398 PackageParser.Activity a = mReceivers.mActivities.get(component); 3399 if (DEBUG_PACKAGE_INFO) Log.v( 3400 TAG, "getReceiverInfo " + component + ": " + a); 3401 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3402 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3403 if (ps == null) return null; 3404 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3405 userId); 3406 } 3407 } 3408 return null; 3409 } 3410 3411 @Override 3412 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3413 if (!sUserManager.exists(userId)) return null; 3414 flags = updateFlagsForComponent(flags, userId, component); 3415 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3416 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3417 synchronized (mPackages) { 3418 PackageParser.Service s = mServices.mServices.get(component); 3419 if (DEBUG_PACKAGE_INFO) Log.v( 3420 TAG, "getServiceInfo " + component + ": " + s); 3421 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3422 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3423 if (ps == null) return null; 3424 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3425 userId); 3426 } 3427 } 3428 return null; 3429 } 3430 3431 @Override 3432 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3433 if (!sUserManager.exists(userId)) return null; 3434 flags = updateFlagsForComponent(flags, userId, component); 3435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3436 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3437 synchronized (mPackages) { 3438 PackageParser.Provider p = mProviders.mProviders.get(component); 3439 if (DEBUG_PACKAGE_INFO) Log.v( 3440 TAG, "getProviderInfo " + component + ": " + p); 3441 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3442 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3443 if (ps == null) return null; 3444 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3445 userId); 3446 } 3447 } 3448 return null; 3449 } 3450 3451 @Override 3452 public String[] getSystemSharedLibraryNames() { 3453 Set<String> libSet; 3454 synchronized (mPackages) { 3455 libSet = mSharedLibraries.keySet(); 3456 int size = libSet.size(); 3457 if (size > 0) { 3458 String[] libs = new String[size]; 3459 libSet.toArray(libs); 3460 return libs; 3461 } 3462 } 3463 return null; 3464 } 3465 3466 @Override 3467 public @Nullable String getServicesSystemSharedLibraryPackageName() { 3468 synchronized (mPackages) { 3469 SharedLibraryEntry libraryEntry = mSharedLibraries.get( 3470 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 3471 if (libraryEntry != null) { 3472 return libraryEntry.apk; 3473 } 3474 } 3475 return null; 3476 } 3477 3478 @Override 3479 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3480 synchronized (mPackages) { 3481 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3482 3483 final FeatureInfo fi = new FeatureInfo(); 3484 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3485 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3486 res.add(fi); 3487 3488 return new ParceledListSlice<>(res); 3489 } 3490 } 3491 3492 @Override 3493 public boolean hasSystemFeature(String name, int version) { 3494 synchronized (mPackages) { 3495 final FeatureInfo feat = mAvailableFeatures.get(name); 3496 if (feat == null) { 3497 return false; 3498 } else { 3499 return feat.version >= version; 3500 } 3501 } 3502 } 3503 3504 @Override 3505 public int checkPermission(String permName, String pkgName, int userId) { 3506 if (!sUserManager.exists(userId)) { 3507 return PackageManager.PERMISSION_DENIED; 3508 } 3509 3510 synchronized (mPackages) { 3511 final PackageParser.Package p = mPackages.get(pkgName); 3512 if (p != null && p.mExtras != null) { 3513 final PackageSetting ps = (PackageSetting) p.mExtras; 3514 final PermissionsState permissionsState = ps.getPermissionsState(); 3515 if (permissionsState.hasPermission(permName, userId)) { 3516 return PackageManager.PERMISSION_GRANTED; 3517 } 3518 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3519 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3520 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3521 return PackageManager.PERMISSION_GRANTED; 3522 } 3523 } 3524 } 3525 3526 return PackageManager.PERMISSION_DENIED; 3527 } 3528 3529 @Override 3530 public int checkUidPermission(String permName, int uid) { 3531 final int userId = UserHandle.getUserId(uid); 3532 3533 if (!sUserManager.exists(userId)) { 3534 return PackageManager.PERMISSION_DENIED; 3535 } 3536 3537 synchronized (mPackages) { 3538 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3539 if (obj != null) { 3540 final SettingBase ps = (SettingBase) obj; 3541 final PermissionsState permissionsState = ps.getPermissionsState(); 3542 if (permissionsState.hasPermission(permName, userId)) { 3543 return PackageManager.PERMISSION_GRANTED; 3544 } 3545 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3546 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3547 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3548 return PackageManager.PERMISSION_GRANTED; 3549 } 3550 } else { 3551 ArraySet<String> perms = mSystemPermissions.get(uid); 3552 if (perms != null) { 3553 if (perms.contains(permName)) { 3554 return PackageManager.PERMISSION_GRANTED; 3555 } 3556 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3557 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3558 return PackageManager.PERMISSION_GRANTED; 3559 } 3560 } 3561 } 3562 } 3563 3564 return PackageManager.PERMISSION_DENIED; 3565 } 3566 3567 @Override 3568 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3569 if (UserHandle.getCallingUserId() != userId) { 3570 mContext.enforceCallingPermission( 3571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3572 "isPermissionRevokedByPolicy for user " + userId); 3573 } 3574 3575 if (checkPermission(permission, packageName, userId) 3576 == PackageManager.PERMISSION_GRANTED) { 3577 return false; 3578 } 3579 3580 final long identity = Binder.clearCallingIdentity(); 3581 try { 3582 final int flags = getPermissionFlags(permission, packageName, userId); 3583 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3584 } finally { 3585 Binder.restoreCallingIdentity(identity); 3586 } 3587 } 3588 3589 @Override 3590 public String getPermissionControllerPackageName() { 3591 synchronized (mPackages) { 3592 return mRequiredInstallerPackage; 3593 } 3594 } 3595 3596 /** 3597 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3598 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3599 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3600 * @param message the message to log on security exception 3601 */ 3602 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3603 boolean checkShell, String message) { 3604 if (userId < 0) { 3605 throw new IllegalArgumentException("Invalid userId " + userId); 3606 } 3607 if (checkShell) { 3608 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3609 } 3610 if (userId == UserHandle.getUserId(callingUid)) return; 3611 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3612 if (requireFullPermission) { 3613 mContext.enforceCallingOrSelfPermission( 3614 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3615 } else { 3616 try { 3617 mContext.enforceCallingOrSelfPermission( 3618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3619 } catch (SecurityException se) { 3620 mContext.enforceCallingOrSelfPermission( 3621 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3622 } 3623 } 3624 } 3625 } 3626 3627 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3628 if (callingUid == Process.SHELL_UID) { 3629 if (userHandle >= 0 3630 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3631 throw new SecurityException("Shell does not have permission to access user " 3632 + userHandle); 3633 } else if (userHandle < 0) { 3634 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3635 + Debug.getCallers(3)); 3636 } 3637 } 3638 } 3639 3640 private BasePermission findPermissionTreeLP(String permName) { 3641 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3642 if (permName.startsWith(bp.name) && 3643 permName.length() > bp.name.length() && 3644 permName.charAt(bp.name.length()) == '.') { 3645 return bp; 3646 } 3647 } 3648 return null; 3649 } 3650 3651 private BasePermission checkPermissionTreeLP(String permName) { 3652 if (permName != null) { 3653 BasePermission bp = findPermissionTreeLP(permName); 3654 if (bp != null) { 3655 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3656 return bp; 3657 } 3658 throw new SecurityException("Calling uid " 3659 + Binder.getCallingUid() 3660 + " is not allowed to add to permission tree " 3661 + bp.name + " owned by uid " + bp.uid); 3662 } 3663 } 3664 throw new SecurityException("No permission tree found for " + permName); 3665 } 3666 3667 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3668 if (s1 == null) { 3669 return s2 == null; 3670 } 3671 if (s2 == null) { 3672 return false; 3673 } 3674 if (s1.getClass() != s2.getClass()) { 3675 return false; 3676 } 3677 return s1.equals(s2); 3678 } 3679 3680 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3681 if (pi1.icon != pi2.icon) return false; 3682 if (pi1.logo != pi2.logo) return false; 3683 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3684 if (!compareStrings(pi1.name, pi2.name)) return false; 3685 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3686 // We'll take care of setting this one. 3687 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3688 // These are not currently stored in settings. 3689 //if (!compareStrings(pi1.group, pi2.group)) return false; 3690 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3691 //if (pi1.labelRes != pi2.labelRes) return false; 3692 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3693 return true; 3694 } 3695 3696 int permissionInfoFootprint(PermissionInfo info) { 3697 int size = info.name.length(); 3698 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3699 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3700 return size; 3701 } 3702 3703 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3704 int size = 0; 3705 for (BasePermission perm : mSettings.mPermissions.values()) { 3706 if (perm.uid == tree.uid) { 3707 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3708 } 3709 } 3710 return size; 3711 } 3712 3713 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3714 // We calculate the max size of permissions defined by this uid and throw 3715 // if that plus the size of 'info' would exceed our stated maximum. 3716 if (tree.uid != Process.SYSTEM_UID) { 3717 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3718 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3719 throw new SecurityException("Permission tree size cap exceeded"); 3720 } 3721 } 3722 } 3723 3724 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3725 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3726 throw new SecurityException("Label must be specified in permission"); 3727 } 3728 BasePermission tree = checkPermissionTreeLP(info.name); 3729 BasePermission bp = mSettings.mPermissions.get(info.name); 3730 boolean added = bp == null; 3731 boolean changed = true; 3732 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3733 if (added) { 3734 enforcePermissionCapLocked(info, tree); 3735 bp = new BasePermission(info.name, tree.sourcePackage, 3736 BasePermission.TYPE_DYNAMIC); 3737 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3738 throw new SecurityException( 3739 "Not allowed to modify non-dynamic permission " 3740 + info.name); 3741 } else { 3742 if (bp.protectionLevel == fixedLevel 3743 && bp.perm.owner.equals(tree.perm.owner) 3744 && bp.uid == tree.uid 3745 && comparePermissionInfos(bp.perm.info, info)) { 3746 changed = false; 3747 } 3748 } 3749 bp.protectionLevel = fixedLevel; 3750 info = new PermissionInfo(info); 3751 info.protectionLevel = fixedLevel; 3752 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3753 bp.perm.info.packageName = tree.perm.info.packageName; 3754 bp.uid = tree.uid; 3755 if (added) { 3756 mSettings.mPermissions.put(info.name, bp); 3757 } 3758 if (changed) { 3759 if (!async) { 3760 mSettings.writeLPr(); 3761 } else { 3762 scheduleWriteSettingsLocked(); 3763 } 3764 } 3765 return added; 3766 } 3767 3768 @Override 3769 public boolean addPermission(PermissionInfo info) { 3770 synchronized (mPackages) { 3771 return addPermissionLocked(info, false); 3772 } 3773 } 3774 3775 @Override 3776 public boolean addPermissionAsync(PermissionInfo info) { 3777 synchronized (mPackages) { 3778 return addPermissionLocked(info, true); 3779 } 3780 } 3781 3782 @Override 3783 public void removePermission(String name) { 3784 synchronized (mPackages) { 3785 checkPermissionTreeLP(name); 3786 BasePermission bp = mSettings.mPermissions.get(name); 3787 if (bp != null) { 3788 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3789 throw new SecurityException( 3790 "Not allowed to modify non-dynamic permission " 3791 + name); 3792 } 3793 mSettings.mPermissions.remove(name); 3794 mSettings.writeLPr(); 3795 } 3796 } 3797 } 3798 3799 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3800 BasePermission bp) { 3801 int index = pkg.requestedPermissions.indexOf(bp.name); 3802 if (index == -1) { 3803 throw new SecurityException("Package " + pkg.packageName 3804 + " has not requested permission " + bp.name); 3805 } 3806 if (!bp.isRuntime() && !bp.isDevelopment()) { 3807 throw new SecurityException("Permission " + bp.name 3808 + " is not a changeable permission type"); 3809 } 3810 } 3811 3812 @Override 3813 public void grantRuntimePermission(String packageName, String name, final int userId) { 3814 if (!sUserManager.exists(userId)) { 3815 Log.e(TAG, "No such user:" + userId); 3816 return; 3817 } 3818 3819 mContext.enforceCallingOrSelfPermission( 3820 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3821 "grantRuntimePermission"); 3822 3823 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3824 true /* requireFullPermission */, true /* checkShell */, 3825 "grantRuntimePermission"); 3826 3827 final int uid; 3828 final SettingBase sb; 3829 3830 synchronized (mPackages) { 3831 final PackageParser.Package pkg = mPackages.get(packageName); 3832 if (pkg == null) { 3833 throw new IllegalArgumentException("Unknown package: " + packageName); 3834 } 3835 3836 final BasePermission bp = mSettings.mPermissions.get(name); 3837 if (bp == null) { 3838 throw new IllegalArgumentException("Unknown permission: " + name); 3839 } 3840 3841 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3842 3843 // If a permission review is required for legacy apps we represent 3844 // their permissions as always granted runtime ones since we need 3845 // to keep the review required permission flag per user while an 3846 // install permission's state is shared across all users. 3847 if (Build.PERMISSIONS_REVIEW_REQUIRED 3848 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3849 && bp.isRuntime()) { 3850 return; 3851 } 3852 3853 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3854 sb = (SettingBase) pkg.mExtras; 3855 if (sb == null) { 3856 throw new IllegalArgumentException("Unknown package: " + packageName); 3857 } 3858 3859 final PermissionsState permissionsState = sb.getPermissionsState(); 3860 3861 final int flags = permissionsState.getPermissionFlags(name, userId); 3862 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3863 throw new SecurityException("Cannot grant system fixed permission " 3864 + name + " for package " + packageName); 3865 } 3866 3867 if (bp.isDevelopment()) { 3868 // Development permissions must be handled specially, since they are not 3869 // normal runtime permissions. For now they apply to all users. 3870 if (permissionsState.grantInstallPermission(bp) != 3871 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3872 scheduleWriteSettingsLocked(); 3873 } 3874 return; 3875 } 3876 3877 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 3878 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 3879 return; 3880 } 3881 3882 final int result = permissionsState.grantRuntimePermission(bp, userId); 3883 switch (result) { 3884 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3885 return; 3886 } 3887 3888 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3889 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3890 mHandler.post(new Runnable() { 3891 @Override 3892 public void run() { 3893 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 3894 } 3895 }); 3896 } 3897 break; 3898 } 3899 3900 mOnPermissionChangeListeners.onPermissionsChanged(uid); 3901 3902 // Not critical if that is lost - app has to request again. 3903 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3904 } 3905 3906 // Only need to do this if user is initialized. Otherwise it's a new user 3907 // and there are no processes running as the user yet and there's no need 3908 // to make an expensive call to remount processes for the changed permissions. 3909 if (READ_EXTERNAL_STORAGE.equals(name) 3910 || WRITE_EXTERNAL_STORAGE.equals(name)) { 3911 final long token = Binder.clearCallingIdentity(); 3912 try { 3913 if (sUserManager.isInitialized(userId)) { 3914 MountServiceInternal mountServiceInternal = LocalServices.getService( 3915 MountServiceInternal.class); 3916 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 3917 } 3918 } finally { 3919 Binder.restoreCallingIdentity(token); 3920 } 3921 } 3922 } 3923 3924 @Override 3925 public void revokeRuntimePermission(String packageName, String name, int userId) { 3926 if (!sUserManager.exists(userId)) { 3927 Log.e(TAG, "No such user:" + userId); 3928 return; 3929 } 3930 3931 mContext.enforceCallingOrSelfPermission( 3932 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 3933 "revokeRuntimePermission"); 3934 3935 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3936 true /* requireFullPermission */, true /* checkShell */, 3937 "revokeRuntimePermission"); 3938 3939 final int appId; 3940 3941 synchronized (mPackages) { 3942 final PackageParser.Package pkg = mPackages.get(packageName); 3943 if (pkg == null) { 3944 throw new IllegalArgumentException("Unknown package: " + packageName); 3945 } 3946 3947 final BasePermission bp = mSettings.mPermissions.get(name); 3948 if (bp == null) { 3949 throw new IllegalArgumentException("Unknown permission: " + name); 3950 } 3951 3952 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3953 3954 // If a permission review is required for legacy apps we represent 3955 // their permissions as always granted runtime ones since we need 3956 // to keep the review required permission flag per user while an 3957 // install permission's state is shared across all users. 3958 if (Build.PERMISSIONS_REVIEW_REQUIRED 3959 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3960 && bp.isRuntime()) { 3961 return; 3962 } 3963 3964 SettingBase sb = (SettingBase) pkg.mExtras; 3965 if (sb == null) { 3966 throw new IllegalArgumentException("Unknown package: " + packageName); 3967 } 3968 3969 final PermissionsState permissionsState = sb.getPermissionsState(); 3970 3971 final int flags = permissionsState.getPermissionFlags(name, userId); 3972 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3973 throw new SecurityException("Cannot revoke system fixed permission " 3974 + name + " for package " + packageName); 3975 } 3976 3977 if (bp.isDevelopment()) { 3978 // Development permissions must be handled specially, since they are not 3979 // normal runtime permissions. For now they apply to all users. 3980 if (permissionsState.revokeInstallPermission(bp) != 3981 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3982 scheduleWriteSettingsLocked(); 3983 } 3984 return; 3985 } 3986 3987 if (permissionsState.revokeRuntimePermission(bp, userId) == 3988 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3989 return; 3990 } 3991 3992 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3993 3994 // Critical, after this call app should never have the permission. 3995 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3996 3997 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 3998 } 3999 4000 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4001 } 4002 4003 @Override 4004 public void resetRuntimePermissions() { 4005 mContext.enforceCallingOrSelfPermission( 4006 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4007 "revokeRuntimePermission"); 4008 4009 int callingUid = Binder.getCallingUid(); 4010 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4011 mContext.enforceCallingOrSelfPermission( 4012 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4013 "resetRuntimePermissions"); 4014 } 4015 4016 synchronized (mPackages) { 4017 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4018 for (int userId : UserManagerService.getInstance().getUserIds()) { 4019 final int packageCount = mPackages.size(); 4020 for (int i = 0; i < packageCount; i++) { 4021 PackageParser.Package pkg = mPackages.valueAt(i); 4022 if (!(pkg.mExtras instanceof PackageSetting)) { 4023 continue; 4024 } 4025 PackageSetting ps = (PackageSetting) pkg.mExtras; 4026 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4027 } 4028 } 4029 } 4030 } 4031 4032 @Override 4033 public int getPermissionFlags(String name, String packageName, int userId) { 4034 if (!sUserManager.exists(userId)) { 4035 return 0; 4036 } 4037 4038 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4039 4040 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4041 true /* requireFullPermission */, false /* checkShell */, 4042 "getPermissionFlags"); 4043 4044 synchronized (mPackages) { 4045 final PackageParser.Package pkg = mPackages.get(packageName); 4046 if (pkg == null) { 4047 throw new IllegalArgumentException("Unknown package: " + packageName); 4048 } 4049 4050 final BasePermission bp = mSettings.mPermissions.get(name); 4051 if (bp == null) { 4052 throw new IllegalArgumentException("Unknown permission: " + name); 4053 } 4054 4055 SettingBase sb = (SettingBase) pkg.mExtras; 4056 if (sb == null) { 4057 throw new IllegalArgumentException("Unknown package: " + packageName); 4058 } 4059 4060 PermissionsState permissionsState = sb.getPermissionsState(); 4061 return permissionsState.getPermissionFlags(name, userId); 4062 } 4063 } 4064 4065 @Override 4066 public void updatePermissionFlags(String name, String packageName, int flagMask, 4067 int flagValues, int userId) { 4068 if (!sUserManager.exists(userId)) { 4069 return; 4070 } 4071 4072 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4073 4074 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4075 true /* requireFullPermission */, true /* checkShell */, 4076 "updatePermissionFlags"); 4077 4078 // Only the system can change these flags and nothing else. 4079 if (getCallingUid() != Process.SYSTEM_UID) { 4080 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4081 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4082 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4083 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4084 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4085 } 4086 4087 synchronized (mPackages) { 4088 final PackageParser.Package pkg = mPackages.get(packageName); 4089 if (pkg == null) { 4090 throw new IllegalArgumentException("Unknown package: " + packageName); 4091 } 4092 4093 final BasePermission bp = mSettings.mPermissions.get(name); 4094 if (bp == null) { 4095 throw new IllegalArgumentException("Unknown permission: " + name); 4096 } 4097 4098 SettingBase sb = (SettingBase) pkg.mExtras; 4099 if (sb == null) { 4100 throw new IllegalArgumentException("Unknown package: " + packageName); 4101 } 4102 4103 PermissionsState permissionsState = sb.getPermissionsState(); 4104 4105 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4106 4107 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4108 // Install and runtime permissions are stored in different places, 4109 // so figure out what permission changed and persist the change. 4110 if (permissionsState.getInstallPermissionState(name) != null) { 4111 scheduleWriteSettingsLocked(); 4112 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4113 || hadState) { 4114 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4115 } 4116 } 4117 } 4118 } 4119 4120 /** 4121 * Update the permission flags for all packages and runtime permissions of a user in order 4122 * to allow device or profile owner to remove POLICY_FIXED. 4123 */ 4124 @Override 4125 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4126 if (!sUserManager.exists(userId)) { 4127 return; 4128 } 4129 4130 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4131 4132 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4133 true /* requireFullPermission */, true /* checkShell */, 4134 "updatePermissionFlagsForAllApps"); 4135 4136 // Only the system can change system fixed flags. 4137 if (getCallingUid() != Process.SYSTEM_UID) { 4138 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4139 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4140 } 4141 4142 synchronized (mPackages) { 4143 boolean changed = false; 4144 final int packageCount = mPackages.size(); 4145 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4146 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4147 SettingBase sb = (SettingBase) pkg.mExtras; 4148 if (sb == null) { 4149 continue; 4150 } 4151 PermissionsState permissionsState = sb.getPermissionsState(); 4152 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4153 userId, flagMask, flagValues); 4154 } 4155 if (changed) { 4156 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4157 } 4158 } 4159 } 4160 4161 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4162 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4163 != PackageManager.PERMISSION_GRANTED 4164 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4165 != PackageManager.PERMISSION_GRANTED) { 4166 throw new SecurityException(message + " requires " 4167 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4168 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4169 } 4170 } 4171 4172 @Override 4173 public boolean shouldShowRequestPermissionRationale(String permissionName, 4174 String packageName, int userId) { 4175 if (UserHandle.getCallingUserId() != userId) { 4176 mContext.enforceCallingPermission( 4177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4178 "canShowRequestPermissionRationale for user " + userId); 4179 } 4180 4181 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4182 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4183 return false; 4184 } 4185 4186 if (checkPermission(permissionName, packageName, userId) 4187 == PackageManager.PERMISSION_GRANTED) { 4188 return false; 4189 } 4190 4191 final int flags; 4192 4193 final long identity = Binder.clearCallingIdentity(); 4194 try { 4195 flags = getPermissionFlags(permissionName, 4196 packageName, userId); 4197 } finally { 4198 Binder.restoreCallingIdentity(identity); 4199 } 4200 4201 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4202 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4203 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4204 4205 if ((flags & fixedFlags) != 0) { 4206 return false; 4207 } 4208 4209 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4210 } 4211 4212 @Override 4213 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4214 mContext.enforceCallingOrSelfPermission( 4215 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4216 "addOnPermissionsChangeListener"); 4217 4218 synchronized (mPackages) { 4219 mOnPermissionChangeListeners.addListenerLocked(listener); 4220 } 4221 } 4222 4223 @Override 4224 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4225 synchronized (mPackages) { 4226 mOnPermissionChangeListeners.removeListenerLocked(listener); 4227 } 4228 } 4229 4230 @Override 4231 public boolean isProtectedBroadcast(String actionName) { 4232 synchronized (mPackages) { 4233 if (mProtectedBroadcasts.contains(actionName)) { 4234 return true; 4235 } else if (actionName != null) { 4236 // TODO: remove these terrible hacks 4237 if (actionName.startsWith("android.net.netmon.lingerExpired") 4238 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4239 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4240 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4241 return true; 4242 } 4243 } 4244 } 4245 return false; 4246 } 4247 4248 @Override 4249 public int checkSignatures(String pkg1, String pkg2) { 4250 synchronized (mPackages) { 4251 final PackageParser.Package p1 = mPackages.get(pkg1); 4252 final PackageParser.Package p2 = mPackages.get(pkg2); 4253 if (p1 == null || p1.mExtras == null 4254 || p2 == null || p2.mExtras == null) { 4255 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4256 } 4257 return compareSignatures(p1.mSignatures, p2.mSignatures); 4258 } 4259 } 4260 4261 @Override 4262 public int checkUidSignatures(int uid1, int uid2) { 4263 // Map to base uids. 4264 uid1 = UserHandle.getAppId(uid1); 4265 uid2 = UserHandle.getAppId(uid2); 4266 // reader 4267 synchronized (mPackages) { 4268 Signature[] s1; 4269 Signature[] s2; 4270 Object obj = mSettings.getUserIdLPr(uid1); 4271 if (obj != null) { 4272 if (obj instanceof SharedUserSetting) { 4273 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4274 } else if (obj instanceof PackageSetting) { 4275 s1 = ((PackageSetting)obj).signatures.mSignatures; 4276 } else { 4277 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4278 } 4279 } else { 4280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4281 } 4282 obj = mSettings.getUserIdLPr(uid2); 4283 if (obj != null) { 4284 if (obj instanceof SharedUserSetting) { 4285 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4286 } else if (obj instanceof PackageSetting) { 4287 s2 = ((PackageSetting)obj).signatures.mSignatures; 4288 } else { 4289 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4290 } 4291 } else { 4292 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4293 } 4294 return compareSignatures(s1, s2); 4295 } 4296 } 4297 4298 private void killUid(int appId, int userId, String reason) { 4299 final long identity = Binder.clearCallingIdentity(); 4300 try { 4301 IActivityManager am = ActivityManagerNative.getDefault(); 4302 if (am != null) { 4303 try { 4304 am.killUid(appId, userId, reason); 4305 } catch (RemoteException e) { 4306 /* ignore - same process */ 4307 } 4308 } 4309 } finally { 4310 Binder.restoreCallingIdentity(identity); 4311 } 4312 } 4313 4314 /** 4315 * Compares two sets of signatures. Returns: 4316 * <br /> 4317 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4318 * <br /> 4319 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4320 * <br /> 4321 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4322 * <br /> 4323 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4324 * <br /> 4325 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4326 */ 4327 static int compareSignatures(Signature[] s1, Signature[] s2) { 4328 if (s1 == null) { 4329 return s2 == null 4330 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4331 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4332 } 4333 4334 if (s2 == null) { 4335 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4336 } 4337 4338 if (s1.length != s2.length) { 4339 return PackageManager.SIGNATURE_NO_MATCH; 4340 } 4341 4342 // Since both signature sets are of size 1, we can compare without HashSets. 4343 if (s1.length == 1) { 4344 return s1[0].equals(s2[0]) ? 4345 PackageManager.SIGNATURE_MATCH : 4346 PackageManager.SIGNATURE_NO_MATCH; 4347 } 4348 4349 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4350 for (Signature sig : s1) { 4351 set1.add(sig); 4352 } 4353 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4354 for (Signature sig : s2) { 4355 set2.add(sig); 4356 } 4357 // Make sure s2 contains all signatures in s1. 4358 if (set1.equals(set2)) { 4359 return PackageManager.SIGNATURE_MATCH; 4360 } 4361 return PackageManager.SIGNATURE_NO_MATCH; 4362 } 4363 4364 /** 4365 * If the database version for this type of package (internal storage or 4366 * external storage) is less than the version where package signatures 4367 * were updated, return true. 4368 */ 4369 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4370 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4371 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4372 } 4373 4374 /** 4375 * Used for backward compatibility to make sure any packages with 4376 * certificate chains get upgraded to the new style. {@code existingSigs} 4377 * will be in the old format (since they were stored on disk from before the 4378 * system upgrade) and {@code scannedSigs} will be in the newer format. 4379 */ 4380 private int compareSignaturesCompat(PackageSignatures existingSigs, 4381 PackageParser.Package scannedPkg) { 4382 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4383 return PackageManager.SIGNATURE_NO_MATCH; 4384 } 4385 4386 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4387 for (Signature sig : existingSigs.mSignatures) { 4388 existingSet.add(sig); 4389 } 4390 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4391 for (Signature sig : scannedPkg.mSignatures) { 4392 try { 4393 Signature[] chainSignatures = sig.getChainSignatures(); 4394 for (Signature chainSig : chainSignatures) { 4395 scannedCompatSet.add(chainSig); 4396 } 4397 } catch (CertificateEncodingException e) { 4398 scannedCompatSet.add(sig); 4399 } 4400 } 4401 /* 4402 * Make sure the expanded scanned set contains all signatures in the 4403 * existing one. 4404 */ 4405 if (scannedCompatSet.equals(existingSet)) { 4406 // Migrate the old signatures to the new scheme. 4407 existingSigs.assignSignatures(scannedPkg.mSignatures); 4408 // The new KeySets will be re-added later in the scanning process. 4409 synchronized (mPackages) { 4410 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4411 } 4412 return PackageManager.SIGNATURE_MATCH; 4413 } 4414 return PackageManager.SIGNATURE_NO_MATCH; 4415 } 4416 4417 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4418 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4419 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4420 } 4421 4422 private int compareSignaturesRecover(PackageSignatures existingSigs, 4423 PackageParser.Package scannedPkg) { 4424 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4425 return PackageManager.SIGNATURE_NO_MATCH; 4426 } 4427 4428 String msg = null; 4429 try { 4430 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4431 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4432 + scannedPkg.packageName); 4433 return PackageManager.SIGNATURE_MATCH; 4434 } 4435 } catch (CertificateException e) { 4436 msg = e.getMessage(); 4437 } 4438 4439 logCriticalInfo(Log.INFO, 4440 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4441 return PackageManager.SIGNATURE_NO_MATCH; 4442 } 4443 4444 @Override 4445 public String[] getPackagesForUid(int uid) { 4446 uid = UserHandle.getAppId(uid); 4447 // reader 4448 synchronized (mPackages) { 4449 Object obj = mSettings.getUserIdLPr(uid); 4450 if (obj instanceof SharedUserSetting) { 4451 final SharedUserSetting sus = (SharedUserSetting) obj; 4452 final int N = sus.packages.size(); 4453 final String[] res = new String[N]; 4454 final Iterator<PackageSetting> it = sus.packages.iterator(); 4455 int i = 0; 4456 while (it.hasNext()) { 4457 res[i++] = it.next().name; 4458 } 4459 return res; 4460 } else if (obj instanceof PackageSetting) { 4461 final PackageSetting ps = (PackageSetting) obj; 4462 return new String[] { ps.name }; 4463 } 4464 } 4465 return null; 4466 } 4467 4468 @Override 4469 public String getNameForUid(int uid) { 4470 // reader 4471 synchronized (mPackages) { 4472 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4473 if (obj instanceof SharedUserSetting) { 4474 final SharedUserSetting sus = (SharedUserSetting) obj; 4475 return sus.name + ":" + sus.userId; 4476 } else if (obj instanceof PackageSetting) { 4477 final PackageSetting ps = (PackageSetting) obj; 4478 return ps.name; 4479 } 4480 } 4481 return null; 4482 } 4483 4484 @Override 4485 public int getUidForSharedUser(String sharedUserName) { 4486 if(sharedUserName == null) { 4487 return -1; 4488 } 4489 // reader 4490 synchronized (mPackages) { 4491 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4492 if (suid == null) { 4493 return -1; 4494 } 4495 return suid.userId; 4496 } 4497 } 4498 4499 @Override 4500 public int getFlagsForUid(int uid) { 4501 synchronized (mPackages) { 4502 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4503 if (obj instanceof SharedUserSetting) { 4504 final SharedUserSetting sus = (SharedUserSetting) obj; 4505 return sus.pkgFlags; 4506 } else if (obj instanceof PackageSetting) { 4507 final PackageSetting ps = (PackageSetting) obj; 4508 return ps.pkgFlags; 4509 } 4510 } 4511 return 0; 4512 } 4513 4514 @Override 4515 public int getPrivateFlagsForUid(int uid) { 4516 synchronized (mPackages) { 4517 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4518 if (obj instanceof SharedUserSetting) { 4519 final SharedUserSetting sus = (SharedUserSetting) obj; 4520 return sus.pkgPrivateFlags; 4521 } else if (obj instanceof PackageSetting) { 4522 final PackageSetting ps = (PackageSetting) obj; 4523 return ps.pkgPrivateFlags; 4524 } 4525 } 4526 return 0; 4527 } 4528 4529 @Override 4530 public boolean isUidPrivileged(int uid) { 4531 uid = UserHandle.getAppId(uid); 4532 // reader 4533 synchronized (mPackages) { 4534 Object obj = mSettings.getUserIdLPr(uid); 4535 if (obj instanceof SharedUserSetting) { 4536 final SharedUserSetting sus = (SharedUserSetting) obj; 4537 final Iterator<PackageSetting> it = sus.packages.iterator(); 4538 while (it.hasNext()) { 4539 if (it.next().isPrivileged()) { 4540 return true; 4541 } 4542 } 4543 } else if (obj instanceof PackageSetting) { 4544 final PackageSetting ps = (PackageSetting) obj; 4545 return ps.isPrivileged(); 4546 } 4547 } 4548 return false; 4549 } 4550 4551 @Override 4552 public String[] getAppOpPermissionPackages(String permissionName) { 4553 synchronized (mPackages) { 4554 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4555 if (pkgs == null) { 4556 return null; 4557 } 4558 return pkgs.toArray(new String[pkgs.size()]); 4559 } 4560 } 4561 4562 @Override 4563 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4564 int flags, int userId) { 4565 if (!sUserManager.exists(userId)) return null; 4566 flags = updateFlagsForResolve(flags, userId, intent); 4567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4568 false /* requireFullPermission */, false /* checkShell */, "resolve intent"); 4569 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4570 userId); 4571 final ResolveInfo bestChoice = 4572 chooseBestActivity(intent, resolvedType, flags, query, userId); 4573 4574 if (isEphemeralAllowed(intent, query, userId)) { 4575 final EphemeralResolveInfo ai = 4576 getEphemeralResolveInfo(intent, resolvedType, userId); 4577 if (ai != null) { 4578 if (DEBUG_EPHEMERAL) { 4579 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4580 } 4581 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4582 bestChoice.ephemeralResolveInfo = ai; 4583 } 4584 } 4585 return bestChoice; 4586 } 4587 4588 @Override 4589 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4590 IntentFilter filter, int match, ComponentName activity) { 4591 final int userId = UserHandle.getCallingUserId(); 4592 if (DEBUG_PREFERRED) { 4593 Log.v(TAG, "setLastChosenActivity intent=" + intent 4594 + " resolvedType=" + resolvedType 4595 + " flags=" + flags 4596 + " filter=" + filter 4597 + " match=" + match 4598 + " activity=" + activity); 4599 filter.dump(new PrintStreamPrinter(System.out), " "); 4600 } 4601 intent.setComponent(null); 4602 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4603 userId); 4604 // Find any earlier preferred or last chosen entries and nuke them 4605 findPreferredActivity(intent, resolvedType, 4606 flags, query, 0, false, true, false, userId); 4607 // Add the new activity as the last chosen for this filter 4608 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4609 "Setting last chosen"); 4610 } 4611 4612 @Override 4613 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4614 final int userId = UserHandle.getCallingUserId(); 4615 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4616 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4617 userId); 4618 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4619 false, false, false, userId); 4620 } 4621 4622 4623 private boolean isEphemeralAllowed( 4624 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4625 // Short circuit and return early if possible. 4626 if (DISABLE_EPHEMERAL_APPS) { 4627 return false; 4628 } 4629 final int callingUser = UserHandle.getCallingUserId(); 4630 if (callingUser != UserHandle.USER_SYSTEM) { 4631 return false; 4632 } 4633 if (mEphemeralResolverConnection == null) { 4634 return false; 4635 } 4636 if (intent.getComponent() != null) { 4637 return false; 4638 } 4639 if (intent.getPackage() != null) { 4640 return false; 4641 } 4642 final boolean isWebUri = hasWebURI(intent); 4643 if (!isWebUri) { 4644 return false; 4645 } 4646 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4647 synchronized (mPackages) { 4648 final int count = resolvedActivites.size(); 4649 for (int n = 0; n < count; n++) { 4650 ResolveInfo info = resolvedActivites.get(n); 4651 String packageName = info.activityInfo.packageName; 4652 PackageSetting ps = mSettings.mPackages.get(packageName); 4653 if (ps != null) { 4654 // Try to get the status from User settings first 4655 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4656 int status = (int) (packedStatus >> 32); 4657 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4658 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4659 if (DEBUG_EPHEMERAL) { 4660 Slog.v(TAG, "DENY ephemeral apps;" 4661 + " pkg: " + packageName + ", status: " + status); 4662 } 4663 return false; 4664 } 4665 } 4666 } 4667 } 4668 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4669 return true; 4670 } 4671 4672 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4673 int userId) { 4674 MessageDigest digest = null; 4675 try { 4676 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4677 } catch (NoSuchAlgorithmException e) { 4678 // If we can't create a digest, ignore ephemeral apps. 4679 return null; 4680 } 4681 4682 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4683 final byte[] digestBytes = digest.digest(hostBytes); 4684 int shaPrefix = 4685 digestBytes[0] << 24 4686 | digestBytes[1] << 16 4687 | digestBytes[2] << 8 4688 | digestBytes[3] << 0; 4689 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4690 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4691 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4692 // No hash prefix match; there are no ephemeral apps for this domain. 4693 return null; 4694 } 4695 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4696 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4697 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4698 continue; 4699 } 4700 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4701 // No filters; this should never happen. 4702 if (filters.isEmpty()) { 4703 continue; 4704 } 4705 // We have a domain match; resolve the filters to see if anything matches. 4706 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4707 for (int j = filters.size() - 1; j >= 0; --j) { 4708 final EphemeralResolveIntentInfo intentInfo = 4709 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4710 ephemeralResolver.addFilter(intentInfo); 4711 } 4712 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4713 intent, resolvedType, false /*defaultOnly*/, userId); 4714 if (!matchedResolveInfoList.isEmpty()) { 4715 return matchedResolveInfoList.get(0); 4716 } 4717 } 4718 // Hash or filter mis-match; no ephemeral apps for this domain. 4719 return null; 4720 } 4721 4722 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4723 int flags, List<ResolveInfo> query, int userId) { 4724 if (query != null) { 4725 final int N = query.size(); 4726 if (N == 1) { 4727 return query.get(0); 4728 } else if (N > 1) { 4729 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4730 // If there is more than one activity with the same priority, 4731 // then let the user decide between them. 4732 ResolveInfo r0 = query.get(0); 4733 ResolveInfo r1 = query.get(1); 4734 if (DEBUG_INTENT_MATCHING || debug) { 4735 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4736 + r1.activityInfo.name + "=" + r1.priority); 4737 } 4738 // If the first activity has a higher priority, or a different 4739 // default, then it is always desirable to pick it. 4740 if (r0.priority != r1.priority 4741 || r0.preferredOrder != r1.preferredOrder 4742 || r0.isDefault != r1.isDefault) { 4743 return query.get(0); 4744 } 4745 // If we have saved a preference for a preferred activity for 4746 // this Intent, use that. 4747 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4748 flags, query, r0.priority, true, false, debug, userId); 4749 if (ri != null) { 4750 return ri; 4751 } 4752 ri = new ResolveInfo(mResolveInfo); 4753 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4754 ri.activityInfo.applicationInfo = new ApplicationInfo( 4755 ri.activityInfo.applicationInfo); 4756 if (userId != 0) { 4757 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4758 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4759 } 4760 // Make sure that the resolver is displayable in car mode 4761 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4762 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4763 return ri; 4764 } 4765 } 4766 return null; 4767 } 4768 4769 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4770 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4771 final int N = query.size(); 4772 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4773 .get(userId); 4774 // Get the list of persistent preferred activities that handle the intent 4775 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4776 List<PersistentPreferredActivity> pprefs = ppir != null 4777 ? ppir.queryIntent(intent, resolvedType, 4778 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4779 : null; 4780 if (pprefs != null && pprefs.size() > 0) { 4781 final int M = pprefs.size(); 4782 for (int i=0; i<M; i++) { 4783 final PersistentPreferredActivity ppa = pprefs.get(i); 4784 if (DEBUG_PREFERRED || debug) { 4785 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4786 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4787 + "\n component=" + ppa.mComponent); 4788 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4789 } 4790 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4791 flags | MATCH_DISABLED_COMPONENTS, userId); 4792 if (DEBUG_PREFERRED || debug) { 4793 Slog.v(TAG, "Found persistent preferred activity:"); 4794 if (ai != null) { 4795 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4796 } else { 4797 Slog.v(TAG, " null"); 4798 } 4799 } 4800 if (ai == null) { 4801 // This previously registered persistent preferred activity 4802 // component is no longer known. Ignore it and do NOT remove it. 4803 continue; 4804 } 4805 for (int j=0; j<N; j++) { 4806 final ResolveInfo ri = query.get(j); 4807 if (!ri.activityInfo.applicationInfo.packageName 4808 .equals(ai.applicationInfo.packageName)) { 4809 continue; 4810 } 4811 if (!ri.activityInfo.name.equals(ai.name)) { 4812 continue; 4813 } 4814 // Found a persistent preference that can handle the intent. 4815 if (DEBUG_PREFERRED || debug) { 4816 Slog.v(TAG, "Returning persistent preferred activity: " + 4817 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4818 } 4819 return ri; 4820 } 4821 } 4822 } 4823 return null; 4824 } 4825 4826 // TODO: handle preferred activities missing while user has amnesia 4827 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4828 List<ResolveInfo> query, int priority, boolean always, 4829 boolean removeMatches, boolean debug, int userId) { 4830 if (!sUserManager.exists(userId)) return null; 4831 flags = updateFlagsForResolve(flags, userId, intent); 4832 // writer 4833 synchronized (mPackages) { 4834 if (intent.getSelector() != null) { 4835 intent = intent.getSelector(); 4836 } 4837 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4838 4839 // Try to find a matching persistent preferred activity. 4840 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 4841 debug, userId); 4842 4843 // If a persistent preferred activity matched, use it. 4844 if (pri != null) { 4845 return pri; 4846 } 4847 4848 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 4849 // Get the list of preferred activities that handle the intent 4850 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 4851 List<PreferredActivity> prefs = pir != null 4852 ? pir.queryIntent(intent, resolvedType, 4853 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4854 : null; 4855 if (prefs != null && prefs.size() > 0) { 4856 boolean changed = false; 4857 try { 4858 // First figure out how good the original match set is. 4859 // We will only allow preferred activities that came 4860 // from the same match quality. 4861 int match = 0; 4862 4863 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 4864 4865 final int N = query.size(); 4866 for (int j=0; j<N; j++) { 4867 final ResolveInfo ri = query.get(j); 4868 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 4869 + ": 0x" + Integer.toHexString(match)); 4870 if (ri.match > match) { 4871 match = ri.match; 4872 } 4873 } 4874 4875 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4876 + Integer.toHexString(match)); 4877 4878 match &= IntentFilter.MATCH_CATEGORY_MASK; 4879 final int M = prefs.size(); 4880 for (int i=0; i<M; i++) { 4881 final PreferredActivity pa = prefs.get(i); 4882 if (DEBUG_PREFERRED || debug) { 4883 Slog.v(TAG, "Checking PreferredActivity ds=" 4884 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4885 + "\n component=" + pa.mPref.mComponent); 4886 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4887 } 4888 if (pa.mPref.mMatch != match) { 4889 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4890 + Integer.toHexString(pa.mPref.mMatch)); 4891 continue; 4892 } 4893 // If it's not an "always" type preferred activity and that's what we're 4894 // looking for, skip it. 4895 if (always && !pa.mPref.mAlways) { 4896 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4897 continue; 4898 } 4899 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4900 flags | MATCH_DISABLED_COMPONENTS, userId); 4901 if (DEBUG_PREFERRED || debug) { 4902 Slog.v(TAG, "Found preferred activity:"); 4903 if (ai != null) { 4904 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4905 } else { 4906 Slog.v(TAG, " null"); 4907 } 4908 } 4909 if (ai == null) { 4910 // This previously registered preferred activity 4911 // component is no longer known. Most likely an update 4912 // to the app was installed and in the new version this 4913 // component no longer exists. Clean it up by removing 4914 // it from the preferred activities list, and skip it. 4915 Slog.w(TAG, "Removing dangling preferred activity: " 4916 + pa.mPref.mComponent); 4917 pir.removeFilter(pa); 4918 changed = true; 4919 continue; 4920 } 4921 for (int j=0; j<N; j++) { 4922 final ResolveInfo ri = query.get(j); 4923 if (!ri.activityInfo.applicationInfo.packageName 4924 .equals(ai.applicationInfo.packageName)) { 4925 continue; 4926 } 4927 if (!ri.activityInfo.name.equals(ai.name)) { 4928 continue; 4929 } 4930 4931 if (removeMatches) { 4932 pir.removeFilter(pa); 4933 changed = true; 4934 if (DEBUG_PREFERRED) { 4935 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4936 } 4937 break; 4938 } 4939 4940 // Okay we found a previously set preferred or last chosen app. 4941 // If the result set is different from when this 4942 // was created, we need to clear it and re-ask the 4943 // user their preference, if we're looking for an "always" type entry. 4944 if (always && !pa.mPref.sameSet(query)) { 4945 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4946 + intent + " type " + resolvedType); 4947 if (DEBUG_PREFERRED) { 4948 Slog.v(TAG, "Removing preferred activity since set changed " 4949 + pa.mPref.mComponent); 4950 } 4951 pir.removeFilter(pa); 4952 // Re-add the filter as a "last chosen" entry (!always) 4953 PreferredActivity lastChosen = new PreferredActivity( 4954 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4955 pir.addFilter(lastChosen); 4956 changed = true; 4957 return null; 4958 } 4959 4960 // Yay! Either the set matched or we're looking for the last chosen 4961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4962 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4963 return ri; 4964 } 4965 } 4966 } finally { 4967 if (changed) { 4968 if (DEBUG_PREFERRED) { 4969 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4970 } 4971 scheduleWritePackageRestrictionsLocked(userId); 4972 } 4973 } 4974 } 4975 } 4976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4977 return null; 4978 } 4979 4980 /* 4981 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4982 */ 4983 @Override 4984 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4985 int targetUserId) { 4986 mContext.enforceCallingOrSelfPermission( 4987 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4988 List<CrossProfileIntentFilter> matches = 4989 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4990 if (matches != null) { 4991 int size = matches.size(); 4992 for (int i = 0; i < size; i++) { 4993 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4994 } 4995 } 4996 if (hasWebURI(intent)) { 4997 // cross-profile app linking works only towards the parent. 4998 final UserInfo parent = getProfileParent(sourceUserId); 4999 synchronized(mPackages) { 5000 int flags = updateFlagsForResolve(0, parent.id, intent); 5001 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5002 intent, resolvedType, flags, sourceUserId, parent.id); 5003 return xpDomainInfo != null; 5004 } 5005 } 5006 return false; 5007 } 5008 5009 private UserInfo getProfileParent(int userId) { 5010 final long identity = Binder.clearCallingIdentity(); 5011 try { 5012 return sUserManager.getProfileParent(userId); 5013 } finally { 5014 Binder.restoreCallingIdentity(identity); 5015 } 5016 } 5017 5018 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5019 String resolvedType, int userId) { 5020 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5021 if (resolver != null) { 5022 return resolver.queryIntent(intent, resolvedType, false, userId); 5023 } 5024 return null; 5025 } 5026 5027 @Override 5028 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5029 String resolvedType, int flags, int userId) { 5030 return new ParceledListSlice<>( 5031 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5032 } 5033 5034 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5035 String resolvedType, int flags, int userId) { 5036 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5037 flags = updateFlagsForResolve(flags, userId, intent); 5038 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5039 false /* requireFullPermission */, false /* checkShell */, 5040 "query intent activities"); 5041 ComponentName comp = intent.getComponent(); 5042 if (comp == null) { 5043 if (intent.getSelector() != null) { 5044 intent = intent.getSelector(); 5045 comp = intent.getComponent(); 5046 } 5047 } 5048 5049 if (comp != null) { 5050 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5051 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5052 if (ai != null) { 5053 final ResolveInfo ri = new ResolveInfo(); 5054 ri.activityInfo = ai; 5055 list.add(ri); 5056 } 5057 return list; 5058 } 5059 5060 // reader 5061 synchronized (mPackages) { 5062 final String pkgName = intent.getPackage(); 5063 if (pkgName == null) { 5064 List<CrossProfileIntentFilter> matchingFilters = 5065 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5066 // Check for results that need to skip the current profile. 5067 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5068 resolvedType, flags, userId); 5069 if (xpResolveInfo != null) { 5070 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5071 result.add(xpResolveInfo); 5072 return filterIfNotSystemUser(result, userId); 5073 } 5074 5075 // Check for results in the current profile. 5076 List<ResolveInfo> result = mActivities.queryIntent( 5077 intent, resolvedType, flags, userId); 5078 result = filterIfNotSystemUser(result, userId); 5079 5080 // Check for cross profile results. 5081 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5082 xpResolveInfo = queryCrossProfileIntents( 5083 matchingFilters, intent, resolvedType, flags, userId, 5084 hasNonNegativePriorityResult); 5085 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5086 boolean isVisibleToUser = filterIfNotSystemUser( 5087 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5088 if (isVisibleToUser) { 5089 result.add(xpResolveInfo); 5090 Collections.sort(result, mResolvePrioritySorter); 5091 } 5092 } 5093 if (hasWebURI(intent)) { 5094 CrossProfileDomainInfo xpDomainInfo = null; 5095 final UserInfo parent = getProfileParent(userId); 5096 if (parent != null) { 5097 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5098 flags, userId, parent.id); 5099 } 5100 if (xpDomainInfo != null) { 5101 if (xpResolveInfo != null) { 5102 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5103 // in the result. 5104 result.remove(xpResolveInfo); 5105 } 5106 if (result.size() == 0) { 5107 result.add(xpDomainInfo.resolveInfo); 5108 return result; 5109 } 5110 } else if (result.size() <= 1) { 5111 return result; 5112 } 5113 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5114 xpDomainInfo, userId); 5115 Collections.sort(result, mResolvePrioritySorter); 5116 } 5117 return result; 5118 } 5119 final PackageParser.Package pkg = mPackages.get(pkgName); 5120 if (pkg != null) { 5121 return filterIfNotSystemUser( 5122 mActivities.queryIntentForPackage( 5123 intent, resolvedType, flags, pkg.activities, userId), 5124 userId); 5125 } 5126 return new ArrayList<ResolveInfo>(); 5127 } 5128 } 5129 5130 private static class CrossProfileDomainInfo { 5131 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5132 ResolveInfo resolveInfo; 5133 /* Best domain verification status of the activities found in the other profile */ 5134 int bestDomainVerificationStatus; 5135 } 5136 5137 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5138 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5139 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5140 sourceUserId)) { 5141 return null; 5142 } 5143 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5144 resolvedType, flags, parentUserId); 5145 5146 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5147 return null; 5148 } 5149 CrossProfileDomainInfo result = null; 5150 int size = resultTargetUser.size(); 5151 for (int i = 0; i < size; i++) { 5152 ResolveInfo riTargetUser = resultTargetUser.get(i); 5153 // Intent filter verification is only for filters that specify a host. So don't return 5154 // those that handle all web uris. 5155 if (riTargetUser.handleAllWebDataURI) { 5156 continue; 5157 } 5158 String packageName = riTargetUser.activityInfo.packageName; 5159 PackageSetting ps = mSettings.mPackages.get(packageName); 5160 if (ps == null) { 5161 continue; 5162 } 5163 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5164 int status = (int)(verificationState >> 32); 5165 if (result == null) { 5166 result = new CrossProfileDomainInfo(); 5167 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5168 sourceUserId, parentUserId); 5169 result.bestDomainVerificationStatus = status; 5170 } else { 5171 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5172 result.bestDomainVerificationStatus); 5173 } 5174 } 5175 // Don't consider matches with status NEVER across profiles. 5176 if (result != null && result.bestDomainVerificationStatus 5177 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5178 return null; 5179 } 5180 return result; 5181 } 5182 5183 /** 5184 * Verification statuses are ordered from the worse to the best, except for 5185 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5186 */ 5187 private int bestDomainVerificationStatus(int status1, int status2) { 5188 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5189 return status2; 5190 } 5191 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5192 return status1; 5193 } 5194 return (int) MathUtils.max(status1, status2); 5195 } 5196 5197 private boolean isUserEnabled(int userId) { 5198 long callingId = Binder.clearCallingIdentity(); 5199 try { 5200 UserInfo userInfo = sUserManager.getUserInfo(userId); 5201 return userInfo != null && userInfo.isEnabled(); 5202 } finally { 5203 Binder.restoreCallingIdentity(callingId); 5204 } 5205 } 5206 5207 /** 5208 * Filter out activities with systemUserOnly flag set, when current user is not System. 5209 * 5210 * @return filtered list 5211 */ 5212 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5213 if (userId == UserHandle.USER_SYSTEM) { 5214 return resolveInfos; 5215 } 5216 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5217 ResolveInfo info = resolveInfos.get(i); 5218 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5219 resolveInfos.remove(i); 5220 } 5221 } 5222 return resolveInfos; 5223 } 5224 5225 /** 5226 * @param resolveInfos list of resolve infos in descending priority order 5227 * @return if the list contains a resolve info with non-negative priority 5228 */ 5229 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5230 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5231 } 5232 5233 private static boolean hasWebURI(Intent intent) { 5234 if (intent.getData() == null) { 5235 return false; 5236 } 5237 final String scheme = intent.getScheme(); 5238 if (TextUtils.isEmpty(scheme)) { 5239 return false; 5240 } 5241 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5242 } 5243 5244 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5245 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5246 int userId) { 5247 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5248 5249 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5250 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5251 candidates.size()); 5252 } 5253 5254 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5255 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5256 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5257 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5258 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5259 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5260 5261 synchronized (mPackages) { 5262 final int count = candidates.size(); 5263 // First, try to use linked apps. Partition the candidates into four lists: 5264 // one for the final results, one for the "do not use ever", one for "undefined status" 5265 // and finally one for "browser app type". 5266 for (int n=0; n<count; n++) { 5267 ResolveInfo info = candidates.get(n); 5268 String packageName = info.activityInfo.packageName; 5269 PackageSetting ps = mSettings.mPackages.get(packageName); 5270 if (ps != null) { 5271 // Add to the special match all list (Browser use case) 5272 if (info.handleAllWebDataURI) { 5273 matchAllList.add(info); 5274 continue; 5275 } 5276 // Try to get the status from User settings first 5277 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5278 int status = (int)(packedStatus >> 32); 5279 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5280 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5281 if (DEBUG_DOMAIN_VERIFICATION) { 5282 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5283 + " : linkgen=" + linkGeneration); 5284 } 5285 // Use link-enabled generation as preferredOrder, i.e. 5286 // prefer newly-enabled over earlier-enabled. 5287 info.preferredOrder = linkGeneration; 5288 alwaysList.add(info); 5289 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5290 if (DEBUG_DOMAIN_VERIFICATION) { 5291 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5292 } 5293 neverList.add(info); 5294 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5295 if (DEBUG_DOMAIN_VERIFICATION) { 5296 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5297 } 5298 alwaysAskList.add(info); 5299 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5300 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5301 if (DEBUG_DOMAIN_VERIFICATION) { 5302 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5303 } 5304 undefinedList.add(info); 5305 } 5306 } 5307 } 5308 5309 // We'll want to include browser possibilities in a few cases 5310 boolean includeBrowser = false; 5311 5312 // First try to add the "always" resolution(s) for the current user, if any 5313 if (alwaysList.size() > 0) { 5314 result.addAll(alwaysList); 5315 } else { 5316 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5317 result.addAll(undefinedList); 5318 // Maybe add one for the other profile. 5319 if (xpDomainInfo != null && ( 5320 xpDomainInfo.bestDomainVerificationStatus 5321 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5322 result.add(xpDomainInfo.resolveInfo); 5323 } 5324 includeBrowser = true; 5325 } 5326 5327 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5328 // If there were 'always' entries their preferred order has been set, so we also 5329 // back that off to make the alternatives equivalent 5330 if (alwaysAskList.size() > 0) { 5331 for (ResolveInfo i : result) { 5332 i.preferredOrder = 0; 5333 } 5334 result.addAll(alwaysAskList); 5335 includeBrowser = true; 5336 } 5337 5338 if (includeBrowser) { 5339 // Also add browsers (all of them or only the default one) 5340 if (DEBUG_DOMAIN_VERIFICATION) { 5341 Slog.v(TAG, " ...including browsers in candidate set"); 5342 } 5343 if ((matchFlags & MATCH_ALL) != 0) { 5344 result.addAll(matchAllList); 5345 } else { 5346 // Browser/generic handling case. If there's a default browser, go straight 5347 // to that (but only if there is no other higher-priority match). 5348 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5349 int maxMatchPrio = 0; 5350 ResolveInfo defaultBrowserMatch = null; 5351 final int numCandidates = matchAllList.size(); 5352 for (int n = 0; n < numCandidates; n++) { 5353 ResolveInfo info = matchAllList.get(n); 5354 // track the highest overall match priority... 5355 if (info.priority > maxMatchPrio) { 5356 maxMatchPrio = info.priority; 5357 } 5358 // ...and the highest-priority default browser match 5359 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5360 if (defaultBrowserMatch == null 5361 || (defaultBrowserMatch.priority < info.priority)) { 5362 if (debug) { 5363 Slog.v(TAG, "Considering default browser match " + info); 5364 } 5365 defaultBrowserMatch = info; 5366 } 5367 } 5368 } 5369 if (defaultBrowserMatch != null 5370 && defaultBrowserMatch.priority >= maxMatchPrio 5371 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5372 { 5373 if (debug) { 5374 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5375 } 5376 result.add(defaultBrowserMatch); 5377 } else { 5378 result.addAll(matchAllList); 5379 } 5380 } 5381 5382 // If there is nothing selected, add all candidates and remove the ones that the user 5383 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5384 if (result.size() == 0) { 5385 result.addAll(candidates); 5386 result.removeAll(neverList); 5387 } 5388 } 5389 } 5390 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5391 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5392 result.size()); 5393 for (ResolveInfo info : result) { 5394 Slog.v(TAG, " + " + info.activityInfo); 5395 } 5396 } 5397 return result; 5398 } 5399 5400 // Returns a packed value as a long: 5401 // 5402 // high 'int'-sized word: link status: undefined/ask/never/always. 5403 // low 'int'-sized word: relative priority among 'always' results. 5404 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5405 long result = ps.getDomainVerificationStatusForUser(userId); 5406 // if none available, get the master status 5407 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5408 if (ps.getIntentFilterVerificationInfo() != null) { 5409 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5410 } 5411 } 5412 return result; 5413 } 5414 5415 private ResolveInfo querySkipCurrentProfileIntents( 5416 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5417 int flags, int sourceUserId) { 5418 if (matchingFilters != null) { 5419 int size = matchingFilters.size(); 5420 for (int i = 0; i < size; i ++) { 5421 CrossProfileIntentFilter filter = matchingFilters.get(i); 5422 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5423 // Checking if there are activities in the target user that can handle the 5424 // intent. 5425 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5426 resolvedType, flags, sourceUserId); 5427 if (resolveInfo != null) { 5428 return resolveInfo; 5429 } 5430 } 5431 } 5432 } 5433 return null; 5434 } 5435 5436 // Return matching ResolveInfo in target user if any. 5437 private ResolveInfo queryCrossProfileIntents( 5438 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5439 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5440 if (matchingFilters != null) { 5441 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5442 // match the same intent. For performance reasons, it is better not to 5443 // run queryIntent twice for the same userId 5444 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5445 int size = matchingFilters.size(); 5446 for (int i = 0; i < size; i++) { 5447 CrossProfileIntentFilter filter = matchingFilters.get(i); 5448 int targetUserId = filter.getTargetUserId(); 5449 boolean skipCurrentProfile = 5450 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5451 boolean skipCurrentProfileIfNoMatchFound = 5452 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5453 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5454 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5455 // Checking if there are activities in the target user that can handle the 5456 // intent. 5457 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5458 resolvedType, flags, sourceUserId); 5459 if (resolveInfo != null) return resolveInfo; 5460 alreadyTriedUserIds.put(targetUserId, true); 5461 } 5462 } 5463 } 5464 return null; 5465 } 5466 5467 /** 5468 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5469 * will forward the intent to the filter's target user. 5470 * Otherwise, returns null. 5471 */ 5472 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5473 String resolvedType, int flags, int sourceUserId) { 5474 int targetUserId = filter.getTargetUserId(); 5475 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5476 resolvedType, flags, targetUserId); 5477 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5478 // If all the matches in the target profile are suspended, return null. 5479 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5480 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5481 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5482 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5483 targetUserId); 5484 } 5485 } 5486 } 5487 return null; 5488 } 5489 5490 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5491 int sourceUserId, int targetUserId) { 5492 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5493 long ident = Binder.clearCallingIdentity(); 5494 boolean targetIsProfile; 5495 try { 5496 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5497 } finally { 5498 Binder.restoreCallingIdentity(ident); 5499 } 5500 String className; 5501 if (targetIsProfile) { 5502 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5503 } else { 5504 className = FORWARD_INTENT_TO_PARENT; 5505 } 5506 ComponentName forwardingActivityComponentName = new ComponentName( 5507 mAndroidApplication.packageName, className); 5508 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5509 sourceUserId); 5510 if (!targetIsProfile) { 5511 forwardingActivityInfo.showUserIcon = targetUserId; 5512 forwardingResolveInfo.noResourceId = true; 5513 } 5514 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5515 forwardingResolveInfo.priority = 0; 5516 forwardingResolveInfo.preferredOrder = 0; 5517 forwardingResolveInfo.match = 0; 5518 forwardingResolveInfo.isDefault = true; 5519 forwardingResolveInfo.filter = filter; 5520 forwardingResolveInfo.targetUserId = targetUserId; 5521 return forwardingResolveInfo; 5522 } 5523 5524 @Override 5525 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5526 Intent[] specifics, String[] specificTypes, Intent intent, 5527 String resolvedType, int flags, int userId) { 5528 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5529 specificTypes, intent, resolvedType, flags, userId)); 5530 } 5531 5532 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5533 Intent[] specifics, String[] specificTypes, Intent intent, 5534 String resolvedType, int flags, int userId) { 5535 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5536 flags = updateFlagsForResolve(flags, userId, intent); 5537 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5538 false /* requireFullPermission */, false /* checkShell */, 5539 "query intent activity options"); 5540 final String resultsAction = intent.getAction(); 5541 5542 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5543 | PackageManager.GET_RESOLVED_FILTER, userId); 5544 5545 if (DEBUG_INTENT_MATCHING) { 5546 Log.v(TAG, "Query " + intent + ": " + results); 5547 } 5548 5549 int specificsPos = 0; 5550 int N; 5551 5552 // todo: note that the algorithm used here is O(N^2). This 5553 // isn't a problem in our current environment, but if we start running 5554 // into situations where we have more than 5 or 10 matches then this 5555 // should probably be changed to something smarter... 5556 5557 // First we go through and resolve each of the specific items 5558 // that were supplied, taking care of removing any corresponding 5559 // duplicate items in the generic resolve list. 5560 if (specifics != null) { 5561 for (int i=0; i<specifics.length; i++) { 5562 final Intent sintent = specifics[i]; 5563 if (sintent == null) { 5564 continue; 5565 } 5566 5567 if (DEBUG_INTENT_MATCHING) { 5568 Log.v(TAG, "Specific #" + i + ": " + sintent); 5569 } 5570 5571 String action = sintent.getAction(); 5572 if (resultsAction != null && resultsAction.equals(action)) { 5573 // If this action was explicitly requested, then don't 5574 // remove things that have it. 5575 action = null; 5576 } 5577 5578 ResolveInfo ri = null; 5579 ActivityInfo ai = null; 5580 5581 ComponentName comp = sintent.getComponent(); 5582 if (comp == null) { 5583 ri = resolveIntent( 5584 sintent, 5585 specificTypes != null ? specificTypes[i] : null, 5586 flags, userId); 5587 if (ri == null) { 5588 continue; 5589 } 5590 if (ri == mResolveInfo) { 5591 // ACK! Must do something better with this. 5592 } 5593 ai = ri.activityInfo; 5594 comp = new ComponentName(ai.applicationInfo.packageName, 5595 ai.name); 5596 } else { 5597 ai = getActivityInfo(comp, flags, userId); 5598 if (ai == null) { 5599 continue; 5600 } 5601 } 5602 5603 // Look for any generic query activities that are duplicates 5604 // of this specific one, and remove them from the results. 5605 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5606 N = results.size(); 5607 int j; 5608 for (j=specificsPos; j<N; j++) { 5609 ResolveInfo sri = results.get(j); 5610 if ((sri.activityInfo.name.equals(comp.getClassName()) 5611 && sri.activityInfo.applicationInfo.packageName.equals( 5612 comp.getPackageName())) 5613 || (action != null && sri.filter.matchAction(action))) { 5614 results.remove(j); 5615 if (DEBUG_INTENT_MATCHING) Log.v( 5616 TAG, "Removing duplicate item from " + j 5617 + " due to specific " + specificsPos); 5618 if (ri == null) { 5619 ri = sri; 5620 } 5621 j--; 5622 N--; 5623 } 5624 } 5625 5626 // Add this specific item to its proper place. 5627 if (ri == null) { 5628 ri = new ResolveInfo(); 5629 ri.activityInfo = ai; 5630 } 5631 results.add(specificsPos, ri); 5632 ri.specificIndex = i; 5633 specificsPos++; 5634 } 5635 } 5636 5637 // Now we go through the remaining generic results and remove any 5638 // duplicate actions that are found here. 5639 N = results.size(); 5640 for (int i=specificsPos; i<N-1; i++) { 5641 final ResolveInfo rii = results.get(i); 5642 if (rii.filter == null) { 5643 continue; 5644 } 5645 5646 // Iterate over all of the actions of this result's intent 5647 // filter... typically this should be just one. 5648 final Iterator<String> it = rii.filter.actionsIterator(); 5649 if (it == null) { 5650 continue; 5651 } 5652 while (it.hasNext()) { 5653 final String action = it.next(); 5654 if (resultsAction != null && resultsAction.equals(action)) { 5655 // If this action was explicitly requested, then don't 5656 // remove things that have it. 5657 continue; 5658 } 5659 for (int j=i+1; j<N; j++) { 5660 final ResolveInfo rij = results.get(j); 5661 if (rij.filter != null && rij.filter.hasAction(action)) { 5662 results.remove(j); 5663 if (DEBUG_INTENT_MATCHING) Log.v( 5664 TAG, "Removing duplicate item from " + j 5665 + " due to action " + action + " at " + i); 5666 j--; 5667 N--; 5668 } 5669 } 5670 } 5671 5672 // If the caller didn't request filter information, drop it now 5673 // so we don't have to marshall/unmarshall it. 5674 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5675 rii.filter = null; 5676 } 5677 } 5678 5679 // Filter out the caller activity if so requested. 5680 if (caller != null) { 5681 N = results.size(); 5682 for (int i=0; i<N; i++) { 5683 ActivityInfo ainfo = results.get(i).activityInfo; 5684 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5685 && caller.getClassName().equals(ainfo.name)) { 5686 results.remove(i); 5687 break; 5688 } 5689 } 5690 } 5691 5692 // If the caller didn't request filter information, 5693 // drop them now so we don't have to 5694 // marshall/unmarshall it. 5695 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5696 N = results.size(); 5697 for (int i=0; i<N; i++) { 5698 results.get(i).filter = null; 5699 } 5700 } 5701 5702 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5703 return results; 5704 } 5705 5706 @Override 5707 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5708 String resolvedType, int flags, int userId) { 5709 return new ParceledListSlice<>( 5710 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5711 } 5712 5713 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5714 String resolvedType, int flags, int userId) { 5715 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5716 flags = updateFlagsForResolve(flags, userId, intent); 5717 ComponentName comp = intent.getComponent(); 5718 if (comp == null) { 5719 if (intent.getSelector() != null) { 5720 intent = intent.getSelector(); 5721 comp = intent.getComponent(); 5722 } 5723 } 5724 if (comp != null) { 5725 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5726 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5727 if (ai != null) { 5728 ResolveInfo ri = new ResolveInfo(); 5729 ri.activityInfo = ai; 5730 list.add(ri); 5731 } 5732 return list; 5733 } 5734 5735 // reader 5736 synchronized (mPackages) { 5737 String pkgName = intent.getPackage(); 5738 if (pkgName == null) { 5739 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5740 } 5741 final PackageParser.Package pkg = mPackages.get(pkgName); 5742 if (pkg != null) { 5743 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5744 userId); 5745 } 5746 return Collections.emptyList(); 5747 } 5748 } 5749 5750 @Override 5751 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5752 if (!sUserManager.exists(userId)) return null; 5753 flags = updateFlagsForResolve(flags, userId, intent); 5754 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5755 if (query != null) { 5756 if (query.size() >= 1) { 5757 // If there is more than one service with the same priority, 5758 // just arbitrarily pick the first one. 5759 return query.get(0); 5760 } 5761 } 5762 return null; 5763 } 5764 5765 @Override 5766 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5767 String resolvedType, int flags, int userId) { 5768 return new ParceledListSlice<>( 5769 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5770 } 5771 5772 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5773 String resolvedType, int flags, int userId) { 5774 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5775 flags = updateFlagsForResolve(flags, userId, intent); 5776 ComponentName comp = intent.getComponent(); 5777 if (comp == null) { 5778 if (intent.getSelector() != null) { 5779 intent = intent.getSelector(); 5780 comp = intent.getComponent(); 5781 } 5782 } 5783 if (comp != null) { 5784 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5785 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5786 if (si != null) { 5787 final ResolveInfo ri = new ResolveInfo(); 5788 ri.serviceInfo = si; 5789 list.add(ri); 5790 } 5791 return list; 5792 } 5793 5794 // reader 5795 synchronized (mPackages) { 5796 String pkgName = intent.getPackage(); 5797 if (pkgName == null) { 5798 return mServices.queryIntent(intent, resolvedType, flags, userId); 5799 } 5800 final PackageParser.Package pkg = mPackages.get(pkgName); 5801 if (pkg != null) { 5802 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5803 userId); 5804 } 5805 return Collections.emptyList(); 5806 } 5807 } 5808 5809 @Override 5810 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5811 String resolvedType, int flags, int userId) { 5812 return new ParceledListSlice<>( 5813 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5814 } 5815 5816 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5817 Intent intent, String resolvedType, int flags, int userId) { 5818 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5819 flags = updateFlagsForResolve(flags, userId, intent); 5820 ComponentName comp = intent.getComponent(); 5821 if (comp == null) { 5822 if (intent.getSelector() != null) { 5823 intent = intent.getSelector(); 5824 comp = intent.getComponent(); 5825 } 5826 } 5827 if (comp != null) { 5828 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5829 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 5830 if (pi != null) { 5831 final ResolveInfo ri = new ResolveInfo(); 5832 ri.providerInfo = pi; 5833 list.add(ri); 5834 } 5835 return list; 5836 } 5837 5838 // reader 5839 synchronized (mPackages) { 5840 String pkgName = intent.getPackage(); 5841 if (pkgName == null) { 5842 return mProviders.queryIntent(intent, resolvedType, flags, userId); 5843 } 5844 final PackageParser.Package pkg = mPackages.get(pkgName); 5845 if (pkg != null) { 5846 return mProviders.queryIntentForPackage( 5847 intent, resolvedType, flags, pkg.providers, userId); 5848 } 5849 return Collections.emptyList(); 5850 } 5851 } 5852 5853 @Override 5854 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 5855 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5856 flags = updateFlagsForPackage(flags, userId, null); 5857 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5858 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5859 true /* requireFullPermission */, false /* checkShell */, 5860 "get installed packages"); 5861 5862 // writer 5863 synchronized (mPackages) { 5864 ArrayList<PackageInfo> list; 5865 if (listUninstalled) { 5866 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 5867 for (PackageSetting ps : mSettings.mPackages.values()) { 5868 PackageInfo pi; 5869 if (ps.pkg != null) { 5870 pi = generatePackageInfo(ps.pkg, flags, userId); 5871 } else { 5872 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5873 } 5874 if (pi != null) { 5875 list.add(pi); 5876 } 5877 } 5878 } else { 5879 list = new ArrayList<PackageInfo>(mPackages.size()); 5880 for (PackageParser.Package p : mPackages.values()) { 5881 PackageInfo pi = generatePackageInfo(p, flags, userId); 5882 if (pi != null) { 5883 list.add(pi); 5884 } 5885 } 5886 } 5887 5888 return new ParceledListSlice<PackageInfo>(list); 5889 } 5890 } 5891 5892 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 5893 String[] permissions, boolean[] tmp, int flags, int userId) { 5894 int numMatch = 0; 5895 final PermissionsState permissionsState = ps.getPermissionsState(); 5896 for (int i=0; i<permissions.length; i++) { 5897 final String permission = permissions[i]; 5898 if (permissionsState.hasPermission(permission, userId)) { 5899 tmp[i] = true; 5900 numMatch++; 5901 } else { 5902 tmp[i] = false; 5903 } 5904 } 5905 if (numMatch == 0) { 5906 return; 5907 } 5908 PackageInfo pi; 5909 if (ps.pkg != null) { 5910 pi = generatePackageInfo(ps.pkg, flags, userId); 5911 } else { 5912 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 5913 } 5914 // The above might return null in cases of uninstalled apps or install-state 5915 // skew across users/profiles. 5916 if (pi != null) { 5917 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 5918 if (numMatch == permissions.length) { 5919 pi.requestedPermissions = permissions; 5920 } else { 5921 pi.requestedPermissions = new String[numMatch]; 5922 numMatch = 0; 5923 for (int i=0; i<permissions.length; i++) { 5924 if (tmp[i]) { 5925 pi.requestedPermissions[numMatch] = permissions[i]; 5926 numMatch++; 5927 } 5928 } 5929 } 5930 } 5931 list.add(pi); 5932 } 5933 } 5934 5935 @Override 5936 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 5937 String[] permissions, int flags, int userId) { 5938 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5939 flags = updateFlagsForPackage(flags, userId, permissions); 5940 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5941 5942 // writer 5943 synchronized (mPackages) { 5944 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 5945 boolean[] tmpBools = new boolean[permissions.length]; 5946 if (listUninstalled) { 5947 for (PackageSetting ps : mSettings.mPackages.values()) { 5948 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 5949 } 5950 } else { 5951 for (PackageParser.Package pkg : mPackages.values()) { 5952 PackageSetting ps = (PackageSetting)pkg.mExtras; 5953 if (ps != null) { 5954 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 5955 userId); 5956 } 5957 } 5958 } 5959 5960 return new ParceledListSlice<PackageInfo>(list); 5961 } 5962 } 5963 5964 @Override 5965 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 5966 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 5967 flags = updateFlagsForApplication(flags, userId, null); 5968 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 5969 5970 // writer 5971 synchronized (mPackages) { 5972 ArrayList<ApplicationInfo> list; 5973 if (listUninstalled) { 5974 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 5975 for (PackageSetting ps : mSettings.mPackages.values()) { 5976 ApplicationInfo ai; 5977 if (ps.pkg != null) { 5978 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 5979 ps.readUserState(userId), userId); 5980 } else { 5981 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 5982 } 5983 if (ai != null) { 5984 list.add(ai); 5985 } 5986 } 5987 } else { 5988 list = new ArrayList<ApplicationInfo>(mPackages.size()); 5989 for (PackageParser.Package p : mPackages.values()) { 5990 if (p.mExtras != null) { 5991 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 5992 ((PackageSetting)p.mExtras).readUserState(userId), userId); 5993 if (ai != null) { 5994 list.add(ai); 5995 } 5996 } 5997 } 5998 } 5999 6000 return new ParceledListSlice<ApplicationInfo>(list); 6001 } 6002 } 6003 6004 @Override 6005 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6006 if (DISABLE_EPHEMERAL_APPS) { 6007 return null; 6008 } 6009 6010 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6011 "getEphemeralApplications"); 6012 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6013 true /* requireFullPermission */, false /* checkShell */, 6014 "getEphemeralApplications"); 6015 synchronized (mPackages) { 6016 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6017 .getEphemeralApplicationsLPw(userId); 6018 if (ephemeralApps != null) { 6019 return new ParceledListSlice<>(ephemeralApps); 6020 } 6021 } 6022 return null; 6023 } 6024 6025 @Override 6026 public boolean isEphemeralApplication(String packageName, int userId) { 6027 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6028 true /* requireFullPermission */, false /* checkShell */, 6029 "isEphemeral"); 6030 if (DISABLE_EPHEMERAL_APPS) { 6031 return false; 6032 } 6033 6034 if (!isCallerSameApp(packageName)) { 6035 return false; 6036 } 6037 synchronized (mPackages) { 6038 PackageParser.Package pkg = mPackages.get(packageName); 6039 if (pkg != null) { 6040 return pkg.applicationInfo.isEphemeralApp(); 6041 } 6042 } 6043 return false; 6044 } 6045 6046 @Override 6047 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6048 if (DISABLE_EPHEMERAL_APPS) { 6049 return null; 6050 } 6051 6052 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6053 true /* requireFullPermission */, false /* checkShell */, 6054 "getCookie"); 6055 if (!isCallerSameApp(packageName)) { 6056 return null; 6057 } 6058 synchronized (mPackages) { 6059 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6060 packageName, userId); 6061 } 6062 } 6063 6064 @Override 6065 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6066 if (DISABLE_EPHEMERAL_APPS) { 6067 return true; 6068 } 6069 6070 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6071 true /* requireFullPermission */, true /* checkShell */, 6072 "setCookie"); 6073 if (!isCallerSameApp(packageName)) { 6074 return false; 6075 } 6076 synchronized (mPackages) { 6077 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6078 packageName, cookie, userId); 6079 } 6080 } 6081 6082 @Override 6083 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6084 if (DISABLE_EPHEMERAL_APPS) { 6085 return null; 6086 } 6087 6088 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6089 "getEphemeralApplicationIcon"); 6090 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6091 true /* requireFullPermission */, false /* checkShell */, 6092 "getEphemeralApplicationIcon"); 6093 synchronized (mPackages) { 6094 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6095 packageName, userId); 6096 } 6097 } 6098 6099 private boolean isCallerSameApp(String packageName) { 6100 PackageParser.Package pkg = mPackages.get(packageName); 6101 return pkg != null 6102 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6103 } 6104 6105 @Override 6106 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6107 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6108 } 6109 6110 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6111 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6112 6113 // reader 6114 synchronized (mPackages) { 6115 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6116 final int userId = UserHandle.getCallingUserId(); 6117 while (i.hasNext()) { 6118 final PackageParser.Package p = i.next(); 6119 if (p.applicationInfo == null) continue; 6120 6121 final boolean matchesUnaware = ((flags & MATCH_ENCRYPTION_UNAWARE) != 0) 6122 && !p.applicationInfo.isEncryptionAware(); 6123 final boolean matchesAware = ((flags & MATCH_ENCRYPTION_AWARE) != 0) 6124 && p.applicationInfo.isEncryptionAware(); 6125 6126 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6127 && (!mSafeMode || isSystemApp(p)) 6128 && (matchesUnaware || matchesAware)) { 6129 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6130 if (ps != null) { 6131 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6132 ps.readUserState(userId), userId); 6133 if (ai != null) { 6134 finalList.add(ai); 6135 } 6136 } 6137 } 6138 } 6139 } 6140 6141 return finalList; 6142 } 6143 6144 @Override 6145 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6146 if (!sUserManager.exists(userId)) return null; 6147 flags = updateFlagsForComponent(flags, userId, name); 6148 // reader 6149 synchronized (mPackages) { 6150 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6151 PackageSetting ps = provider != null 6152 ? mSettings.mPackages.get(provider.owner.packageName) 6153 : null; 6154 return ps != null 6155 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6156 ? PackageParser.generateProviderInfo(provider, flags, 6157 ps.readUserState(userId), userId) 6158 : null; 6159 } 6160 } 6161 6162 /** 6163 * @deprecated 6164 */ 6165 @Deprecated 6166 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6167 // reader 6168 synchronized (mPackages) { 6169 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6170 .entrySet().iterator(); 6171 final int userId = UserHandle.getCallingUserId(); 6172 while (i.hasNext()) { 6173 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6174 PackageParser.Provider p = entry.getValue(); 6175 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6176 6177 if (ps != null && p.syncable 6178 && (!mSafeMode || (p.info.applicationInfo.flags 6179 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6180 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6181 ps.readUserState(userId), userId); 6182 if (info != null) { 6183 outNames.add(entry.getKey()); 6184 outInfo.add(info); 6185 } 6186 } 6187 } 6188 } 6189 } 6190 6191 @Override 6192 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6193 int uid, int flags) { 6194 final int userId = processName != null ? UserHandle.getUserId(uid) 6195 : UserHandle.getCallingUserId(); 6196 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6197 flags = updateFlagsForComponent(flags, userId, processName); 6198 6199 ArrayList<ProviderInfo> finalList = null; 6200 // reader 6201 synchronized (mPackages) { 6202 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6203 while (i.hasNext()) { 6204 final PackageParser.Provider p = i.next(); 6205 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6206 if (ps != null && p.info.authority != null 6207 && (processName == null 6208 || (p.info.processName.equals(processName) 6209 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6210 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6211 if (finalList == null) { 6212 finalList = new ArrayList<ProviderInfo>(3); 6213 } 6214 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6215 ps.readUserState(userId), userId); 6216 if (info != null) { 6217 finalList.add(info); 6218 } 6219 } 6220 } 6221 } 6222 6223 if (finalList != null) { 6224 Collections.sort(finalList, mProviderInitOrderSorter); 6225 return new ParceledListSlice<ProviderInfo>(finalList); 6226 } 6227 6228 return ParceledListSlice.emptyList(); 6229 } 6230 6231 @Override 6232 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6233 // reader 6234 synchronized (mPackages) { 6235 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6236 return PackageParser.generateInstrumentationInfo(i, flags); 6237 } 6238 } 6239 6240 @Override 6241 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6242 String targetPackage, int flags) { 6243 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6244 } 6245 6246 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6247 int flags) { 6248 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6249 6250 // reader 6251 synchronized (mPackages) { 6252 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6253 while (i.hasNext()) { 6254 final PackageParser.Instrumentation p = i.next(); 6255 if (targetPackage == null 6256 || targetPackage.equals(p.info.targetPackage)) { 6257 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6258 flags); 6259 if (ii != null) { 6260 finalList.add(ii); 6261 } 6262 } 6263 } 6264 } 6265 6266 return finalList; 6267 } 6268 6269 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6270 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6271 if (overlays == null) { 6272 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6273 return; 6274 } 6275 for (PackageParser.Package opkg : overlays.values()) { 6276 // Not much to do if idmap fails: we already logged the error 6277 // and we certainly don't want to abort installation of pkg simply 6278 // because an overlay didn't fit properly. For these reasons, 6279 // ignore the return value of createIdmapForPackagePairLI. 6280 createIdmapForPackagePairLI(pkg, opkg); 6281 } 6282 } 6283 6284 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6285 PackageParser.Package opkg) { 6286 if (!opkg.mTrustedOverlay) { 6287 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6288 opkg.baseCodePath + ": overlay not trusted"); 6289 return false; 6290 } 6291 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6292 if (overlaySet == null) { 6293 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6294 opkg.baseCodePath + " but target package has no known overlays"); 6295 return false; 6296 } 6297 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6298 // TODO: generate idmap for split APKs 6299 try { 6300 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6301 } catch (InstallerException e) { 6302 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6303 + opkg.baseCodePath); 6304 return false; 6305 } 6306 PackageParser.Package[] overlayArray = 6307 overlaySet.values().toArray(new PackageParser.Package[0]); 6308 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6309 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6310 return p1.mOverlayPriority - p2.mOverlayPriority; 6311 } 6312 }; 6313 Arrays.sort(overlayArray, cmp); 6314 6315 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6316 int i = 0; 6317 for (PackageParser.Package p : overlayArray) { 6318 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6319 } 6320 return true; 6321 } 6322 6323 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6325 try { 6326 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6327 } finally { 6328 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6329 } 6330 } 6331 6332 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6333 final File[] files = dir.listFiles(); 6334 if (ArrayUtils.isEmpty(files)) { 6335 Log.d(TAG, "No files in app dir " + dir); 6336 return; 6337 } 6338 6339 if (DEBUG_PACKAGE_SCANNING) { 6340 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6341 + " flags=0x" + Integer.toHexString(parseFlags)); 6342 } 6343 6344 for (File file : files) { 6345 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6346 && !PackageInstallerService.isStageName(file.getName()); 6347 if (!isPackage) { 6348 // Ignore entries which are not packages 6349 continue; 6350 } 6351 try { 6352 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6353 scanFlags, currentTime, null); 6354 } catch (PackageManagerException e) { 6355 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6356 6357 // Delete invalid userdata apps 6358 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6359 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6360 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6361 removeCodePathLI(file); 6362 } 6363 } 6364 } 6365 } 6366 6367 private static File getSettingsProblemFile() { 6368 File dataDir = Environment.getDataDirectory(); 6369 File systemDir = new File(dataDir, "system"); 6370 File fname = new File(systemDir, "uiderrors.txt"); 6371 return fname; 6372 } 6373 6374 static void reportSettingsProblem(int priority, String msg) { 6375 logCriticalInfo(priority, msg); 6376 } 6377 6378 static void logCriticalInfo(int priority, String msg) { 6379 Slog.println(priority, TAG, msg); 6380 EventLogTags.writePmCriticalInfo(msg); 6381 try { 6382 File fname = getSettingsProblemFile(); 6383 FileOutputStream out = new FileOutputStream(fname, true); 6384 PrintWriter pw = new FastPrintWriter(out); 6385 SimpleDateFormat formatter = new SimpleDateFormat(); 6386 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6387 pw.println(dateString + ": " + msg); 6388 pw.close(); 6389 FileUtils.setPermissions( 6390 fname.toString(), 6391 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6392 -1, -1); 6393 } catch (java.io.IOException e) { 6394 } 6395 } 6396 6397 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6398 int parseFlags) throws PackageManagerException { 6399 if (ps != null 6400 && ps.codePath.equals(srcFile) 6401 && ps.timeStamp == srcFile.lastModified() 6402 && !isCompatSignatureUpdateNeeded(pkg) 6403 && !isRecoverSignatureUpdateNeeded(pkg)) { 6404 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6405 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6406 ArraySet<PublicKey> signingKs; 6407 synchronized (mPackages) { 6408 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6409 } 6410 if (ps.signatures.mSignatures != null 6411 && ps.signatures.mSignatures.length != 0 6412 && signingKs != null) { 6413 // Optimization: reuse the existing cached certificates 6414 // if the package appears to be unchanged. 6415 pkg.mSignatures = ps.signatures.mSignatures; 6416 pkg.mSigningKeys = signingKs; 6417 return; 6418 } 6419 6420 Slog.w(TAG, "PackageSetting for " + ps.name 6421 + " is missing signatures. Collecting certs again to recover them."); 6422 } else { 6423 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6424 } 6425 6426 try { 6427 PackageParser.collectCertificates(pkg, parseFlags); 6428 } catch (PackageParserException e) { 6429 throw PackageManagerException.from(e); 6430 } 6431 } 6432 6433 /** 6434 * Traces a package scan. 6435 * @see #scanPackageLI(File, int, int, long, UserHandle) 6436 */ 6437 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6438 long currentTime, UserHandle user) throws PackageManagerException { 6439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6440 try { 6441 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6442 } finally { 6443 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6444 } 6445 } 6446 6447 /** 6448 * Scans a package and returns the newly parsed package. 6449 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6450 */ 6451 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6452 long currentTime, UserHandle user) throws PackageManagerException { 6453 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6454 parseFlags |= mDefParseFlags; 6455 PackageParser pp = new PackageParser(); 6456 pp.setSeparateProcesses(mSeparateProcesses); 6457 pp.setOnlyCoreApps(mOnlyCore); 6458 pp.setDisplayMetrics(mMetrics); 6459 6460 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6461 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6462 } 6463 6464 final PackageParser.Package pkg; 6465 try { 6466 pkg = pp.parsePackage(scanFile, parseFlags); 6467 } catch (PackageParserException e) { 6468 throw PackageManagerException.from(e); 6469 } 6470 6471 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6472 } 6473 6474 /** 6475 * Scans a package and returns the newly parsed package. 6476 * @throws PackageManagerException on a parse error. 6477 */ 6478 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6479 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6480 throws PackageManagerException { 6481 // If the package has children and this is the first dive in the function 6482 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6483 // packages (parent and children) would be successfully scanned before the 6484 // actual scan since scanning mutates internal state and we want to atomically 6485 // install the package and its children. 6486 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6487 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6488 scanFlags |= SCAN_CHECK_ONLY; 6489 } 6490 } else { 6491 scanFlags &= ~SCAN_CHECK_ONLY; 6492 } 6493 6494 // Scan the parent 6495 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6496 scanFlags, currentTime, user); 6497 6498 // Scan the children 6499 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6500 for (int i = 0; i < childCount; i++) { 6501 PackageParser.Package childPackage = pkg.childPackages.get(i); 6502 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6503 currentTime, user); 6504 } 6505 6506 6507 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6508 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6509 } 6510 6511 return scannedPkg; 6512 } 6513 6514 /** 6515 * Scans a package and returns the newly parsed package. 6516 * @throws PackageManagerException on a parse error. 6517 */ 6518 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6519 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6520 throws PackageManagerException { 6521 PackageSetting ps = null; 6522 PackageSetting updatedPkg; 6523 // reader 6524 synchronized (mPackages) { 6525 // Look to see if we already know about this package. 6526 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6527 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6528 // This package has been renamed to its original name. Let's 6529 // use that. 6530 ps = mSettings.peekPackageLPr(oldName); 6531 } 6532 // If there was no original package, see one for the real package name. 6533 if (ps == null) { 6534 ps = mSettings.peekPackageLPr(pkg.packageName); 6535 } 6536 // Check to see if this package could be hiding/updating a system 6537 // package. Must look for it either under the original or real 6538 // package name depending on our state. 6539 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6540 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6541 6542 // If this is a package we don't know about on the system partition, we 6543 // may need to remove disabled child packages on the system partition 6544 // or may need to not add child packages if the parent apk is updated 6545 // on the data partition and no longer defines this child package. 6546 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6547 // If this is a parent package for an updated system app and this system 6548 // app got an OTA update which no longer defines some of the child packages 6549 // we have to prune them from the disabled system packages. 6550 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6551 if (disabledPs != null) { 6552 final int scannedChildCount = (pkg.childPackages != null) 6553 ? pkg.childPackages.size() : 0; 6554 final int disabledChildCount = disabledPs.childPackageNames != null 6555 ? disabledPs.childPackageNames.size() : 0; 6556 for (int i = 0; i < disabledChildCount; i++) { 6557 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6558 boolean disabledPackageAvailable = false; 6559 for (int j = 0; j < scannedChildCount; j++) { 6560 PackageParser.Package childPkg = pkg.childPackages.get(j); 6561 if (childPkg.packageName.equals(disabledChildPackageName)) { 6562 disabledPackageAvailable = true; 6563 break; 6564 } 6565 } 6566 if (!disabledPackageAvailable) { 6567 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6568 } 6569 } 6570 } 6571 } 6572 } 6573 6574 boolean updatedPkgBetter = false; 6575 // First check if this is a system package that may involve an update 6576 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6577 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6578 // it needs to drop FLAG_PRIVILEGED. 6579 if (locationIsPrivileged(scanFile)) { 6580 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6581 } else { 6582 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6583 } 6584 6585 if (ps != null && !ps.codePath.equals(scanFile)) { 6586 // The path has changed from what was last scanned... check the 6587 // version of the new path against what we have stored to determine 6588 // what to do. 6589 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6590 if (pkg.mVersionCode <= ps.versionCode) { 6591 // The system package has been updated and the code path does not match 6592 // Ignore entry. Skip it. 6593 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6594 + " ignored: updated version " + ps.versionCode 6595 + " better than this " + pkg.mVersionCode); 6596 if (!updatedPkg.codePath.equals(scanFile)) { 6597 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6598 + ps.name + " changing from " + updatedPkg.codePathString 6599 + " to " + scanFile); 6600 updatedPkg.codePath = scanFile; 6601 updatedPkg.codePathString = scanFile.toString(); 6602 updatedPkg.resourcePath = scanFile; 6603 updatedPkg.resourcePathString = scanFile.toString(); 6604 } 6605 updatedPkg.pkg = pkg; 6606 updatedPkg.versionCode = pkg.mVersionCode; 6607 6608 // Update the disabled system child packages to point to the package too. 6609 final int childCount = updatedPkg.childPackageNames != null 6610 ? updatedPkg.childPackageNames.size() : 0; 6611 for (int i = 0; i < childCount; i++) { 6612 String childPackageName = updatedPkg.childPackageNames.get(i); 6613 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6614 childPackageName); 6615 if (updatedChildPkg != null) { 6616 updatedChildPkg.pkg = pkg; 6617 updatedChildPkg.versionCode = pkg.mVersionCode; 6618 } 6619 } 6620 6621 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6622 + scanFile + " ignored: updated version " + ps.versionCode 6623 + " better than this " + pkg.mVersionCode); 6624 } else { 6625 // The current app on the system partition is better than 6626 // what we have updated to on the data partition; switch 6627 // back to the system partition version. 6628 // At this point, its safely assumed that package installation for 6629 // apps in system partition will go through. If not there won't be a working 6630 // version of the app 6631 // writer 6632 synchronized (mPackages) { 6633 // Just remove the loaded entries from package lists. 6634 mPackages.remove(ps.name); 6635 } 6636 6637 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6638 + " reverting from " + ps.codePathString 6639 + ": new version " + pkg.mVersionCode 6640 + " better than installed " + ps.versionCode); 6641 6642 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6643 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6644 synchronized (mInstallLock) { 6645 args.cleanUpResourcesLI(); 6646 } 6647 synchronized (mPackages) { 6648 mSettings.enableSystemPackageLPw(ps.name); 6649 } 6650 updatedPkgBetter = true; 6651 } 6652 } 6653 } 6654 6655 if (updatedPkg != null) { 6656 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6657 // initially 6658 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6659 6660 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6661 // flag set initially 6662 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6663 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6664 } 6665 } 6666 6667 // Verify certificates against what was last scanned 6668 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6669 6670 /* 6671 * A new system app appeared, but we already had a non-system one of the 6672 * same name installed earlier. 6673 */ 6674 boolean shouldHideSystemApp = false; 6675 if (updatedPkg == null && ps != null 6676 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6677 /* 6678 * Check to make sure the signatures match first. If they don't, 6679 * wipe the installed application and its data. 6680 */ 6681 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6682 != PackageManager.SIGNATURE_MATCH) { 6683 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6684 + " signatures don't match existing userdata copy; removing"); 6685 deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null); 6686 ps = null; 6687 } else { 6688 /* 6689 * If the newly-added system app is an older version than the 6690 * already installed version, hide it. It will be scanned later 6691 * and re-added like an update. 6692 */ 6693 if (pkg.mVersionCode <= ps.versionCode) { 6694 shouldHideSystemApp = true; 6695 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6696 + " but new version " + pkg.mVersionCode + " better than installed " 6697 + ps.versionCode + "; hiding system"); 6698 } else { 6699 /* 6700 * The newly found system app is a newer version that the 6701 * one previously installed. Simply remove the 6702 * already-installed application and replace it with our own 6703 * while keeping the application data. 6704 */ 6705 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6706 + " reverting from " + ps.codePathString + ": new version " 6707 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6708 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6709 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6710 synchronized (mInstallLock) { 6711 args.cleanUpResourcesLI(); 6712 } 6713 } 6714 } 6715 } 6716 6717 // The apk is forward locked (not public) if its code and resources 6718 // are kept in different files. (except for app in either system or 6719 // vendor path). 6720 // TODO grab this value from PackageSettings 6721 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6722 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6723 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6724 } 6725 } 6726 6727 // TODO: extend to support forward-locked splits 6728 String resourcePath = null; 6729 String baseResourcePath = null; 6730 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6731 if (ps != null && ps.resourcePathString != null) { 6732 resourcePath = ps.resourcePathString; 6733 baseResourcePath = ps.resourcePathString; 6734 } else { 6735 // Should not happen at all. Just log an error. 6736 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6737 } 6738 } else { 6739 resourcePath = pkg.codePath; 6740 baseResourcePath = pkg.baseCodePath; 6741 } 6742 6743 // Set application objects path explicitly. 6744 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6745 pkg.setApplicationInfoCodePath(pkg.codePath); 6746 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6747 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6748 pkg.setApplicationInfoResourcePath(resourcePath); 6749 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6750 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6751 6752 // Note that we invoke the following method only if we are about to unpack an application 6753 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6754 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6755 6756 /* 6757 * If the system app should be overridden by a previously installed 6758 * data, hide the system app now and let the /data/app scan pick it up 6759 * again. 6760 */ 6761 if (shouldHideSystemApp) { 6762 synchronized (mPackages) { 6763 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6764 } 6765 } 6766 6767 return scannedPkg; 6768 } 6769 6770 private static String fixProcessName(String defProcessName, 6771 String processName, int uid) { 6772 if (processName == null) { 6773 return defProcessName; 6774 } 6775 return processName; 6776 } 6777 6778 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6779 throws PackageManagerException { 6780 if (pkgSetting.signatures.mSignatures != null) { 6781 // Already existing package. Make sure signatures match 6782 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6783 == PackageManager.SIGNATURE_MATCH; 6784 if (!match) { 6785 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6786 == PackageManager.SIGNATURE_MATCH; 6787 } 6788 if (!match) { 6789 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6790 == PackageManager.SIGNATURE_MATCH; 6791 } 6792 if (!match) { 6793 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6794 + pkg.packageName + " signatures do not match the " 6795 + "previously installed version; ignoring!"); 6796 } 6797 } 6798 6799 // Check for shared user signatures 6800 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6801 // Already existing package. Make sure signatures match 6802 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6803 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6804 if (!match) { 6805 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6806 == PackageManager.SIGNATURE_MATCH; 6807 } 6808 if (!match) { 6809 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6810 == PackageManager.SIGNATURE_MATCH; 6811 } 6812 if (!match) { 6813 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6814 "Package " + pkg.packageName 6815 + " has no signatures that match those in shared user " 6816 + pkgSetting.sharedUser.name + "; ignoring!"); 6817 } 6818 } 6819 } 6820 6821 /** 6822 * Enforces that only the system UID or root's UID can call a method exposed 6823 * via Binder. 6824 * 6825 * @param message used as message if SecurityException is thrown 6826 * @throws SecurityException if the caller is not system or root 6827 */ 6828 private static final void enforceSystemOrRoot(String message) { 6829 final int uid = Binder.getCallingUid(); 6830 if (uid != Process.SYSTEM_UID && uid != 0) { 6831 throw new SecurityException(message); 6832 } 6833 } 6834 6835 @Override 6836 public void performFstrimIfNeeded() { 6837 enforceSystemOrRoot("Only the system can request fstrim"); 6838 6839 // Before everything else, see whether we need to fstrim. 6840 try { 6841 IMountService ms = PackageHelper.getMountService(); 6842 if (ms != null) { 6843 final boolean isUpgrade = isUpgrade(); 6844 boolean doTrim = isUpgrade; 6845 if (doTrim) { 6846 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 6847 } else { 6848 final long interval = android.provider.Settings.Global.getLong( 6849 mContext.getContentResolver(), 6850 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 6851 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 6852 if (interval > 0) { 6853 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 6854 if (timeSinceLast > interval) { 6855 doTrim = true; 6856 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 6857 + "; running immediately"); 6858 } 6859 } 6860 } 6861 if (doTrim) { 6862 if (!isFirstBoot()) { 6863 try { 6864 ActivityManagerNative.getDefault().showBootMessage( 6865 mContext.getResources().getString( 6866 R.string.android_upgrading_fstrim), true); 6867 } catch (RemoteException e) { 6868 } 6869 } 6870 ms.runMaintenance(); 6871 } 6872 } else { 6873 Slog.e(TAG, "Mount service unavailable!"); 6874 } 6875 } catch (RemoteException e) { 6876 // Can't happen; MountService is local 6877 } 6878 } 6879 6880 @Override 6881 public void extractPackagesIfNeeded() { 6882 enforceSystemOrRoot("Only the system can request package extraction"); 6883 6884 // Extract pacakges only if profile-guided compilation is enabled because 6885 // otherwise BackgroundDexOptService will not dexopt them later. 6886 if (!isUpgrade()) { 6887 return; 6888 } 6889 6890 List<PackageParser.Package> pkgs; 6891 synchronized (mPackages) { 6892 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 6893 } 6894 6895 int curr = 0; 6896 int total = pkgs.size(); 6897 for (PackageParser.Package pkg : pkgs) { 6898 curr++; 6899 6900 if (DEBUG_DEXOPT) { 6901 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 6902 } 6903 6904 if (!isFirstBoot()) { 6905 try { 6906 ActivityManagerNative.getDefault().showBootMessage( 6907 mContext.getResources().getString(R.string.android_upgrading_apk, 6908 curr, total), true); 6909 } catch (RemoteException e) { 6910 } 6911 } 6912 6913 if (PackageDexOptimizer.canOptimizePackage(pkg)) { 6914 performDexOpt(pkg.packageName, null /* instructionSet */, 6915 false /* useProfiles */, true /* extractOnly */, false /* force */); 6916 } 6917 } 6918 } 6919 6920 @Override 6921 public void notifyPackageUse(String packageName) { 6922 synchronized (mPackages) { 6923 PackageParser.Package p = mPackages.get(packageName); 6924 if (p == null) { 6925 return; 6926 } 6927 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 6928 } 6929 } 6930 6931 // TODO: this is not used nor needed. Delete it. 6932 @Override 6933 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 6934 return performDexOptTraced(packageName, instructionSet, false /* useProfiles */, 6935 false /* extractOnly */, false /* force */); 6936 } 6937 6938 @Override 6939 public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles, 6940 boolean extractOnly, boolean force) { 6941 return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force); 6942 } 6943 6944 private boolean performDexOptTraced(String packageName, String instructionSet, 6945 boolean useProfiles, boolean extractOnly, boolean force) { 6946 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 6947 try { 6948 return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly, 6949 force); 6950 } finally { 6951 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6952 } 6953 } 6954 6955 private boolean performDexOptInternal(String packageName, String instructionSet, 6956 boolean useProfiles, boolean extractOnly, boolean force) { 6957 PackageParser.Package p; 6958 final String targetInstructionSet; 6959 synchronized (mPackages) { 6960 p = mPackages.get(packageName); 6961 if (p == null) { 6962 return false; 6963 } 6964 mPackageUsage.write(false); 6965 6966 targetInstructionSet = instructionSet != null ? instructionSet : 6967 getPrimaryInstructionSet(p.applicationInfo); 6968 } 6969 long callingId = Binder.clearCallingIdentity(); 6970 try { 6971 synchronized (mInstallLock) { 6972 final String[] instructionSets = new String[] { targetInstructionSet }; 6973 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 6974 useProfiles, extractOnly, force); 6975 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 6976 } 6977 } finally { 6978 Binder.restoreCallingIdentity(callingId); 6979 } 6980 } 6981 6982 public ArraySet<String> getOptimizablePackages() { 6983 ArraySet<String> pkgs = new ArraySet<String>(); 6984 synchronized (mPackages) { 6985 for (PackageParser.Package p : mPackages.values()) { 6986 if (PackageDexOptimizer.canOptimizePackage(p)) { 6987 pkgs.add(p.packageName); 6988 } 6989 } 6990 } 6991 return pkgs; 6992 } 6993 6994 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 6995 String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) { 6996 // Select the dex optimizer based on the force parameter. 6997 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 6998 // allocate an object here. 6999 PackageDexOptimizer pdo = force 7000 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7001 : mPackageDexOptimizer; 7002 7003 // Optimize all dependencies first. Note: we ignore the return value and march on 7004 // on errors. 7005 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7006 if (!deps.isEmpty()) { 7007 for (PackageParser.Package depPackage : deps) { 7008 // TODO: Analyze and investigate if we (should) profile libraries. 7009 // Currently this will do a full compilation of the library. 7010 pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */, 7011 false /* extractOnly */); 7012 } 7013 } 7014 7015 return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly); 7016 } 7017 7018 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7019 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7020 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7021 Set<String> collectedNames = new HashSet<>(); 7022 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7023 7024 retValue.remove(p); 7025 7026 return retValue; 7027 } else { 7028 return Collections.emptyList(); 7029 } 7030 } 7031 7032 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7033 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7034 if (!collectedNames.contains(p.packageName)) { 7035 collectedNames.add(p.packageName); 7036 collected.add(p); 7037 7038 if (p.usesLibraries != null) { 7039 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7040 } 7041 if (p.usesOptionalLibraries != null) { 7042 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7043 collectedNames); 7044 } 7045 } 7046 } 7047 7048 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7049 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7050 for (String libName : libs) { 7051 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7052 if (libPkg != null) { 7053 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7054 } 7055 } 7056 } 7057 7058 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7059 synchronized (mPackages) { 7060 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7061 if (lib != null && lib.apk != null) { 7062 return mPackages.get(lib.apk); 7063 } 7064 } 7065 return null; 7066 } 7067 7068 public void shutdown() { 7069 mPackageUsage.write(true); 7070 } 7071 7072 @Override 7073 public void forceDexOpt(String packageName) { 7074 enforceSystemOrRoot("forceDexOpt"); 7075 7076 PackageParser.Package pkg; 7077 synchronized (mPackages) { 7078 pkg = mPackages.get(packageName); 7079 if (pkg == null) { 7080 throw new IllegalArgumentException("Unknown package: " + packageName); 7081 } 7082 } 7083 7084 synchronized (mInstallLock) { 7085 final String[] instructionSets = new String[] { 7086 getPrimaryInstructionSet(pkg.applicationInfo) }; 7087 7088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7089 7090 // Whoever is calling forceDexOpt wants a fully compiled package. 7091 // Don't use profiles since that may cause compilation to be skipped. 7092 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7093 false /* useProfiles */, false /* extractOnly */, true /* force */); 7094 7095 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7096 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7097 throw new IllegalStateException("Failed to dexopt: " + res); 7098 } 7099 } 7100 } 7101 7102 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7103 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7104 Slog.w(TAG, "Unable to update from " + oldPkg.name 7105 + " to " + newPkg.packageName 7106 + ": old package not in system partition"); 7107 return false; 7108 } else if (mPackages.get(oldPkg.name) != null) { 7109 Slog.w(TAG, "Unable to update from " + oldPkg.name 7110 + " to " + newPkg.packageName 7111 + ": old package still exists"); 7112 return false; 7113 } 7114 return true; 7115 } 7116 7117 private boolean removeDataDirsLI(String volumeUuid, String packageName) { 7118 // TODO: triage flags as part of 26466827 7119 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7120 7121 boolean res = true; 7122 final int[] users = sUserManager.getUserIds(); 7123 for (int user : users) { 7124 try { 7125 mInstaller.destroyAppData(volumeUuid, packageName, user, flags); 7126 } catch (InstallerException e) { 7127 Slog.w(TAG, "Failed to delete data directory", e); 7128 res = false; 7129 } 7130 } 7131 return res; 7132 } 7133 7134 void removeCodePathLI(File codePath) { 7135 if (codePath.isDirectory()) { 7136 try { 7137 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7138 } catch (InstallerException e) { 7139 Slog.w(TAG, "Failed to remove code path", e); 7140 } 7141 } else { 7142 codePath.delete(); 7143 } 7144 } 7145 7146 void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) { 7147 try { 7148 mInstaller.destroyAppData(volumeUuid, packageName, userId, flags); 7149 } catch (InstallerException e) { 7150 Slog.w(TAG, "Failed to destroy app data", e); 7151 } 7152 } 7153 7154 void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags, 7155 int appId, String seinfo) { 7156 try { 7157 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo); 7158 } catch (InstallerException e) { 7159 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 7160 } 7161 } 7162 7163 private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 7164 final PackageParser.Package pkg; 7165 synchronized (mPackages) { 7166 pkg = mPackages.get(packageName); 7167 } 7168 if (pkg == null) { 7169 Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName); 7170 return; 7171 } 7172 deleteCodeCacheDirsLI(pkg); 7173 } 7174 7175 private void deleteCodeCacheDirsLI(PackageParser.Package pkg) { 7176 // TODO: triage flags as part of 26466827 7177 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 7178 7179 int[] users = sUserManager.getUserIds(); 7180 int res = 0; 7181 for (int user : users) { 7182 // Remove the parent code cache 7183 try { 7184 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user, 7185 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7186 } catch (InstallerException e) { 7187 Slog.w(TAG, "Failed to delete code cache directory", e); 7188 } 7189 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7190 for (int i = 0; i < childCount; i++) { 7191 PackageParser.Package childPkg = pkg.childPackages.get(i); 7192 // Remove the child code cache 7193 try { 7194 mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName, 7195 user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 7196 } catch (InstallerException e) { 7197 Slog.w(TAG, "Failed to delete code cache directory", e); 7198 } 7199 } 7200 } 7201 } 7202 7203 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7204 long lastUpdateTime) { 7205 // Set parent install/update time 7206 PackageSetting ps = (PackageSetting) pkg.mExtras; 7207 if (ps != null) { 7208 ps.firstInstallTime = firstInstallTime; 7209 ps.lastUpdateTime = lastUpdateTime; 7210 } 7211 // Set children install/update time 7212 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7213 for (int i = 0; i < childCount; i++) { 7214 PackageParser.Package childPkg = pkg.childPackages.get(i); 7215 ps = (PackageSetting) childPkg.mExtras; 7216 if (ps != null) { 7217 ps.firstInstallTime = firstInstallTime; 7218 ps.lastUpdateTime = lastUpdateTime; 7219 } 7220 } 7221 } 7222 7223 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7224 PackageParser.Package changingLib) { 7225 if (file.path != null) { 7226 usesLibraryFiles.add(file.path); 7227 return; 7228 } 7229 PackageParser.Package p = mPackages.get(file.apk); 7230 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7231 // If we are doing this while in the middle of updating a library apk, 7232 // then we need to make sure to use that new apk for determining the 7233 // dependencies here. (We haven't yet finished committing the new apk 7234 // to the package manager state.) 7235 if (p == null || p.packageName.equals(changingLib.packageName)) { 7236 p = changingLib; 7237 } 7238 } 7239 if (p != null) { 7240 usesLibraryFiles.addAll(p.getAllCodePaths()); 7241 } 7242 } 7243 7244 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7245 PackageParser.Package changingLib) throws PackageManagerException { 7246 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7247 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7248 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7249 for (int i=0; i<N; i++) { 7250 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7251 if (file == null) { 7252 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7253 "Package " + pkg.packageName + " requires unavailable shared library " 7254 + pkg.usesLibraries.get(i) + "; failing!"); 7255 } 7256 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7257 } 7258 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7259 for (int i=0; i<N; i++) { 7260 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7261 if (file == null) { 7262 Slog.w(TAG, "Package " + pkg.packageName 7263 + " desires unavailable shared library " 7264 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7265 } else { 7266 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7267 } 7268 } 7269 N = usesLibraryFiles.size(); 7270 if (N > 0) { 7271 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7272 } else { 7273 pkg.usesLibraryFiles = null; 7274 } 7275 } 7276 } 7277 7278 private static boolean hasString(List<String> list, List<String> which) { 7279 if (list == null) { 7280 return false; 7281 } 7282 for (int i=list.size()-1; i>=0; i--) { 7283 for (int j=which.size()-1; j>=0; j--) { 7284 if (which.get(j).equals(list.get(i))) { 7285 return true; 7286 } 7287 } 7288 } 7289 return false; 7290 } 7291 7292 private void updateAllSharedLibrariesLPw() { 7293 for (PackageParser.Package pkg : mPackages.values()) { 7294 try { 7295 updateSharedLibrariesLPw(pkg, null); 7296 } catch (PackageManagerException e) { 7297 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7298 } 7299 } 7300 } 7301 7302 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7303 PackageParser.Package changingPkg) { 7304 ArrayList<PackageParser.Package> res = null; 7305 for (PackageParser.Package pkg : mPackages.values()) { 7306 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7307 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7308 if (res == null) { 7309 res = new ArrayList<PackageParser.Package>(); 7310 } 7311 res.add(pkg); 7312 try { 7313 updateSharedLibrariesLPw(pkg, changingPkg); 7314 } catch (PackageManagerException e) { 7315 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7316 } 7317 } 7318 } 7319 return res; 7320 } 7321 7322 /** 7323 * Derive the value of the {@code cpuAbiOverride} based on the provided 7324 * value and an optional stored value from the package settings. 7325 */ 7326 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7327 String cpuAbiOverride = null; 7328 7329 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7330 cpuAbiOverride = null; 7331 } else if (abiOverride != null) { 7332 cpuAbiOverride = abiOverride; 7333 } else if (settings != null) { 7334 cpuAbiOverride = settings.cpuAbiOverrideString; 7335 } 7336 7337 return cpuAbiOverride; 7338 } 7339 7340 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7341 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7343 // If the package has children and this is the first dive in the function 7344 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7345 // whether all packages (parent and children) would be successfully scanned 7346 // before the actual scan since scanning mutates internal state and we want 7347 // to atomically install the package and its children. 7348 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7349 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7350 scanFlags |= SCAN_CHECK_ONLY; 7351 } 7352 } else { 7353 scanFlags &= ~SCAN_CHECK_ONLY; 7354 } 7355 7356 final PackageParser.Package scannedPkg; 7357 try { 7358 // Scan the parent 7359 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7360 // Scan the children 7361 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7362 for (int i = 0; i < childCount; i++) { 7363 PackageParser.Package childPkg = pkg.childPackages.get(i); 7364 scanPackageLI(childPkg, parseFlags, 7365 scanFlags, currentTime, user); 7366 } 7367 } finally { 7368 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7369 } 7370 7371 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7372 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7373 } 7374 7375 return scannedPkg; 7376 } 7377 7378 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7379 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7380 boolean success = false; 7381 try { 7382 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7383 currentTime, user); 7384 success = true; 7385 return res; 7386 } finally { 7387 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7388 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 7389 } 7390 } 7391 } 7392 7393 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7394 int scanFlags, long currentTime, UserHandle user) 7395 throws PackageManagerException { 7396 final File scanFile = new File(pkg.codePath); 7397 if (pkg.applicationInfo.getCodePath() == null || 7398 pkg.applicationInfo.getResourcePath() == null) { 7399 // Bail out. The resource and code paths haven't been set. 7400 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7401 "Code and resource paths haven't been set correctly"); 7402 } 7403 7404 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7405 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7406 } else { 7407 // Only allow system apps to be flagged as core apps. 7408 pkg.coreApp = false; 7409 } 7410 7411 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7412 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7413 } 7414 7415 if (mCustomResolverComponentName != null && 7416 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7417 setUpCustomResolverActivity(pkg); 7418 } 7419 7420 if (pkg.packageName.equals("android")) { 7421 synchronized (mPackages) { 7422 if (mAndroidApplication != null) { 7423 Slog.w(TAG, "*************************************************"); 7424 Slog.w(TAG, "Core android package being redefined. Skipping."); 7425 Slog.w(TAG, " file=" + scanFile); 7426 Slog.w(TAG, "*************************************************"); 7427 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7428 "Core android package being redefined. Skipping."); 7429 } 7430 7431 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7432 // Set up information for our fall-back user intent resolution activity. 7433 mPlatformPackage = pkg; 7434 pkg.mVersionCode = mSdkVersion; 7435 mAndroidApplication = pkg.applicationInfo; 7436 7437 if (!mResolverReplaced) { 7438 mResolveActivity.applicationInfo = mAndroidApplication; 7439 mResolveActivity.name = ResolverActivity.class.getName(); 7440 mResolveActivity.packageName = mAndroidApplication.packageName; 7441 mResolveActivity.processName = "system:ui"; 7442 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7443 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7444 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7445 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7446 mResolveActivity.exported = true; 7447 mResolveActivity.enabled = true; 7448 mResolveInfo.activityInfo = mResolveActivity; 7449 mResolveInfo.priority = 0; 7450 mResolveInfo.preferredOrder = 0; 7451 mResolveInfo.match = 0; 7452 mResolveComponentName = new ComponentName( 7453 mAndroidApplication.packageName, mResolveActivity.name); 7454 } 7455 } 7456 } 7457 } 7458 7459 if (DEBUG_PACKAGE_SCANNING) { 7460 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7461 Log.d(TAG, "Scanning package " + pkg.packageName); 7462 } 7463 7464 synchronized (mPackages) { 7465 if (mPackages.containsKey(pkg.packageName) 7466 || mSharedLibraries.containsKey(pkg.packageName)) { 7467 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7468 "Application package " + pkg.packageName 7469 + " already installed. Skipping duplicate."); 7470 } 7471 7472 // If we're only installing presumed-existing packages, require that the 7473 // scanned APK is both already known and at the path previously established 7474 // for it. Previously unknown packages we pick up normally, but if we have an 7475 // a priori expectation about this package's install presence, enforce it. 7476 // With a singular exception for new system packages. When an OTA contains 7477 // a new system package, we allow the codepath to change from a system location 7478 // to the user-installed location. If we don't allow this change, any newer, 7479 // user-installed version of the application will be ignored. 7480 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7481 if (mExpectingBetter.containsKey(pkg.packageName)) { 7482 logCriticalInfo(Log.WARN, 7483 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7484 } else { 7485 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7486 if (known != null) { 7487 if (DEBUG_PACKAGE_SCANNING) { 7488 Log.d(TAG, "Examining " + pkg.codePath 7489 + " and requiring known paths " + known.codePathString 7490 + " & " + known.resourcePathString); 7491 } 7492 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7493 || !pkg.applicationInfo.getResourcePath().equals( 7494 known.resourcePathString)) { 7495 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7496 "Application package " + pkg.packageName 7497 + " found at " + pkg.applicationInfo.getCodePath() 7498 + " but expected at " + known.codePathString 7499 + "; ignoring."); 7500 } 7501 } 7502 } 7503 } 7504 } 7505 7506 // Initialize package source and resource directories 7507 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7508 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7509 7510 SharedUserSetting suid = null; 7511 PackageSetting pkgSetting = null; 7512 7513 if (!isSystemApp(pkg)) { 7514 // Only system apps can use these features. 7515 pkg.mOriginalPackages = null; 7516 pkg.mRealPackage = null; 7517 pkg.mAdoptPermissions = null; 7518 } 7519 7520 // Getting the package setting may have a side-effect, so if we 7521 // are only checking if scan would succeed, stash a copy of the 7522 // old setting to restore at the end. 7523 PackageSetting nonMutatedPs = null; 7524 7525 // writer 7526 synchronized (mPackages) { 7527 if (pkg.mSharedUserId != null) { 7528 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7529 if (suid == null) { 7530 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7531 "Creating application package " + pkg.packageName 7532 + " for shared user failed"); 7533 } 7534 if (DEBUG_PACKAGE_SCANNING) { 7535 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7536 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7537 + "): packages=" + suid.packages); 7538 } 7539 } 7540 7541 // Check if we are renaming from an original package name. 7542 PackageSetting origPackage = null; 7543 String realName = null; 7544 if (pkg.mOriginalPackages != null) { 7545 // This package may need to be renamed to a previously 7546 // installed name. Let's check on that... 7547 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7548 if (pkg.mOriginalPackages.contains(renamed)) { 7549 // This package had originally been installed as the 7550 // original name, and we have already taken care of 7551 // transitioning to the new one. Just update the new 7552 // one to continue using the old name. 7553 realName = pkg.mRealPackage; 7554 if (!pkg.packageName.equals(renamed)) { 7555 // Callers into this function may have already taken 7556 // care of renaming the package; only do it here if 7557 // it is not already done. 7558 pkg.setPackageName(renamed); 7559 } 7560 7561 } else { 7562 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7563 if ((origPackage = mSettings.peekPackageLPr( 7564 pkg.mOriginalPackages.get(i))) != null) { 7565 // We do have the package already installed under its 7566 // original name... should we use it? 7567 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7568 // New package is not compatible with original. 7569 origPackage = null; 7570 continue; 7571 } else if (origPackage.sharedUser != null) { 7572 // Make sure uid is compatible between packages. 7573 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7574 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7575 + " to " + pkg.packageName + ": old uid " 7576 + origPackage.sharedUser.name 7577 + " differs from " + pkg.mSharedUserId); 7578 origPackage = null; 7579 continue; 7580 } 7581 } else { 7582 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7583 + pkg.packageName + " to old name " + origPackage.name); 7584 } 7585 break; 7586 } 7587 } 7588 } 7589 } 7590 7591 if (mTransferedPackages.contains(pkg.packageName)) { 7592 Slog.w(TAG, "Package " + pkg.packageName 7593 + " was transferred to another, but its .apk remains"); 7594 } 7595 7596 // See comments in nonMutatedPs declaration 7597 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7598 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7599 if (foundPs != null) { 7600 nonMutatedPs = new PackageSetting(foundPs); 7601 } 7602 } 7603 7604 // Just create the setting, don't add it yet. For already existing packages 7605 // the PkgSetting exists already and doesn't have to be created. 7606 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7607 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7608 pkg.applicationInfo.primaryCpuAbi, 7609 pkg.applicationInfo.secondaryCpuAbi, 7610 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7611 user, false); 7612 if (pkgSetting == null) { 7613 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7614 "Creating application package " + pkg.packageName + " failed"); 7615 } 7616 7617 if (pkgSetting.origPackage != null) { 7618 // If we are first transitioning from an original package, 7619 // fix up the new package's name now. We need to do this after 7620 // looking up the package under its new name, so getPackageLP 7621 // can take care of fiddling things correctly. 7622 pkg.setPackageName(origPackage.name); 7623 7624 // File a report about this. 7625 String msg = "New package " + pkgSetting.realName 7626 + " renamed to replace old package " + pkgSetting.name; 7627 reportSettingsProblem(Log.WARN, msg); 7628 7629 // Make a note of it. 7630 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7631 mTransferedPackages.add(origPackage.name); 7632 } 7633 7634 // No longer need to retain this. 7635 pkgSetting.origPackage = null; 7636 } 7637 7638 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7639 // Make a note of it. 7640 mTransferedPackages.add(pkg.packageName); 7641 } 7642 7643 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7644 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7645 } 7646 7647 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7648 // Check all shared libraries and map to their actual file path. 7649 // We only do this here for apps not on a system dir, because those 7650 // are the only ones that can fail an install due to this. We 7651 // will take care of the system apps by updating all of their 7652 // library paths after the scan is done. 7653 updateSharedLibrariesLPw(pkg, null); 7654 } 7655 7656 if (mFoundPolicyFile) { 7657 SELinuxMMAC.assignSeinfoValue(pkg); 7658 } 7659 7660 pkg.applicationInfo.uid = pkgSetting.appId; 7661 pkg.mExtras = pkgSetting; 7662 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7663 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7664 // We just determined the app is signed correctly, so bring 7665 // over the latest parsed certs. 7666 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7667 } else { 7668 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7669 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7670 "Package " + pkg.packageName + " upgrade keys do not match the " 7671 + "previously installed version"); 7672 } else { 7673 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7674 String msg = "System package " + pkg.packageName 7675 + " signature changed; retaining data."; 7676 reportSettingsProblem(Log.WARN, msg); 7677 } 7678 } 7679 } else { 7680 try { 7681 verifySignaturesLP(pkgSetting, pkg); 7682 // We just determined the app is signed correctly, so bring 7683 // over the latest parsed certs. 7684 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7685 } catch (PackageManagerException e) { 7686 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7687 throw e; 7688 } 7689 // The signature has changed, but this package is in the system 7690 // image... let's recover! 7691 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7692 // However... if this package is part of a shared user, but it 7693 // doesn't match the signature of the shared user, let's fail. 7694 // What this means is that you can't change the signatures 7695 // associated with an overall shared user, which doesn't seem all 7696 // that unreasonable. 7697 if (pkgSetting.sharedUser != null) { 7698 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7699 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7700 throw new PackageManagerException( 7701 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7702 "Signature mismatch for shared user: " 7703 + pkgSetting.sharedUser); 7704 } 7705 } 7706 // File a report about this. 7707 String msg = "System package " + pkg.packageName 7708 + " signature changed; retaining data."; 7709 reportSettingsProblem(Log.WARN, msg); 7710 } 7711 } 7712 // Verify that this new package doesn't have any content providers 7713 // that conflict with existing packages. Only do this if the 7714 // package isn't already installed, since we don't want to break 7715 // things that are installed. 7716 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7717 final int N = pkg.providers.size(); 7718 int i; 7719 for (i=0; i<N; i++) { 7720 PackageParser.Provider p = pkg.providers.get(i); 7721 if (p.info.authority != null) { 7722 String names[] = p.info.authority.split(";"); 7723 for (int j = 0; j < names.length; j++) { 7724 if (mProvidersByAuthority.containsKey(names[j])) { 7725 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7726 final String otherPackageName = 7727 ((other != null && other.getComponentName() != null) ? 7728 other.getComponentName().getPackageName() : "?"); 7729 throw new PackageManagerException( 7730 INSTALL_FAILED_CONFLICTING_PROVIDER, 7731 "Can't install because provider name " + names[j] 7732 + " (in package " + pkg.applicationInfo.packageName 7733 + ") is already used by " + otherPackageName); 7734 } 7735 } 7736 } 7737 } 7738 } 7739 7740 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7741 // This package wants to adopt ownership of permissions from 7742 // another package. 7743 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7744 final String origName = pkg.mAdoptPermissions.get(i); 7745 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7746 if (orig != null) { 7747 if (verifyPackageUpdateLPr(orig, pkg)) { 7748 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7749 + pkg.packageName); 7750 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7751 } 7752 } 7753 } 7754 } 7755 } 7756 7757 final String pkgName = pkg.packageName; 7758 7759 final long scanFileTime = scanFile.lastModified(); 7760 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 7761 pkg.applicationInfo.processName = fixProcessName( 7762 pkg.applicationInfo.packageName, 7763 pkg.applicationInfo.processName, 7764 pkg.applicationInfo.uid); 7765 7766 if (pkg != mPlatformPackage) { 7767 // Get all of our default paths setup 7768 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 7769 } 7770 7771 final String path = scanFile.getPath(); 7772 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 7773 7774 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 7775 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 7776 7777 // Some system apps still use directory structure for native libraries 7778 // in which case we might end up not detecting abi solely based on apk 7779 // structure. Try to detect abi based on directory structure. 7780 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 7781 pkg.applicationInfo.primaryCpuAbi == null) { 7782 setBundledAppAbisAndRoots(pkg, pkgSetting); 7783 setNativeLibraryPaths(pkg); 7784 } 7785 7786 } else { 7787 if ((scanFlags & SCAN_MOVE) != 0) { 7788 // We haven't run dex-opt for this move (since we've moved the compiled output too) 7789 // but we already have this packages package info in the PackageSetting. We just 7790 // use that and derive the native library path based on the new codepath. 7791 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 7792 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 7793 } 7794 7795 // Set native library paths again. For moves, the path will be updated based on the 7796 // ABIs we've determined above. For non-moves, the path will be updated based on the 7797 // ABIs we determined during compilation, but the path will depend on the final 7798 // package path (after the rename away from the stage path). 7799 setNativeLibraryPaths(pkg); 7800 } 7801 7802 // This is a special case for the "system" package, where the ABI is 7803 // dictated by the zygote configuration (and init.rc). We should keep track 7804 // of this ABI so that we can deal with "normal" applications that run under 7805 // the same UID correctly. 7806 if (mPlatformPackage == pkg) { 7807 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 7808 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 7809 } 7810 7811 // If there's a mismatch between the abi-override in the package setting 7812 // and the abiOverride specified for the install. Warn about this because we 7813 // would've already compiled the app without taking the package setting into 7814 // account. 7815 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 7816 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 7817 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 7818 " for package " + pkg.packageName); 7819 } 7820 } 7821 7822 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7823 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7824 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 7825 7826 // Copy the derived override back to the parsed package, so that we can 7827 // update the package settings accordingly. 7828 pkg.cpuAbiOverride = cpuAbiOverride; 7829 7830 if (DEBUG_ABI_SELECTION) { 7831 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 7832 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 7833 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 7834 } 7835 7836 // Push the derived path down into PackageSettings so we know what to 7837 // clean up at uninstall time. 7838 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 7839 7840 if (DEBUG_ABI_SELECTION) { 7841 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 7842 " primary=" + pkg.applicationInfo.primaryCpuAbi + 7843 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 7844 } 7845 7846 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 7847 // We don't do this here during boot because we can do it all 7848 // at once after scanning all existing packages. 7849 // 7850 // We also do this *before* we perform dexopt on this package, so that 7851 // we can avoid redundant dexopts, and also to make sure we've got the 7852 // code and package path correct. 7853 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 7854 pkg, true /* boot complete */); 7855 } 7856 7857 if (mFactoryTest && pkg.requestedPermissions.contains( 7858 android.Manifest.permission.FACTORY_TEST)) { 7859 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 7860 } 7861 7862 ArrayList<PackageParser.Package> clientLibPkgs = null; 7863 7864 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7865 if (nonMutatedPs != null) { 7866 synchronized (mPackages) { 7867 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 7868 } 7869 } 7870 return pkg; 7871 } 7872 7873 // Only privileged apps and updated privileged apps can add child packages. 7874 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 7875 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 7876 throw new PackageManagerException("Only privileged apps and updated " 7877 + "privileged apps can add child packages. Ignoring package " 7878 + pkg.packageName); 7879 } 7880 final int childCount = pkg.childPackages.size(); 7881 for (int i = 0; i < childCount; i++) { 7882 PackageParser.Package childPkg = pkg.childPackages.get(i); 7883 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 7884 childPkg.packageName)) { 7885 throw new PackageManagerException("Cannot override a child package of " 7886 + "another disabled system app. Ignoring package " + pkg.packageName); 7887 } 7888 } 7889 } 7890 7891 // writer 7892 synchronized (mPackages) { 7893 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7894 // Only system apps can add new shared libraries. 7895 if (pkg.libraryNames != null) { 7896 for (int i=0; i<pkg.libraryNames.size(); i++) { 7897 String name = pkg.libraryNames.get(i); 7898 boolean allowed = false; 7899 if (pkg.isUpdatedSystemApp()) { 7900 // New library entries can only be added through the 7901 // system image. This is important to get rid of a lot 7902 // of nasty edge cases: for example if we allowed a non- 7903 // system update of the app to add a library, then uninstalling 7904 // the update would make the library go away, and assumptions 7905 // we made such as through app install filtering would now 7906 // have allowed apps on the device which aren't compatible 7907 // with it. Better to just have the restriction here, be 7908 // conservative, and create many fewer cases that can negatively 7909 // impact the user experience. 7910 final PackageSetting sysPs = mSettings 7911 .getDisabledSystemPkgLPr(pkg.packageName); 7912 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 7913 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 7914 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 7915 allowed = true; 7916 break; 7917 } 7918 } 7919 } 7920 } else { 7921 allowed = true; 7922 } 7923 if (allowed) { 7924 if (!mSharedLibraries.containsKey(name)) { 7925 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 7926 } else if (!name.equals(pkg.packageName)) { 7927 Slog.w(TAG, "Package " + pkg.packageName + " library " 7928 + name + " already exists; skipping"); 7929 } 7930 } else { 7931 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 7932 + name + " that is not declared on system image; skipping"); 7933 } 7934 } 7935 if ((scanFlags & SCAN_BOOTING) == 0) { 7936 // If we are not booting, we need to update any applications 7937 // that are clients of our shared library. If we are booting, 7938 // this will all be done once the scan is complete. 7939 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 7940 } 7941 } 7942 } 7943 } 7944 7945 // Request the ActivityManager to kill the process(only for existing packages) 7946 // so that we do not end up in a confused state while the user is still using the older 7947 // version of the application while the new one gets installed. 7948 final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0; 7949 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 7950 if (killApp) { 7951 if (isReplacing) { 7952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication"); 7953 7954 killApplication(pkg.applicationInfo.packageName, 7955 pkg.applicationInfo.uid, "replace pkg"); 7956 7957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7958 } 7959 } 7960 7961 // Also need to kill any apps that are dependent on the library. 7962 if (clientLibPkgs != null) { 7963 for (int i=0; i<clientLibPkgs.size(); i++) { 7964 PackageParser.Package clientPkg = clientLibPkgs.get(i); 7965 killApplication(clientPkg.applicationInfo.packageName, 7966 clientPkg.applicationInfo.uid, "update lib"); 7967 } 7968 } 7969 7970 // Make sure we're not adding any bogus keyset info 7971 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7972 ksms.assertScannedPackageValid(pkg); 7973 7974 // writer 7975 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 7976 7977 boolean createIdmapFailed = false; 7978 synchronized (mPackages) { 7979 // We don't expect installation to fail beyond this point 7980 7981 // Add the new setting to mSettings 7982 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 7983 // Add the new setting to mPackages 7984 mPackages.put(pkg.applicationInfo.packageName, pkg); 7985 // Make sure we don't accidentally delete its data. 7986 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 7987 while (iter.hasNext()) { 7988 PackageCleanItem item = iter.next(); 7989 if (pkgName.equals(item.packageName)) { 7990 iter.remove(); 7991 } 7992 } 7993 7994 // Take care of first install / last update times. 7995 if (currentTime != 0) { 7996 if (pkgSetting.firstInstallTime == 0) { 7997 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 7998 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 7999 pkgSetting.lastUpdateTime = currentTime; 8000 } 8001 } else if (pkgSetting.firstInstallTime == 0) { 8002 // We need *something*. Take time time stamp of the file. 8003 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8004 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8005 if (scanFileTime != pkgSetting.timeStamp) { 8006 // A package on the system image has changed; consider this 8007 // to be an update. 8008 pkgSetting.lastUpdateTime = scanFileTime; 8009 } 8010 } 8011 8012 // Add the package's KeySets to the global KeySetManagerService 8013 ksms.addScannedPackageLPw(pkg); 8014 8015 int N = pkg.providers.size(); 8016 StringBuilder r = null; 8017 int i; 8018 for (i=0; i<N; i++) { 8019 PackageParser.Provider p = pkg.providers.get(i); 8020 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8021 p.info.processName, pkg.applicationInfo.uid); 8022 mProviders.addProvider(p); 8023 p.syncable = p.info.isSyncable; 8024 if (p.info.authority != null) { 8025 String names[] = p.info.authority.split(";"); 8026 p.info.authority = null; 8027 for (int j = 0; j < names.length; j++) { 8028 if (j == 1 && p.syncable) { 8029 // We only want the first authority for a provider to possibly be 8030 // syncable, so if we already added this provider using a different 8031 // authority clear the syncable flag. We copy the provider before 8032 // changing it because the mProviders object contains a reference 8033 // to a provider that we don't want to change. 8034 // Only do this for the second authority since the resulting provider 8035 // object can be the same for all future authorities for this provider. 8036 p = new PackageParser.Provider(p); 8037 p.syncable = false; 8038 } 8039 if (!mProvidersByAuthority.containsKey(names[j])) { 8040 mProvidersByAuthority.put(names[j], p); 8041 if (p.info.authority == null) { 8042 p.info.authority = names[j]; 8043 } else { 8044 p.info.authority = p.info.authority + ";" + names[j]; 8045 } 8046 if (DEBUG_PACKAGE_SCANNING) { 8047 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8048 Log.d(TAG, "Registered content provider: " + names[j] 8049 + ", className = " + p.info.name + ", isSyncable = " 8050 + p.info.isSyncable); 8051 } 8052 } else { 8053 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8054 Slog.w(TAG, "Skipping provider name " + names[j] + 8055 " (in package " + pkg.applicationInfo.packageName + 8056 "): name already used by " 8057 + ((other != null && other.getComponentName() != null) 8058 ? other.getComponentName().getPackageName() : "?")); 8059 } 8060 } 8061 } 8062 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8063 if (r == null) { 8064 r = new StringBuilder(256); 8065 } else { 8066 r.append(' '); 8067 } 8068 r.append(p.info.name); 8069 } 8070 } 8071 if (r != null) { 8072 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8073 } 8074 8075 N = pkg.services.size(); 8076 r = null; 8077 for (i=0; i<N; i++) { 8078 PackageParser.Service s = pkg.services.get(i); 8079 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8080 s.info.processName, pkg.applicationInfo.uid); 8081 mServices.addService(s); 8082 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8083 if (r == null) { 8084 r = new StringBuilder(256); 8085 } else { 8086 r.append(' '); 8087 } 8088 r.append(s.info.name); 8089 } 8090 } 8091 if (r != null) { 8092 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8093 } 8094 8095 N = pkg.receivers.size(); 8096 r = null; 8097 for (i=0; i<N; i++) { 8098 PackageParser.Activity a = pkg.receivers.get(i); 8099 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8100 a.info.processName, pkg.applicationInfo.uid); 8101 mReceivers.addActivity(a, "receiver"); 8102 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8103 if (r == null) { 8104 r = new StringBuilder(256); 8105 } else { 8106 r.append(' '); 8107 } 8108 r.append(a.info.name); 8109 } 8110 } 8111 if (r != null) { 8112 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8113 } 8114 8115 N = pkg.activities.size(); 8116 r = null; 8117 for (i=0; i<N; i++) { 8118 PackageParser.Activity a = pkg.activities.get(i); 8119 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8120 a.info.processName, pkg.applicationInfo.uid); 8121 mActivities.addActivity(a, "activity"); 8122 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8123 if (r == null) { 8124 r = new StringBuilder(256); 8125 } else { 8126 r.append(' '); 8127 } 8128 r.append(a.info.name); 8129 } 8130 } 8131 if (r != null) { 8132 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8133 } 8134 8135 N = pkg.permissionGroups.size(); 8136 r = null; 8137 for (i=0; i<N; i++) { 8138 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8139 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8140 if (cur == null) { 8141 mPermissionGroups.put(pg.info.name, pg); 8142 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8143 if (r == null) { 8144 r = new StringBuilder(256); 8145 } else { 8146 r.append(' '); 8147 } 8148 r.append(pg.info.name); 8149 } 8150 } else { 8151 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8152 + pg.info.packageName + " ignored: original from " 8153 + cur.info.packageName); 8154 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8155 if (r == null) { 8156 r = new StringBuilder(256); 8157 } else { 8158 r.append(' '); 8159 } 8160 r.append("DUP:"); 8161 r.append(pg.info.name); 8162 } 8163 } 8164 } 8165 if (r != null) { 8166 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8167 } 8168 8169 N = pkg.permissions.size(); 8170 r = null; 8171 for (i=0; i<N; i++) { 8172 PackageParser.Permission p = pkg.permissions.get(i); 8173 8174 // Assume by default that we did not install this permission into the system. 8175 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8176 8177 // Now that permission groups have a special meaning, we ignore permission 8178 // groups for legacy apps to prevent unexpected behavior. In particular, 8179 // permissions for one app being granted to someone just becase they happen 8180 // to be in a group defined by another app (before this had no implications). 8181 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8182 p.group = mPermissionGroups.get(p.info.group); 8183 // Warn for a permission in an unknown group. 8184 if (p.info.group != null && p.group == null) { 8185 Slog.w(TAG, "Permission " + p.info.name + " from package " 8186 + p.info.packageName + " in an unknown group " + p.info.group); 8187 } 8188 } 8189 8190 ArrayMap<String, BasePermission> permissionMap = 8191 p.tree ? mSettings.mPermissionTrees 8192 : mSettings.mPermissions; 8193 BasePermission bp = permissionMap.get(p.info.name); 8194 8195 // Allow system apps to redefine non-system permissions 8196 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8197 final boolean currentOwnerIsSystem = (bp.perm != null 8198 && isSystemApp(bp.perm.owner)); 8199 if (isSystemApp(p.owner)) { 8200 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8201 // It's a built-in permission and no owner, take ownership now 8202 bp.packageSetting = pkgSetting; 8203 bp.perm = p; 8204 bp.uid = pkg.applicationInfo.uid; 8205 bp.sourcePackage = p.info.packageName; 8206 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8207 } else if (!currentOwnerIsSystem) { 8208 String msg = "New decl " + p.owner + " of permission " 8209 + p.info.name + " is system; overriding " + bp.sourcePackage; 8210 reportSettingsProblem(Log.WARN, msg); 8211 bp = null; 8212 } 8213 } 8214 } 8215 8216 if (bp == null) { 8217 bp = new BasePermission(p.info.name, p.info.packageName, 8218 BasePermission.TYPE_NORMAL); 8219 permissionMap.put(p.info.name, bp); 8220 } 8221 8222 if (bp.perm == null) { 8223 if (bp.sourcePackage == null 8224 || bp.sourcePackage.equals(p.info.packageName)) { 8225 BasePermission tree = findPermissionTreeLP(p.info.name); 8226 if (tree == null 8227 || tree.sourcePackage.equals(p.info.packageName)) { 8228 bp.packageSetting = pkgSetting; 8229 bp.perm = p; 8230 bp.uid = pkg.applicationInfo.uid; 8231 bp.sourcePackage = p.info.packageName; 8232 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8233 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8234 if (r == null) { 8235 r = new StringBuilder(256); 8236 } else { 8237 r.append(' '); 8238 } 8239 r.append(p.info.name); 8240 } 8241 } else { 8242 Slog.w(TAG, "Permission " + p.info.name + " from package " 8243 + p.info.packageName + " ignored: base tree " 8244 + tree.name + " is from package " 8245 + tree.sourcePackage); 8246 } 8247 } else { 8248 Slog.w(TAG, "Permission " + p.info.name + " from package " 8249 + p.info.packageName + " ignored: original from " 8250 + bp.sourcePackage); 8251 } 8252 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8253 if (r == null) { 8254 r = new StringBuilder(256); 8255 } else { 8256 r.append(' '); 8257 } 8258 r.append("DUP:"); 8259 r.append(p.info.name); 8260 } 8261 if (bp.perm == p) { 8262 bp.protectionLevel = p.info.protectionLevel; 8263 } 8264 } 8265 8266 if (r != null) { 8267 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8268 } 8269 8270 N = pkg.instrumentation.size(); 8271 r = null; 8272 for (i=0; i<N; i++) { 8273 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8274 a.info.packageName = pkg.applicationInfo.packageName; 8275 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8276 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8277 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8278 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8279 a.info.dataDir = pkg.applicationInfo.dataDir; 8280 a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir; 8281 a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir; 8282 8283 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8284 // need other information about the application, like the ABI and what not ? 8285 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8286 mInstrumentation.put(a.getComponentName(), a); 8287 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8288 if (r == null) { 8289 r = new StringBuilder(256); 8290 } else { 8291 r.append(' '); 8292 } 8293 r.append(a.info.name); 8294 } 8295 } 8296 if (r != null) { 8297 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8298 } 8299 8300 if (pkg.protectedBroadcasts != null) { 8301 N = pkg.protectedBroadcasts.size(); 8302 for (i=0; i<N; i++) { 8303 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8304 } 8305 } 8306 8307 pkgSetting.setTimeStamp(scanFileTime); 8308 8309 // Create idmap files for pairs of (packages, overlay packages). 8310 // Note: "android", ie framework-res.apk, is handled by native layers. 8311 if (pkg.mOverlayTarget != null) { 8312 // This is an overlay package. 8313 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8314 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8315 mOverlays.put(pkg.mOverlayTarget, 8316 new ArrayMap<String, PackageParser.Package>()); 8317 } 8318 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8319 map.put(pkg.packageName, pkg); 8320 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8321 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8322 createIdmapFailed = true; 8323 } 8324 } 8325 } else if (mOverlays.containsKey(pkg.packageName) && 8326 !pkg.packageName.equals("android")) { 8327 // This is a regular package, with one or more known overlay packages. 8328 createIdmapsForPackageLI(pkg); 8329 } 8330 } 8331 8332 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8333 8334 if (createIdmapFailed) { 8335 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8336 "scanPackageLI failed to createIdmap"); 8337 } 8338 return pkg; 8339 } 8340 8341 /** 8342 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8343 * is derived purely on the basis of the contents of {@code scanFile} and 8344 * {@code cpuAbiOverride}. 8345 * 8346 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8347 */ 8348 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8349 String cpuAbiOverride, boolean extractLibs) 8350 throws PackageManagerException { 8351 // TODO: We can probably be smarter about this stuff. For installed apps, 8352 // we can calculate this information at install time once and for all. For 8353 // system apps, we can probably assume that this information doesn't change 8354 // after the first boot scan. As things stand, we do lots of unnecessary work. 8355 8356 // Give ourselves some initial paths; we'll come back for another 8357 // pass once we've determined ABI below. 8358 setNativeLibraryPaths(pkg); 8359 8360 // We would never need to extract libs for forward-locked and external packages, 8361 // since the container service will do it for us. We shouldn't attempt to 8362 // extract libs from system app when it was not updated. 8363 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8364 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8365 extractLibs = false; 8366 } 8367 8368 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8369 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8370 8371 NativeLibraryHelper.Handle handle = null; 8372 try { 8373 handle = NativeLibraryHelper.Handle.create(pkg); 8374 // TODO(multiArch): This can be null for apps that didn't go through the 8375 // usual installation process. We can calculate it again, like we 8376 // do during install time. 8377 // 8378 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8379 // unnecessary. 8380 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8381 8382 // Null out the abis so that they can be recalculated. 8383 pkg.applicationInfo.primaryCpuAbi = null; 8384 pkg.applicationInfo.secondaryCpuAbi = null; 8385 if (isMultiArch(pkg.applicationInfo)) { 8386 // Warn if we've set an abiOverride for multi-lib packages.. 8387 // By definition, we need to copy both 32 and 64 bit libraries for 8388 // such packages. 8389 if (pkg.cpuAbiOverride != null 8390 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8391 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8392 } 8393 8394 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8395 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8396 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8397 if (extractLibs) { 8398 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8399 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8400 useIsaSpecificSubdirs); 8401 } else { 8402 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8403 } 8404 } 8405 8406 maybeThrowExceptionForMultiArchCopy( 8407 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8408 8409 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8410 if (extractLibs) { 8411 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8412 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8413 useIsaSpecificSubdirs); 8414 } else { 8415 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8416 } 8417 } 8418 8419 maybeThrowExceptionForMultiArchCopy( 8420 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8421 8422 if (abi64 >= 0) { 8423 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8424 } 8425 8426 if (abi32 >= 0) { 8427 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8428 if (abi64 >= 0) { 8429 if (cpuAbiOverride == null && pkg.use32bitAbi) { 8430 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8431 pkg.applicationInfo.primaryCpuAbi = abi; 8432 } else { 8433 pkg.applicationInfo.secondaryCpuAbi = abi; 8434 } 8435 } else { 8436 pkg.applicationInfo.primaryCpuAbi = abi; 8437 } 8438 } 8439 8440 } else { 8441 String[] abiList = (cpuAbiOverride != null) ? 8442 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8443 8444 // Enable gross and lame hacks for apps that are built with old 8445 // SDK tools. We must scan their APKs for renderscript bitcode and 8446 // not launch them if it's present. Don't bother checking on devices 8447 // that don't have 64 bit support. 8448 boolean needsRenderScriptOverride = false; 8449 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8450 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8451 abiList = Build.SUPPORTED_32_BIT_ABIS; 8452 needsRenderScriptOverride = true; 8453 } 8454 8455 final int copyRet; 8456 if (extractLibs) { 8457 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8458 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8459 } else { 8460 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8461 } 8462 8463 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8464 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8465 "Error unpackaging native libs for app, errorCode=" + copyRet); 8466 } 8467 8468 if (copyRet >= 0) { 8469 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8470 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8471 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8472 } else if (needsRenderScriptOverride) { 8473 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8474 } 8475 } 8476 } catch (IOException ioe) { 8477 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8478 } finally { 8479 IoUtils.closeQuietly(handle); 8480 } 8481 8482 // Now that we've calculated the ABIs and determined if it's an internal app, 8483 // we will go ahead and populate the nativeLibraryPath. 8484 setNativeLibraryPaths(pkg); 8485 } 8486 8487 /** 8488 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8489 * i.e, so that all packages can be run inside a single process if required. 8490 * 8491 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8492 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8493 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8494 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8495 * updating a package that belongs to a shared user. 8496 * 8497 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8498 * adds unnecessary complexity. 8499 */ 8500 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8501 PackageParser.Package scannedPackage, boolean bootComplete) { 8502 String requiredInstructionSet = null; 8503 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8504 requiredInstructionSet = VMRuntime.getInstructionSet( 8505 scannedPackage.applicationInfo.primaryCpuAbi); 8506 } 8507 8508 PackageSetting requirer = null; 8509 for (PackageSetting ps : packagesForUser) { 8510 // If packagesForUser contains scannedPackage, we skip it. This will happen 8511 // when scannedPackage is an update of an existing package. Without this check, 8512 // we will never be able to change the ABI of any package belonging to a shared 8513 // user, even if it's compatible with other packages. 8514 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8515 if (ps.primaryCpuAbiString == null) { 8516 continue; 8517 } 8518 8519 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8520 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8521 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8522 // this but there's not much we can do. 8523 String errorMessage = "Instruction set mismatch, " 8524 + ((requirer == null) ? "[caller]" : requirer) 8525 + " requires " + requiredInstructionSet + " whereas " + ps 8526 + " requires " + instructionSet; 8527 Slog.w(TAG, errorMessage); 8528 } 8529 8530 if (requiredInstructionSet == null) { 8531 requiredInstructionSet = instructionSet; 8532 requirer = ps; 8533 } 8534 } 8535 } 8536 8537 if (requiredInstructionSet != null) { 8538 String adjustedAbi; 8539 if (requirer != null) { 8540 // requirer != null implies that either scannedPackage was null or that scannedPackage 8541 // did not require an ABI, in which case we have to adjust scannedPackage to match 8542 // the ABI of the set (which is the same as requirer's ABI) 8543 adjustedAbi = requirer.primaryCpuAbiString; 8544 if (scannedPackage != null) { 8545 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8546 } 8547 } else { 8548 // requirer == null implies that we're updating all ABIs in the set to 8549 // match scannedPackage. 8550 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8551 } 8552 8553 for (PackageSetting ps : packagesForUser) { 8554 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8555 if (ps.primaryCpuAbiString != null) { 8556 continue; 8557 } 8558 8559 ps.primaryCpuAbiString = adjustedAbi; 8560 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8561 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8562 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8563 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8564 + " (requirer=" 8565 + (requirer == null ? "null" : requirer.pkg.packageName) 8566 + ", scannedPackage=" 8567 + (scannedPackage != null ? scannedPackage.packageName : "null") 8568 + ")"); 8569 try { 8570 mInstaller.rmdex(ps.codePathString, 8571 getDexCodeInstructionSet(getPreferredInstructionSet())); 8572 } catch (InstallerException ignored) { 8573 } 8574 } 8575 } 8576 } 8577 } 8578 } 8579 8580 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8581 synchronized (mPackages) { 8582 mResolverReplaced = true; 8583 // Set up information for custom user intent resolution activity. 8584 mResolveActivity.applicationInfo = pkg.applicationInfo; 8585 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8586 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8587 mResolveActivity.processName = pkg.applicationInfo.packageName; 8588 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8589 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8590 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8591 mResolveActivity.theme = 0; 8592 mResolveActivity.exported = true; 8593 mResolveActivity.enabled = true; 8594 mResolveInfo.activityInfo = mResolveActivity; 8595 mResolveInfo.priority = 0; 8596 mResolveInfo.preferredOrder = 0; 8597 mResolveInfo.match = 0; 8598 mResolveComponentName = mCustomResolverComponentName; 8599 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8600 mResolveComponentName); 8601 } 8602 } 8603 8604 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8605 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8606 8607 // Set up information for ephemeral installer activity 8608 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8609 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8610 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8611 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8612 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8613 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8614 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8615 mEphemeralInstallerActivity.theme = 0; 8616 mEphemeralInstallerActivity.exported = true; 8617 mEphemeralInstallerActivity.enabled = true; 8618 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8619 mEphemeralInstallerInfo.priority = 0; 8620 mEphemeralInstallerInfo.preferredOrder = 0; 8621 mEphemeralInstallerInfo.match = 0; 8622 8623 if (DEBUG_EPHEMERAL) { 8624 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8625 } 8626 } 8627 8628 private static String calculateBundledApkRoot(final String codePathString) { 8629 final File codePath = new File(codePathString); 8630 final File codeRoot; 8631 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8632 codeRoot = Environment.getRootDirectory(); 8633 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8634 codeRoot = Environment.getOemDirectory(); 8635 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8636 codeRoot = Environment.getVendorDirectory(); 8637 } else { 8638 // Unrecognized code path; take its top real segment as the apk root: 8639 // e.g. /something/app/blah.apk => /something 8640 try { 8641 File f = codePath.getCanonicalFile(); 8642 File parent = f.getParentFile(); // non-null because codePath is a file 8643 File tmp; 8644 while ((tmp = parent.getParentFile()) != null) { 8645 f = parent; 8646 parent = tmp; 8647 } 8648 codeRoot = f; 8649 Slog.w(TAG, "Unrecognized code path " 8650 + codePath + " - using " + codeRoot); 8651 } catch (IOException e) { 8652 // Can't canonicalize the code path -- shenanigans? 8653 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8654 return Environment.getRootDirectory().getPath(); 8655 } 8656 } 8657 return codeRoot.getPath(); 8658 } 8659 8660 /** 8661 * Derive and set the location of native libraries for the given package, 8662 * which varies depending on where and how the package was installed. 8663 */ 8664 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8665 final ApplicationInfo info = pkg.applicationInfo; 8666 final String codePath = pkg.codePath; 8667 final File codeFile = new File(codePath); 8668 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8669 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8670 8671 info.nativeLibraryRootDir = null; 8672 info.nativeLibraryRootRequiresIsa = false; 8673 info.nativeLibraryDir = null; 8674 info.secondaryNativeLibraryDir = null; 8675 8676 if (isApkFile(codeFile)) { 8677 // Monolithic install 8678 if (bundledApp) { 8679 // If "/system/lib64/apkname" exists, assume that is the per-package 8680 // native library directory to use; otherwise use "/system/lib/apkname". 8681 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8682 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8683 getPrimaryInstructionSet(info)); 8684 8685 // This is a bundled system app so choose the path based on the ABI. 8686 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8687 // is just the default path. 8688 final String apkName = deriveCodePathName(codePath); 8689 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8690 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8691 apkName).getAbsolutePath(); 8692 8693 if (info.secondaryCpuAbi != null) { 8694 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8695 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8696 secondaryLibDir, apkName).getAbsolutePath(); 8697 } 8698 } else if (asecApp) { 8699 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8700 .getAbsolutePath(); 8701 } else { 8702 final String apkName = deriveCodePathName(codePath); 8703 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8704 .getAbsolutePath(); 8705 } 8706 8707 info.nativeLibraryRootRequiresIsa = false; 8708 info.nativeLibraryDir = info.nativeLibraryRootDir; 8709 } else { 8710 // Cluster install 8711 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8712 info.nativeLibraryRootRequiresIsa = true; 8713 8714 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8715 getPrimaryInstructionSet(info)).getAbsolutePath(); 8716 8717 if (info.secondaryCpuAbi != null) { 8718 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8719 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8720 } 8721 } 8722 } 8723 8724 /** 8725 * Calculate the abis and roots for a bundled app. These can uniquely 8726 * be determined from the contents of the system partition, i.e whether 8727 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8728 * of this information, and instead assume that the system was built 8729 * sensibly. 8730 */ 8731 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8732 PackageSetting pkgSetting) { 8733 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8734 8735 // If "/system/lib64/apkname" exists, assume that is the per-package 8736 // native library directory to use; otherwise use "/system/lib/apkname". 8737 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8738 setBundledAppAbi(pkg, apkRoot, apkName); 8739 // pkgSetting might be null during rescan following uninstall of updates 8740 // to a bundled app, so accommodate that possibility. The settings in 8741 // that case will be established later from the parsed package. 8742 // 8743 // If the settings aren't null, sync them up with what we've just derived. 8744 // note that apkRoot isn't stored in the package settings. 8745 if (pkgSetting != null) { 8746 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8747 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8748 } 8749 } 8750 8751 /** 8752 * Deduces the ABI of a bundled app and sets the relevant fields on the 8753 * parsed pkg object. 8754 * 8755 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8756 * under which system libraries are installed. 8757 * @param apkName the name of the installed package. 8758 */ 8759 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8760 final File codeFile = new File(pkg.codePath); 8761 8762 final boolean has64BitLibs; 8763 final boolean has32BitLibs; 8764 if (isApkFile(codeFile)) { 8765 // Monolithic install 8766 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 8767 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 8768 } else { 8769 // Cluster install 8770 final File rootDir = new File(codeFile, LIB_DIR_NAME); 8771 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 8772 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 8773 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 8774 has64BitLibs = (new File(rootDir, isa)).exists(); 8775 } else { 8776 has64BitLibs = false; 8777 } 8778 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 8779 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 8780 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 8781 has32BitLibs = (new File(rootDir, isa)).exists(); 8782 } else { 8783 has32BitLibs = false; 8784 } 8785 } 8786 8787 if (has64BitLibs && !has32BitLibs) { 8788 // The package has 64 bit libs, but not 32 bit libs. Its primary 8789 // ABI should be 64 bit. We can safely assume here that the bundled 8790 // native libraries correspond to the most preferred ABI in the list. 8791 8792 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8793 pkg.applicationInfo.secondaryCpuAbi = null; 8794 } else if (has32BitLibs && !has64BitLibs) { 8795 // The package has 32 bit libs but not 64 bit libs. Its primary 8796 // ABI should be 32 bit. 8797 8798 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8799 pkg.applicationInfo.secondaryCpuAbi = null; 8800 } else if (has32BitLibs && has64BitLibs) { 8801 // The application has both 64 and 32 bit bundled libraries. We check 8802 // here that the app declares multiArch support, and warn if it doesn't. 8803 // 8804 // We will be lenient here and record both ABIs. The primary will be the 8805 // ABI that's higher on the list, i.e, a device that's configured to prefer 8806 // 64 bit apps will see a 64 bit primary ABI, 8807 8808 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 8809 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 8810 } 8811 8812 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 8813 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8814 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8815 } else { 8816 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 8817 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 8818 } 8819 } else { 8820 pkg.applicationInfo.primaryCpuAbi = null; 8821 pkg.applicationInfo.secondaryCpuAbi = null; 8822 } 8823 } 8824 8825 private void killPackage(PackageParser.Package pkg, String reason) { 8826 // Kill the parent package 8827 killApplication(pkg.packageName, pkg.applicationInfo.uid, reason); 8828 // Kill the child packages 8829 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8830 for (int i = 0; i < childCount; i++) { 8831 PackageParser.Package childPkg = pkg.childPackages.get(i); 8832 killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason); 8833 } 8834 } 8835 8836 private void killApplication(String pkgName, int appId, String reason) { 8837 // Request the ActivityManager to kill the process(only for existing packages) 8838 // so that we do not end up in a confused state while the user is still using the older 8839 // version of the application while the new one gets installed. 8840 IActivityManager am = ActivityManagerNative.getDefault(); 8841 if (am != null) { 8842 try { 8843 am.killApplicationWithAppId(pkgName, appId, reason); 8844 } catch (RemoteException e) { 8845 } 8846 } 8847 } 8848 8849 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 8850 // Remove the parent package setting 8851 PackageSetting ps = (PackageSetting) pkg.mExtras; 8852 if (ps != null) { 8853 removePackageLI(ps, chatty); 8854 } 8855 // Remove the child package setting 8856 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8857 for (int i = 0; i < childCount; i++) { 8858 PackageParser.Package childPkg = pkg.childPackages.get(i); 8859 ps = (PackageSetting) childPkg.mExtras; 8860 if (ps != null) { 8861 removePackageLI(ps, chatty); 8862 } 8863 } 8864 } 8865 8866 void removePackageLI(PackageSetting ps, boolean chatty) { 8867 if (DEBUG_INSTALL) { 8868 if (chatty) 8869 Log.d(TAG, "Removing package " + ps.name); 8870 } 8871 8872 // writer 8873 synchronized (mPackages) { 8874 mPackages.remove(ps.name); 8875 final PackageParser.Package pkg = ps.pkg; 8876 if (pkg != null) { 8877 cleanPackageDataStructuresLILPw(pkg, chatty); 8878 } 8879 } 8880 } 8881 8882 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 8883 if (DEBUG_INSTALL) { 8884 if (chatty) 8885 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 8886 } 8887 8888 // writer 8889 synchronized (mPackages) { 8890 // Remove the parent package 8891 mPackages.remove(pkg.applicationInfo.packageName); 8892 cleanPackageDataStructuresLILPw(pkg, chatty); 8893 8894 // Remove the child packages 8895 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8896 for (int i = 0; i < childCount; i++) { 8897 PackageParser.Package childPkg = pkg.childPackages.get(i); 8898 mPackages.remove(childPkg.applicationInfo.packageName); 8899 cleanPackageDataStructuresLILPw(childPkg, chatty); 8900 } 8901 } 8902 } 8903 8904 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 8905 int N = pkg.providers.size(); 8906 StringBuilder r = null; 8907 int i; 8908 for (i=0; i<N; i++) { 8909 PackageParser.Provider p = pkg.providers.get(i); 8910 mProviders.removeProvider(p); 8911 if (p.info.authority == null) { 8912 8913 /* There was another ContentProvider with this authority when 8914 * this app was installed so this authority is null, 8915 * Ignore it as we don't have to unregister the provider. 8916 */ 8917 continue; 8918 } 8919 String names[] = p.info.authority.split(";"); 8920 for (int j = 0; j < names.length; j++) { 8921 if (mProvidersByAuthority.get(names[j]) == p) { 8922 mProvidersByAuthority.remove(names[j]); 8923 if (DEBUG_REMOVE) { 8924 if (chatty) 8925 Log.d(TAG, "Unregistered content provider: " + names[j] 8926 + ", className = " + p.info.name + ", isSyncable = " 8927 + p.info.isSyncable); 8928 } 8929 } 8930 } 8931 if (DEBUG_REMOVE && chatty) { 8932 if (r == null) { 8933 r = new StringBuilder(256); 8934 } else { 8935 r.append(' '); 8936 } 8937 r.append(p.info.name); 8938 } 8939 } 8940 if (r != null) { 8941 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 8942 } 8943 8944 N = pkg.services.size(); 8945 r = null; 8946 for (i=0; i<N; i++) { 8947 PackageParser.Service s = pkg.services.get(i); 8948 mServices.removeService(s); 8949 if (chatty) { 8950 if (r == null) { 8951 r = new StringBuilder(256); 8952 } else { 8953 r.append(' '); 8954 } 8955 r.append(s.info.name); 8956 } 8957 } 8958 if (r != null) { 8959 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 8960 } 8961 8962 N = pkg.receivers.size(); 8963 r = null; 8964 for (i=0; i<N; i++) { 8965 PackageParser.Activity a = pkg.receivers.get(i); 8966 mReceivers.removeActivity(a, "receiver"); 8967 if (DEBUG_REMOVE && chatty) { 8968 if (r == null) { 8969 r = new StringBuilder(256); 8970 } else { 8971 r.append(' '); 8972 } 8973 r.append(a.info.name); 8974 } 8975 } 8976 if (r != null) { 8977 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 8978 } 8979 8980 N = pkg.activities.size(); 8981 r = null; 8982 for (i=0; i<N; i++) { 8983 PackageParser.Activity a = pkg.activities.get(i); 8984 mActivities.removeActivity(a, "activity"); 8985 if (DEBUG_REMOVE && chatty) { 8986 if (r == null) { 8987 r = new StringBuilder(256); 8988 } else { 8989 r.append(' '); 8990 } 8991 r.append(a.info.name); 8992 } 8993 } 8994 if (r != null) { 8995 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 8996 } 8997 8998 N = pkg.permissions.size(); 8999 r = null; 9000 for (i=0; i<N; i++) { 9001 PackageParser.Permission p = pkg.permissions.get(i); 9002 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9003 if (bp == null) { 9004 bp = mSettings.mPermissionTrees.get(p.info.name); 9005 } 9006 if (bp != null && bp.perm == p) { 9007 bp.perm = null; 9008 if (DEBUG_REMOVE && chatty) { 9009 if (r == null) { 9010 r = new StringBuilder(256); 9011 } else { 9012 r.append(' '); 9013 } 9014 r.append(p.info.name); 9015 } 9016 } 9017 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9018 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9019 if (appOpPkgs != null) { 9020 appOpPkgs.remove(pkg.packageName); 9021 } 9022 } 9023 } 9024 if (r != null) { 9025 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9026 } 9027 9028 N = pkg.requestedPermissions.size(); 9029 r = null; 9030 for (i=0; i<N; i++) { 9031 String perm = pkg.requestedPermissions.get(i); 9032 BasePermission bp = mSettings.mPermissions.get(perm); 9033 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9034 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9035 if (appOpPkgs != null) { 9036 appOpPkgs.remove(pkg.packageName); 9037 if (appOpPkgs.isEmpty()) { 9038 mAppOpPermissionPackages.remove(perm); 9039 } 9040 } 9041 } 9042 } 9043 if (r != null) { 9044 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9045 } 9046 9047 N = pkg.instrumentation.size(); 9048 r = null; 9049 for (i=0; i<N; i++) { 9050 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9051 mInstrumentation.remove(a.getComponentName()); 9052 if (DEBUG_REMOVE && chatty) { 9053 if (r == null) { 9054 r = new StringBuilder(256); 9055 } else { 9056 r.append(' '); 9057 } 9058 r.append(a.info.name); 9059 } 9060 } 9061 if (r != null) { 9062 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9063 } 9064 9065 r = null; 9066 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9067 // Only system apps can hold shared libraries. 9068 if (pkg.libraryNames != null) { 9069 for (i=0; i<pkg.libraryNames.size(); i++) { 9070 String name = pkg.libraryNames.get(i); 9071 SharedLibraryEntry cur = mSharedLibraries.get(name); 9072 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9073 mSharedLibraries.remove(name); 9074 if (DEBUG_REMOVE && chatty) { 9075 if (r == null) { 9076 r = new StringBuilder(256); 9077 } else { 9078 r.append(' '); 9079 } 9080 r.append(name); 9081 } 9082 } 9083 } 9084 } 9085 } 9086 if (r != null) { 9087 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9088 } 9089 } 9090 9091 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9092 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9093 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9094 return true; 9095 } 9096 } 9097 return false; 9098 } 9099 9100 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9101 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9102 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9103 9104 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9105 // Update the parent permissions 9106 updatePermissionsLPw(pkg.packageName, pkg, flags); 9107 // Update the child permissions 9108 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9109 for (int i = 0; i < childCount; i++) { 9110 PackageParser.Package childPkg = pkg.childPackages.get(i); 9111 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9112 } 9113 } 9114 9115 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9116 int flags) { 9117 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9118 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9119 } 9120 9121 private void updatePermissionsLPw(String changingPkg, 9122 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9123 // Make sure there are no dangling permission trees. 9124 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9125 while (it.hasNext()) { 9126 final BasePermission bp = it.next(); 9127 if (bp.packageSetting == null) { 9128 // We may not yet have parsed the package, so just see if 9129 // we still know about its settings. 9130 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9131 } 9132 if (bp.packageSetting == null) { 9133 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9134 + " from package " + bp.sourcePackage); 9135 it.remove(); 9136 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9137 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9138 Slog.i(TAG, "Removing old permission tree: " + bp.name 9139 + " from package " + bp.sourcePackage); 9140 flags |= UPDATE_PERMISSIONS_ALL; 9141 it.remove(); 9142 } 9143 } 9144 } 9145 9146 // Make sure all dynamic permissions have been assigned to a package, 9147 // and make sure there are no dangling permissions. 9148 it = mSettings.mPermissions.values().iterator(); 9149 while (it.hasNext()) { 9150 final BasePermission bp = it.next(); 9151 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9152 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9153 + bp.name + " pkg=" + bp.sourcePackage 9154 + " info=" + bp.pendingInfo); 9155 if (bp.packageSetting == null && bp.pendingInfo != null) { 9156 final BasePermission tree = findPermissionTreeLP(bp.name); 9157 if (tree != null && tree.perm != null) { 9158 bp.packageSetting = tree.packageSetting; 9159 bp.perm = new PackageParser.Permission(tree.perm.owner, 9160 new PermissionInfo(bp.pendingInfo)); 9161 bp.perm.info.packageName = tree.perm.info.packageName; 9162 bp.perm.info.name = bp.name; 9163 bp.uid = tree.uid; 9164 } 9165 } 9166 } 9167 if (bp.packageSetting == null) { 9168 // We may not yet have parsed the package, so just see if 9169 // we still know about its settings. 9170 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9171 } 9172 if (bp.packageSetting == null) { 9173 Slog.w(TAG, "Removing dangling permission: " + bp.name 9174 + " from package " + bp.sourcePackage); 9175 it.remove(); 9176 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9177 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9178 Slog.i(TAG, "Removing old permission: " + bp.name 9179 + " from package " + bp.sourcePackage); 9180 flags |= UPDATE_PERMISSIONS_ALL; 9181 it.remove(); 9182 } 9183 } 9184 } 9185 9186 // Now update the permissions for all packages, in particular 9187 // replace the granted permissions of the system packages. 9188 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9189 for (PackageParser.Package pkg : mPackages.values()) { 9190 if (pkg != pkgInfo) { 9191 // Only replace for packages on requested volume 9192 final String volumeUuid = getVolumeUuidForPackage(pkg); 9193 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9194 && Objects.equals(replaceVolumeUuid, volumeUuid); 9195 grantPermissionsLPw(pkg, replace, changingPkg); 9196 } 9197 } 9198 } 9199 9200 if (pkgInfo != null) { 9201 // Only replace for packages on requested volume 9202 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9203 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9204 && Objects.equals(replaceVolumeUuid, volumeUuid); 9205 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9206 } 9207 } 9208 9209 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9210 String packageOfInterest) { 9211 // IMPORTANT: There are two types of permissions: install and runtime. 9212 // Install time permissions are granted when the app is installed to 9213 // all device users and users added in the future. Runtime permissions 9214 // are granted at runtime explicitly to specific users. Normal and signature 9215 // protected permissions are install time permissions. Dangerous permissions 9216 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9217 // otherwise they are runtime permissions. This function does not manage 9218 // runtime permissions except for the case an app targeting Lollipop MR1 9219 // being upgraded to target a newer SDK, in which case dangerous permissions 9220 // are transformed from install time to runtime ones. 9221 9222 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9223 if (ps == null) { 9224 return; 9225 } 9226 9227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9228 9229 PermissionsState permissionsState = ps.getPermissionsState(); 9230 PermissionsState origPermissions = permissionsState; 9231 9232 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9233 9234 boolean runtimePermissionsRevoked = false; 9235 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9236 9237 boolean changedInstallPermission = false; 9238 9239 if (replace) { 9240 ps.installPermissionsFixed = false; 9241 if (!ps.isSharedUser()) { 9242 origPermissions = new PermissionsState(permissionsState); 9243 permissionsState.reset(); 9244 } else { 9245 // We need to know only about runtime permission changes since the 9246 // calling code always writes the install permissions state but 9247 // the runtime ones are written only if changed. The only cases of 9248 // changed runtime permissions here are promotion of an install to 9249 // runtime and revocation of a runtime from a shared user. 9250 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9251 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9252 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9253 runtimePermissionsRevoked = true; 9254 } 9255 } 9256 } 9257 9258 permissionsState.setGlobalGids(mGlobalGids); 9259 9260 final int N = pkg.requestedPermissions.size(); 9261 for (int i=0; i<N; i++) { 9262 final String name = pkg.requestedPermissions.get(i); 9263 final BasePermission bp = mSettings.mPermissions.get(name); 9264 9265 if (DEBUG_INSTALL) { 9266 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9267 } 9268 9269 if (bp == null || bp.packageSetting == null) { 9270 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9271 Slog.w(TAG, "Unknown permission " + name 9272 + " in package " + pkg.packageName); 9273 } 9274 continue; 9275 } 9276 9277 final String perm = bp.name; 9278 boolean allowedSig = false; 9279 int grant = GRANT_DENIED; 9280 9281 // Keep track of app op permissions. 9282 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9283 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9284 if (pkgs == null) { 9285 pkgs = new ArraySet<>(); 9286 mAppOpPermissionPackages.put(bp.name, pkgs); 9287 } 9288 pkgs.add(pkg.packageName); 9289 } 9290 9291 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9292 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9293 >= Build.VERSION_CODES.M; 9294 switch (level) { 9295 case PermissionInfo.PROTECTION_NORMAL: { 9296 // For all apps normal permissions are install time ones. 9297 grant = GRANT_INSTALL; 9298 } break; 9299 9300 case PermissionInfo.PROTECTION_DANGEROUS: { 9301 // If a permission review is required for legacy apps we represent 9302 // their permissions as always granted runtime ones since we need 9303 // to keep the review required permission flag per user while an 9304 // install permission's state is shared across all users. 9305 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9306 // For legacy apps dangerous permissions are install time ones. 9307 grant = GRANT_INSTALL; 9308 } else if (origPermissions.hasInstallPermission(bp.name)) { 9309 // For legacy apps that became modern, install becomes runtime. 9310 grant = GRANT_UPGRADE; 9311 } else if (mPromoteSystemApps 9312 && isSystemApp(ps) 9313 && mExistingSystemPackages.contains(ps.name)) { 9314 // For legacy system apps, install becomes runtime. 9315 // We cannot check hasInstallPermission() for system apps since those 9316 // permissions were granted implicitly and not persisted pre-M. 9317 grant = GRANT_UPGRADE; 9318 } else { 9319 // For modern apps keep runtime permissions unchanged. 9320 grant = GRANT_RUNTIME; 9321 } 9322 } break; 9323 9324 case PermissionInfo.PROTECTION_SIGNATURE: { 9325 // For all apps signature permissions are install time ones. 9326 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9327 if (allowedSig) { 9328 grant = GRANT_INSTALL; 9329 } 9330 } break; 9331 } 9332 9333 if (DEBUG_INSTALL) { 9334 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9335 } 9336 9337 if (grant != GRANT_DENIED) { 9338 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9339 // If this is an existing, non-system package, then 9340 // we can't add any new permissions to it. 9341 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9342 // Except... if this is a permission that was added 9343 // to the platform (note: need to only do this when 9344 // updating the platform). 9345 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9346 grant = GRANT_DENIED; 9347 } 9348 } 9349 } 9350 9351 switch (grant) { 9352 case GRANT_INSTALL: { 9353 // Revoke this as runtime permission to handle the case of 9354 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9355 for (int userId : UserManagerService.getInstance().getUserIds()) { 9356 if (origPermissions.getRuntimePermissionState( 9357 bp.name, userId) != null) { 9358 // Revoke the runtime permission and clear the flags. 9359 origPermissions.revokeRuntimePermission(bp, userId); 9360 origPermissions.updatePermissionFlags(bp, userId, 9361 PackageManager.MASK_PERMISSION_FLAGS, 0); 9362 // If we revoked a permission permission, we have to write. 9363 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9364 changedRuntimePermissionUserIds, userId); 9365 } 9366 } 9367 // Grant an install permission. 9368 if (permissionsState.grantInstallPermission(bp) != 9369 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9370 changedInstallPermission = true; 9371 } 9372 } break; 9373 9374 case GRANT_RUNTIME: { 9375 // Grant previously granted runtime permissions. 9376 for (int userId : UserManagerService.getInstance().getUserIds()) { 9377 PermissionState permissionState = origPermissions 9378 .getRuntimePermissionState(bp.name, userId); 9379 int flags = permissionState != null 9380 ? permissionState.getFlags() : 0; 9381 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9382 if (permissionsState.grantRuntimePermission(bp, userId) == 9383 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9384 // If we cannot put the permission as it was, we have to write. 9385 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9386 changedRuntimePermissionUserIds, userId); 9387 } 9388 // If the app supports runtime permissions no need for a review. 9389 if (Build.PERMISSIONS_REVIEW_REQUIRED 9390 && appSupportsRuntimePermissions 9391 && (flags & PackageManager 9392 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9393 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9394 // Since we changed the flags, we have to write. 9395 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9396 changedRuntimePermissionUserIds, userId); 9397 } 9398 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9399 && !appSupportsRuntimePermissions) { 9400 // For legacy apps that need a permission review, every new 9401 // runtime permission is granted but it is pending a review. 9402 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9403 permissionsState.grantRuntimePermission(bp, userId); 9404 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9405 // We changed the permission and flags, hence have to write. 9406 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9407 changedRuntimePermissionUserIds, userId); 9408 } 9409 } 9410 // Propagate the permission flags. 9411 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9412 } 9413 } break; 9414 9415 case GRANT_UPGRADE: { 9416 // Grant runtime permissions for a previously held install permission. 9417 PermissionState permissionState = origPermissions 9418 .getInstallPermissionState(bp.name); 9419 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9420 9421 if (origPermissions.revokeInstallPermission(bp) 9422 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9423 // We will be transferring the permission flags, so clear them. 9424 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9425 PackageManager.MASK_PERMISSION_FLAGS, 0); 9426 changedInstallPermission = true; 9427 } 9428 9429 // If the permission is not to be promoted to runtime we ignore it and 9430 // also its other flags as they are not applicable to install permissions. 9431 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9432 for (int userId : currentUserIds) { 9433 if (permissionsState.grantRuntimePermission(bp, userId) != 9434 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9435 // Transfer the permission flags. 9436 permissionsState.updatePermissionFlags(bp, userId, 9437 flags, flags); 9438 // If we granted the permission, we have to write. 9439 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9440 changedRuntimePermissionUserIds, userId); 9441 } 9442 } 9443 } 9444 } break; 9445 9446 default: { 9447 if (packageOfInterest == null 9448 || packageOfInterest.equals(pkg.packageName)) { 9449 Slog.w(TAG, "Not granting permission " + perm 9450 + " to package " + pkg.packageName 9451 + " because it was previously installed without"); 9452 } 9453 } break; 9454 } 9455 } else { 9456 if (permissionsState.revokeInstallPermission(bp) != 9457 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9458 // Also drop the permission flags. 9459 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9460 PackageManager.MASK_PERMISSION_FLAGS, 0); 9461 changedInstallPermission = true; 9462 Slog.i(TAG, "Un-granting permission " + perm 9463 + " from package " + pkg.packageName 9464 + " (protectionLevel=" + bp.protectionLevel 9465 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9466 + ")"); 9467 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9468 // Don't print warning for app op permissions, since it is fine for them 9469 // not to be granted, there is a UI for the user to decide. 9470 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9471 Slog.w(TAG, "Not granting permission " + perm 9472 + " to package " + pkg.packageName 9473 + " (protectionLevel=" + bp.protectionLevel 9474 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9475 + ")"); 9476 } 9477 } 9478 } 9479 } 9480 9481 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9482 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9483 // This is the first that we have heard about this package, so the 9484 // permissions we have now selected are fixed until explicitly 9485 // changed. 9486 ps.installPermissionsFixed = true; 9487 } 9488 9489 // Persist the runtime permissions state for users with changes. If permissions 9490 // were revoked because no app in the shared user declares them we have to 9491 // write synchronously to avoid losing runtime permissions state. 9492 for (int userId : changedRuntimePermissionUserIds) { 9493 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9494 } 9495 9496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9497 } 9498 9499 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9500 boolean allowed = false; 9501 final int NP = PackageParser.NEW_PERMISSIONS.length; 9502 for (int ip=0; ip<NP; ip++) { 9503 final PackageParser.NewPermissionInfo npi 9504 = PackageParser.NEW_PERMISSIONS[ip]; 9505 if (npi.name.equals(perm) 9506 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9507 allowed = true; 9508 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9509 + pkg.packageName); 9510 break; 9511 } 9512 } 9513 return allowed; 9514 } 9515 9516 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9517 BasePermission bp, PermissionsState origPermissions) { 9518 boolean allowed; 9519 allowed = (compareSignatures( 9520 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9521 == PackageManager.SIGNATURE_MATCH) 9522 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9523 == PackageManager.SIGNATURE_MATCH); 9524 if (!allowed && (bp.protectionLevel 9525 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9526 if (isSystemApp(pkg)) { 9527 // For updated system applications, a system permission 9528 // is granted only if it had been defined by the original application. 9529 if (pkg.isUpdatedSystemApp()) { 9530 final PackageSetting sysPs = mSettings 9531 .getDisabledSystemPkgLPr(pkg.packageName); 9532 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9533 // If the original was granted this permission, we take 9534 // that grant decision as read and propagate it to the 9535 // update. 9536 if (sysPs.isPrivileged()) { 9537 allowed = true; 9538 } 9539 } else { 9540 // The system apk may have been updated with an older 9541 // version of the one on the data partition, but which 9542 // granted a new system permission that it didn't have 9543 // before. In this case we do want to allow the app to 9544 // now get the new permission if the ancestral apk is 9545 // privileged to get it. 9546 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9547 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9548 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9549 allowed = true; 9550 break; 9551 } 9552 } 9553 } 9554 // Also if a privileged parent package on the system image or any of 9555 // its children requested a privileged permission, the updated child 9556 // packages can also get the permission. 9557 if (pkg.parentPackage != null) { 9558 final PackageSetting disabledSysParentPs = mSettings 9559 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9560 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9561 && disabledSysParentPs.isPrivileged()) { 9562 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9563 allowed = true; 9564 } else if (disabledSysParentPs.pkg.childPackages != null) { 9565 final int count = disabledSysParentPs.pkg.childPackages.size(); 9566 for (int i = 0; i < count; i++) { 9567 PackageParser.Package disabledSysChildPkg = 9568 disabledSysParentPs.pkg.childPackages.get(i); 9569 if (isPackageRequestingPermission(disabledSysChildPkg, 9570 perm)) { 9571 allowed = true; 9572 break; 9573 } 9574 } 9575 } 9576 } 9577 } 9578 } 9579 } else { 9580 allowed = isPrivilegedApp(pkg); 9581 } 9582 } 9583 } 9584 if (!allowed) { 9585 if (!allowed && (bp.protectionLevel 9586 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9587 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9588 // If this was a previously normal/dangerous permission that got moved 9589 // to a system permission as part of the runtime permission redesign, then 9590 // we still want to blindly grant it to old apps. 9591 allowed = true; 9592 } 9593 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9594 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9595 // If this permission is to be granted to the system installer and 9596 // this app is an installer, then it gets the permission. 9597 allowed = true; 9598 } 9599 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9600 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9601 // If this permission is to be granted to the system verifier and 9602 // this app is a verifier, then it gets the permission. 9603 allowed = true; 9604 } 9605 if (!allowed && (bp.protectionLevel 9606 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9607 && isSystemApp(pkg)) { 9608 // Any pre-installed system app is allowed to get this permission. 9609 allowed = true; 9610 } 9611 if (!allowed && (bp.protectionLevel 9612 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9613 // For development permissions, a development permission 9614 // is granted only if it was already granted. 9615 allowed = origPermissions.hasInstallPermission(perm); 9616 } 9617 } 9618 return allowed; 9619 } 9620 9621 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9622 final int permCount = pkg.requestedPermissions.size(); 9623 for (int j = 0; j < permCount; j++) { 9624 String requestedPermission = pkg.requestedPermissions.get(j); 9625 if (permission.equals(requestedPermission)) { 9626 return true; 9627 } 9628 } 9629 return false; 9630 } 9631 9632 final class ActivityIntentResolver 9633 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9634 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9635 boolean defaultOnly, int userId) { 9636 if (!sUserManager.exists(userId)) return null; 9637 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9638 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9639 } 9640 9641 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9642 int userId) { 9643 if (!sUserManager.exists(userId)) return null; 9644 mFlags = flags; 9645 return super.queryIntent(intent, resolvedType, 9646 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9647 } 9648 9649 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9650 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9651 if (!sUserManager.exists(userId)) return null; 9652 if (packageActivities == null) { 9653 return null; 9654 } 9655 mFlags = flags; 9656 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9657 final int N = packageActivities.size(); 9658 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9659 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9660 9661 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9662 for (int i = 0; i < N; ++i) { 9663 intentFilters = packageActivities.get(i).intents; 9664 if (intentFilters != null && intentFilters.size() > 0) { 9665 PackageParser.ActivityIntentInfo[] array = 9666 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9667 intentFilters.toArray(array); 9668 listCut.add(array); 9669 } 9670 } 9671 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9672 } 9673 9674 public final void addActivity(PackageParser.Activity a, String type) { 9675 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 9676 mActivities.put(a.getComponentName(), a); 9677 if (DEBUG_SHOW_INFO) 9678 Log.v( 9679 TAG, " " + type + " " + 9680 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 9681 if (DEBUG_SHOW_INFO) 9682 Log.v(TAG, " Class=" + a.info.name); 9683 final int NI = a.intents.size(); 9684 for (int j=0; j<NI; j++) { 9685 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9686 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 9687 intent.setPriority(0); 9688 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 9689 + a.className + " with priority > 0, forcing to 0"); 9690 } 9691 if (DEBUG_SHOW_INFO) { 9692 Log.v(TAG, " IntentFilter:"); 9693 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9694 } 9695 if (!intent.debugCheck()) { 9696 Log.w(TAG, "==> For Activity " + a.info.name); 9697 } 9698 addFilter(intent); 9699 } 9700 } 9701 9702 public final void removeActivity(PackageParser.Activity a, String type) { 9703 mActivities.remove(a.getComponentName()); 9704 if (DEBUG_SHOW_INFO) { 9705 Log.v(TAG, " " + type + " " 9706 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 9707 : a.info.name) + ":"); 9708 Log.v(TAG, " Class=" + a.info.name); 9709 } 9710 final int NI = a.intents.size(); 9711 for (int j=0; j<NI; j++) { 9712 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 9713 if (DEBUG_SHOW_INFO) { 9714 Log.v(TAG, " IntentFilter:"); 9715 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9716 } 9717 removeFilter(intent); 9718 } 9719 } 9720 9721 @Override 9722 protected boolean allowFilterResult( 9723 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 9724 ActivityInfo filterAi = filter.activity.info; 9725 for (int i=dest.size()-1; i>=0; i--) { 9726 ActivityInfo destAi = dest.get(i).activityInfo; 9727 if (destAi.name == filterAi.name 9728 && destAi.packageName == filterAi.packageName) { 9729 return false; 9730 } 9731 } 9732 return true; 9733 } 9734 9735 @Override 9736 protected ActivityIntentInfo[] newArray(int size) { 9737 return new ActivityIntentInfo[size]; 9738 } 9739 9740 @Override 9741 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 9742 if (!sUserManager.exists(userId)) return true; 9743 PackageParser.Package p = filter.activity.owner; 9744 if (p != null) { 9745 PackageSetting ps = (PackageSetting)p.mExtras; 9746 if (ps != null) { 9747 // System apps are never considered stopped for purposes of 9748 // filtering, because there may be no way for the user to 9749 // actually re-launch them. 9750 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 9751 && ps.getStopped(userId); 9752 } 9753 } 9754 return false; 9755 } 9756 9757 @Override 9758 protected boolean isPackageForFilter(String packageName, 9759 PackageParser.ActivityIntentInfo info) { 9760 return packageName.equals(info.activity.owner.packageName); 9761 } 9762 9763 @Override 9764 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 9765 int match, int userId) { 9766 if (!sUserManager.exists(userId)) return null; 9767 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 9768 return null; 9769 } 9770 final PackageParser.Activity activity = info.activity; 9771 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 9772 if (ps == null) { 9773 return null; 9774 } 9775 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 9776 ps.readUserState(userId), userId); 9777 if (ai == null) { 9778 return null; 9779 } 9780 final ResolveInfo res = new ResolveInfo(); 9781 res.activityInfo = ai; 9782 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 9783 res.filter = info; 9784 } 9785 if (info != null) { 9786 res.handleAllWebDataURI = info.handleAllWebDataURI(); 9787 } 9788 res.priority = info.getPriority(); 9789 res.preferredOrder = activity.owner.mPreferredOrder; 9790 //System.out.println("Result: " + res.activityInfo.className + 9791 // " = " + res.priority); 9792 res.match = match; 9793 res.isDefault = info.hasDefault; 9794 res.labelRes = info.labelRes; 9795 res.nonLocalizedLabel = info.nonLocalizedLabel; 9796 if (userNeedsBadging(userId)) { 9797 res.noResourceId = true; 9798 } else { 9799 res.icon = info.icon; 9800 } 9801 res.iconResourceId = info.icon; 9802 res.system = res.activityInfo.applicationInfo.isSystemApp(); 9803 return res; 9804 } 9805 9806 @Override 9807 protected void sortResults(List<ResolveInfo> results) { 9808 Collections.sort(results, mResolvePrioritySorter); 9809 } 9810 9811 @Override 9812 protected void dumpFilter(PrintWriter out, String prefix, 9813 PackageParser.ActivityIntentInfo filter) { 9814 out.print(prefix); out.print( 9815 Integer.toHexString(System.identityHashCode(filter.activity))); 9816 out.print(' '); 9817 filter.activity.printComponentShortName(out); 9818 out.print(" filter "); 9819 out.println(Integer.toHexString(System.identityHashCode(filter))); 9820 } 9821 9822 @Override 9823 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 9824 return filter.activity; 9825 } 9826 9827 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 9828 PackageParser.Activity activity = (PackageParser.Activity)label; 9829 out.print(prefix); out.print( 9830 Integer.toHexString(System.identityHashCode(activity))); 9831 out.print(' '); 9832 activity.printComponentShortName(out); 9833 if (count > 1) { 9834 out.print(" ("); out.print(count); out.print(" filters)"); 9835 } 9836 out.println(); 9837 } 9838 9839// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 9840// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 9841// final List<ResolveInfo> retList = Lists.newArrayList(); 9842// while (i.hasNext()) { 9843// final ResolveInfo resolveInfo = i.next(); 9844// if (isEnabledLP(resolveInfo.activityInfo)) { 9845// retList.add(resolveInfo); 9846// } 9847// } 9848// return retList; 9849// } 9850 9851 // Keys are String (activity class name), values are Activity. 9852 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 9853 = new ArrayMap<ComponentName, PackageParser.Activity>(); 9854 private int mFlags; 9855 } 9856 9857 private final class ServiceIntentResolver 9858 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 9859 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9860 boolean defaultOnly, int userId) { 9861 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9862 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9863 } 9864 9865 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9866 int userId) { 9867 if (!sUserManager.exists(userId)) return null; 9868 mFlags = flags; 9869 return super.queryIntent(intent, resolvedType, 9870 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9871 } 9872 9873 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9874 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 9875 if (!sUserManager.exists(userId)) return null; 9876 if (packageServices == null) { 9877 return null; 9878 } 9879 mFlags = flags; 9880 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9881 final int N = packageServices.size(); 9882 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 9883 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 9884 9885 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 9886 for (int i = 0; i < N; ++i) { 9887 intentFilters = packageServices.get(i).intents; 9888 if (intentFilters != null && intentFilters.size() > 0) { 9889 PackageParser.ServiceIntentInfo[] array = 9890 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 9891 intentFilters.toArray(array); 9892 listCut.add(array); 9893 } 9894 } 9895 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9896 } 9897 9898 public final void addService(PackageParser.Service s) { 9899 mServices.put(s.getComponentName(), s); 9900 if (DEBUG_SHOW_INFO) { 9901 Log.v(TAG, " " 9902 + (s.info.nonLocalizedLabel != null 9903 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9904 Log.v(TAG, " Class=" + s.info.name); 9905 } 9906 final int NI = s.intents.size(); 9907 int j; 9908 for (j=0; j<NI; j++) { 9909 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9910 if (DEBUG_SHOW_INFO) { 9911 Log.v(TAG, " IntentFilter:"); 9912 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9913 } 9914 if (!intent.debugCheck()) { 9915 Log.w(TAG, "==> For Service " + s.info.name); 9916 } 9917 addFilter(intent); 9918 } 9919 } 9920 9921 public final void removeService(PackageParser.Service s) { 9922 mServices.remove(s.getComponentName()); 9923 if (DEBUG_SHOW_INFO) { 9924 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 9925 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 9926 Log.v(TAG, " Class=" + s.info.name); 9927 } 9928 final int NI = s.intents.size(); 9929 int j; 9930 for (j=0; j<NI; j++) { 9931 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 9932 if (DEBUG_SHOW_INFO) { 9933 Log.v(TAG, " IntentFilter:"); 9934 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 9935 } 9936 removeFilter(intent); 9937 } 9938 } 9939 9940 @Override 9941 protected boolean allowFilterResult( 9942 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 9943 ServiceInfo filterSi = filter.service.info; 9944 for (int i=dest.size()-1; i>=0; i--) { 9945 ServiceInfo destAi = dest.get(i).serviceInfo; 9946 if (destAi.name == filterSi.name 9947 && destAi.packageName == filterSi.packageName) { 9948 return false; 9949 } 9950 } 9951 return true; 9952 } 9953 9954 @Override 9955 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 9956 return new PackageParser.ServiceIntentInfo[size]; 9957 } 9958 9959 @Override 9960 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 9961 if (!sUserManager.exists(userId)) return true; 9962 PackageParser.Package p = filter.service.owner; 9963 if (p != null) { 9964 PackageSetting ps = (PackageSetting)p.mExtras; 9965 if (ps != null) { 9966 // System apps are never considered stopped for purposes of 9967 // filtering, because there may be no way for the user to 9968 // actually re-launch them. 9969 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 9970 && ps.getStopped(userId); 9971 } 9972 } 9973 return false; 9974 } 9975 9976 @Override 9977 protected boolean isPackageForFilter(String packageName, 9978 PackageParser.ServiceIntentInfo info) { 9979 return packageName.equals(info.service.owner.packageName); 9980 } 9981 9982 @Override 9983 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 9984 int match, int userId) { 9985 if (!sUserManager.exists(userId)) return null; 9986 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 9987 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 9988 return null; 9989 } 9990 final PackageParser.Service service = info.service; 9991 PackageSetting ps = (PackageSetting) service.owner.mExtras; 9992 if (ps == null) { 9993 return null; 9994 } 9995 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 9996 ps.readUserState(userId), userId); 9997 if (si == null) { 9998 return null; 9999 } 10000 final ResolveInfo res = new ResolveInfo(); 10001 res.serviceInfo = si; 10002 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10003 res.filter = filter; 10004 } 10005 res.priority = info.getPriority(); 10006 res.preferredOrder = service.owner.mPreferredOrder; 10007 res.match = match; 10008 res.isDefault = info.hasDefault; 10009 res.labelRes = info.labelRes; 10010 res.nonLocalizedLabel = info.nonLocalizedLabel; 10011 res.icon = info.icon; 10012 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10013 return res; 10014 } 10015 10016 @Override 10017 protected void sortResults(List<ResolveInfo> results) { 10018 Collections.sort(results, mResolvePrioritySorter); 10019 } 10020 10021 @Override 10022 protected void dumpFilter(PrintWriter out, String prefix, 10023 PackageParser.ServiceIntentInfo filter) { 10024 out.print(prefix); out.print( 10025 Integer.toHexString(System.identityHashCode(filter.service))); 10026 out.print(' '); 10027 filter.service.printComponentShortName(out); 10028 out.print(" filter "); 10029 out.println(Integer.toHexString(System.identityHashCode(filter))); 10030 } 10031 10032 @Override 10033 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10034 return filter.service; 10035 } 10036 10037 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10038 PackageParser.Service service = (PackageParser.Service)label; 10039 out.print(prefix); out.print( 10040 Integer.toHexString(System.identityHashCode(service))); 10041 out.print(' '); 10042 service.printComponentShortName(out); 10043 if (count > 1) { 10044 out.print(" ("); out.print(count); out.print(" filters)"); 10045 } 10046 out.println(); 10047 } 10048 10049// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10050// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10051// final List<ResolveInfo> retList = Lists.newArrayList(); 10052// while (i.hasNext()) { 10053// final ResolveInfo resolveInfo = (ResolveInfo) i; 10054// if (isEnabledLP(resolveInfo.serviceInfo)) { 10055// retList.add(resolveInfo); 10056// } 10057// } 10058// return retList; 10059// } 10060 10061 // Keys are String (activity class name), values are Activity. 10062 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10063 = new ArrayMap<ComponentName, PackageParser.Service>(); 10064 private int mFlags; 10065 }; 10066 10067 private final class ProviderIntentResolver 10068 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10069 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10070 boolean defaultOnly, int userId) { 10071 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10072 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10073 } 10074 10075 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10076 int userId) { 10077 if (!sUserManager.exists(userId)) 10078 return null; 10079 mFlags = flags; 10080 return super.queryIntent(intent, resolvedType, 10081 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10082 } 10083 10084 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10085 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10086 if (!sUserManager.exists(userId)) 10087 return null; 10088 if (packageProviders == null) { 10089 return null; 10090 } 10091 mFlags = flags; 10092 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10093 final int N = packageProviders.size(); 10094 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10095 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10096 10097 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10098 for (int i = 0; i < N; ++i) { 10099 intentFilters = packageProviders.get(i).intents; 10100 if (intentFilters != null && intentFilters.size() > 0) { 10101 PackageParser.ProviderIntentInfo[] array = 10102 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10103 intentFilters.toArray(array); 10104 listCut.add(array); 10105 } 10106 } 10107 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10108 } 10109 10110 public final void addProvider(PackageParser.Provider p) { 10111 if (mProviders.containsKey(p.getComponentName())) { 10112 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10113 return; 10114 } 10115 10116 mProviders.put(p.getComponentName(), p); 10117 if (DEBUG_SHOW_INFO) { 10118 Log.v(TAG, " " 10119 + (p.info.nonLocalizedLabel != null 10120 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10121 Log.v(TAG, " Class=" + p.info.name); 10122 } 10123 final int NI = p.intents.size(); 10124 int j; 10125 for (j = 0; j < NI; j++) { 10126 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10127 if (DEBUG_SHOW_INFO) { 10128 Log.v(TAG, " IntentFilter:"); 10129 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10130 } 10131 if (!intent.debugCheck()) { 10132 Log.w(TAG, "==> For Provider " + p.info.name); 10133 } 10134 addFilter(intent); 10135 } 10136 } 10137 10138 public final void removeProvider(PackageParser.Provider p) { 10139 mProviders.remove(p.getComponentName()); 10140 if (DEBUG_SHOW_INFO) { 10141 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10142 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10143 Log.v(TAG, " Class=" + p.info.name); 10144 } 10145 final int NI = p.intents.size(); 10146 int j; 10147 for (j = 0; j < NI; j++) { 10148 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10149 if (DEBUG_SHOW_INFO) { 10150 Log.v(TAG, " IntentFilter:"); 10151 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10152 } 10153 removeFilter(intent); 10154 } 10155 } 10156 10157 @Override 10158 protected boolean allowFilterResult( 10159 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10160 ProviderInfo filterPi = filter.provider.info; 10161 for (int i = dest.size() - 1; i >= 0; i--) { 10162 ProviderInfo destPi = dest.get(i).providerInfo; 10163 if (destPi.name == filterPi.name 10164 && destPi.packageName == filterPi.packageName) { 10165 return false; 10166 } 10167 } 10168 return true; 10169 } 10170 10171 @Override 10172 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10173 return new PackageParser.ProviderIntentInfo[size]; 10174 } 10175 10176 @Override 10177 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10178 if (!sUserManager.exists(userId)) 10179 return true; 10180 PackageParser.Package p = filter.provider.owner; 10181 if (p != null) { 10182 PackageSetting ps = (PackageSetting) p.mExtras; 10183 if (ps != null) { 10184 // System apps are never considered stopped for purposes of 10185 // filtering, because there may be no way for the user to 10186 // actually re-launch them. 10187 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10188 && ps.getStopped(userId); 10189 } 10190 } 10191 return false; 10192 } 10193 10194 @Override 10195 protected boolean isPackageForFilter(String packageName, 10196 PackageParser.ProviderIntentInfo info) { 10197 return packageName.equals(info.provider.owner.packageName); 10198 } 10199 10200 @Override 10201 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10202 int match, int userId) { 10203 if (!sUserManager.exists(userId)) 10204 return null; 10205 final PackageParser.ProviderIntentInfo info = filter; 10206 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10207 return null; 10208 } 10209 final PackageParser.Provider provider = info.provider; 10210 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10211 if (ps == null) { 10212 return null; 10213 } 10214 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10215 ps.readUserState(userId), userId); 10216 if (pi == null) { 10217 return null; 10218 } 10219 final ResolveInfo res = new ResolveInfo(); 10220 res.providerInfo = pi; 10221 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10222 res.filter = filter; 10223 } 10224 res.priority = info.getPriority(); 10225 res.preferredOrder = provider.owner.mPreferredOrder; 10226 res.match = match; 10227 res.isDefault = info.hasDefault; 10228 res.labelRes = info.labelRes; 10229 res.nonLocalizedLabel = info.nonLocalizedLabel; 10230 res.icon = info.icon; 10231 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10232 return res; 10233 } 10234 10235 @Override 10236 protected void sortResults(List<ResolveInfo> results) { 10237 Collections.sort(results, mResolvePrioritySorter); 10238 } 10239 10240 @Override 10241 protected void dumpFilter(PrintWriter out, String prefix, 10242 PackageParser.ProviderIntentInfo filter) { 10243 out.print(prefix); 10244 out.print( 10245 Integer.toHexString(System.identityHashCode(filter.provider))); 10246 out.print(' '); 10247 filter.provider.printComponentShortName(out); 10248 out.print(" filter "); 10249 out.println(Integer.toHexString(System.identityHashCode(filter))); 10250 } 10251 10252 @Override 10253 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10254 return filter.provider; 10255 } 10256 10257 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10258 PackageParser.Provider provider = (PackageParser.Provider)label; 10259 out.print(prefix); out.print( 10260 Integer.toHexString(System.identityHashCode(provider))); 10261 out.print(' '); 10262 provider.printComponentShortName(out); 10263 if (count > 1) { 10264 out.print(" ("); out.print(count); out.print(" filters)"); 10265 } 10266 out.println(); 10267 } 10268 10269 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10270 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10271 private int mFlags; 10272 } 10273 10274 private static final class EphemeralIntentResolver 10275 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10276 @Override 10277 protected EphemeralResolveIntentInfo[] newArray(int size) { 10278 return new EphemeralResolveIntentInfo[size]; 10279 } 10280 10281 @Override 10282 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10283 return true; 10284 } 10285 10286 @Override 10287 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10288 int userId) { 10289 if (!sUserManager.exists(userId)) { 10290 return null; 10291 } 10292 return info.getEphemeralResolveInfo(); 10293 } 10294 } 10295 10296 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10297 new Comparator<ResolveInfo>() { 10298 public int compare(ResolveInfo r1, ResolveInfo r2) { 10299 int v1 = r1.priority; 10300 int v2 = r2.priority; 10301 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10302 if (v1 != v2) { 10303 return (v1 > v2) ? -1 : 1; 10304 } 10305 v1 = r1.preferredOrder; 10306 v2 = r2.preferredOrder; 10307 if (v1 != v2) { 10308 return (v1 > v2) ? -1 : 1; 10309 } 10310 if (r1.isDefault != r2.isDefault) { 10311 return r1.isDefault ? -1 : 1; 10312 } 10313 v1 = r1.match; 10314 v2 = r2.match; 10315 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10316 if (v1 != v2) { 10317 return (v1 > v2) ? -1 : 1; 10318 } 10319 if (r1.system != r2.system) { 10320 return r1.system ? -1 : 1; 10321 } 10322 if (r1.activityInfo != null) { 10323 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10324 } 10325 if (r1.serviceInfo != null) { 10326 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10327 } 10328 if (r1.providerInfo != null) { 10329 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10330 } 10331 return 0; 10332 } 10333 }; 10334 10335 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10336 new Comparator<ProviderInfo>() { 10337 public int compare(ProviderInfo p1, ProviderInfo p2) { 10338 final int v1 = p1.initOrder; 10339 final int v2 = p2.initOrder; 10340 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10341 } 10342 }; 10343 10344 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10345 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10346 final int[] userIds) { 10347 mHandler.post(new Runnable() { 10348 @Override 10349 public void run() { 10350 try { 10351 final IActivityManager am = ActivityManagerNative.getDefault(); 10352 if (am == null) return; 10353 final int[] resolvedUserIds; 10354 if (userIds == null) { 10355 resolvedUserIds = am.getRunningUserIds(); 10356 } else { 10357 resolvedUserIds = userIds; 10358 } 10359 for (int id : resolvedUserIds) { 10360 final Intent intent = new Intent(action, 10361 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10362 if (extras != null) { 10363 intent.putExtras(extras); 10364 } 10365 if (targetPkg != null) { 10366 intent.setPackage(targetPkg); 10367 } 10368 // Modify the UID when posting to other users 10369 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10370 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10371 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10372 intent.putExtra(Intent.EXTRA_UID, uid); 10373 } 10374 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10375 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10376 if (DEBUG_BROADCASTS) { 10377 RuntimeException here = new RuntimeException("here"); 10378 here.fillInStackTrace(); 10379 Slog.d(TAG, "Sending to user " + id + ": " 10380 + intent.toShortString(false, true, false, false) 10381 + " " + intent.getExtras(), here); 10382 } 10383 am.broadcastIntent(null, intent, null, finishedReceiver, 10384 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10385 null, finishedReceiver != null, false, id); 10386 } 10387 } catch (RemoteException ex) { 10388 } 10389 } 10390 }); 10391 } 10392 10393 /** 10394 * Check if the external storage media is available. This is true if there 10395 * is a mounted external storage medium or if the external storage is 10396 * emulated. 10397 */ 10398 private boolean isExternalMediaAvailable() { 10399 return mMediaMounted || Environment.isExternalStorageEmulated(); 10400 } 10401 10402 @Override 10403 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10404 // writer 10405 synchronized (mPackages) { 10406 if (!isExternalMediaAvailable()) { 10407 // If the external storage is no longer mounted at this point, 10408 // the caller may not have been able to delete all of this 10409 // packages files and can not delete any more. Bail. 10410 return null; 10411 } 10412 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10413 if (lastPackage != null) { 10414 pkgs.remove(lastPackage); 10415 } 10416 if (pkgs.size() > 0) { 10417 return pkgs.get(0); 10418 } 10419 } 10420 return null; 10421 } 10422 10423 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10424 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10425 userId, andCode ? 1 : 0, packageName); 10426 if (mSystemReady) { 10427 msg.sendToTarget(); 10428 } else { 10429 if (mPostSystemReadyMessages == null) { 10430 mPostSystemReadyMessages = new ArrayList<>(); 10431 } 10432 mPostSystemReadyMessages.add(msg); 10433 } 10434 } 10435 10436 void startCleaningPackages() { 10437 // reader 10438 synchronized (mPackages) { 10439 if (!isExternalMediaAvailable()) { 10440 return; 10441 } 10442 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10443 return; 10444 } 10445 } 10446 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10447 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10448 IActivityManager am = ActivityManagerNative.getDefault(); 10449 if (am != null) { 10450 try { 10451 am.startService(null, intent, null, mContext.getOpPackageName(), 10452 UserHandle.USER_SYSTEM); 10453 } catch (RemoteException e) { 10454 } 10455 } 10456 } 10457 10458 @Override 10459 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10460 int installFlags, String installerPackageName, int userId) { 10461 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10462 10463 final int callingUid = Binder.getCallingUid(); 10464 enforceCrossUserPermission(callingUid, userId, 10465 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 10466 10467 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10468 try { 10469 if (observer != null) { 10470 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 10471 } 10472 } catch (RemoteException re) { 10473 } 10474 return; 10475 } 10476 10477 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 10478 installFlags |= PackageManager.INSTALL_FROM_ADB; 10479 10480 } else { 10481 // Caller holds INSTALL_PACKAGES permission, so we're less strict 10482 // about installerPackageName. 10483 10484 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 10485 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 10486 } 10487 10488 UserHandle user; 10489 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 10490 user = UserHandle.ALL; 10491 } else { 10492 user = new UserHandle(userId); 10493 } 10494 10495 // Only system components can circumvent runtime permissions when installing. 10496 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 10497 && mContext.checkCallingOrSelfPermission(Manifest.permission 10498 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 10499 throw new SecurityException("You need the " 10500 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 10501 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 10502 } 10503 10504 final File originFile = new File(originPath); 10505 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 10506 10507 final Message msg = mHandler.obtainMessage(INIT_COPY); 10508 final VerificationInfo verificationInfo = new VerificationInfo( 10509 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 10510 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 10511 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 10512 null /*packageAbiOverride*/, null /*grantedPermissions*/); 10513 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 10514 msg.obj = params; 10515 10516 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 10517 System.identityHashCode(msg.obj)); 10518 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10519 System.identityHashCode(msg.obj)); 10520 10521 mHandler.sendMessage(msg); 10522 } 10523 10524 void installStage(String packageName, File stagedDir, String stagedCid, 10525 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 10526 String installerPackageName, int installerUid, UserHandle user) { 10527 if (DEBUG_EPHEMERAL) { 10528 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 10529 Slog.d(TAG, "Ephemeral install of " + packageName); 10530 } 10531 } 10532 final VerificationInfo verificationInfo = new VerificationInfo( 10533 sessionParams.originatingUri, sessionParams.referrerUri, 10534 sessionParams.originatingUid, installerUid); 10535 10536 final OriginInfo origin; 10537 if (stagedDir != null) { 10538 origin = OriginInfo.fromStagedFile(stagedDir); 10539 } else { 10540 origin = OriginInfo.fromStagedContainer(stagedCid); 10541 } 10542 10543 final Message msg = mHandler.obtainMessage(INIT_COPY); 10544 final InstallParams params = new InstallParams(origin, null, observer, 10545 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 10546 verificationInfo, user, sessionParams.abiOverride, 10547 sessionParams.grantedRuntimePermissions); 10548 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 10549 msg.obj = params; 10550 10551 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 10552 System.identityHashCode(msg.obj)); 10553 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 10554 System.identityHashCode(msg.obj)); 10555 10556 mHandler.sendMessage(msg); 10557 } 10558 10559 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 10560 int userId) { 10561 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 10562 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 10563 } 10564 10565 private void sendPackageAddedForUser(String packageName, boolean isSystem, 10566 int appId, int userId) { 10567 Bundle extras = new Bundle(1); 10568 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 10569 10570 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 10571 packageName, extras, 0, null, null, new int[] {userId}); 10572 try { 10573 IActivityManager am = ActivityManagerNative.getDefault(); 10574 if (isSystem && am.isUserRunning(userId, 0)) { 10575 // The just-installed/enabled app is bundled on the system, so presumed 10576 // to be able to run automatically without needing an explicit launch. 10577 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 10578 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 10579 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 10580 .setPackage(packageName); 10581 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 10582 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 10583 } 10584 } catch (RemoteException e) { 10585 // shouldn't happen 10586 Slog.w(TAG, "Unable to bootstrap installed package", e); 10587 } 10588 } 10589 10590 @Override 10591 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 10592 int userId) { 10593 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10594 PackageSetting pkgSetting; 10595 final int uid = Binder.getCallingUid(); 10596 enforceCrossUserPermission(uid, userId, 10597 true /* requireFullPermission */, true /* checkShell */, 10598 "setApplicationHiddenSetting for user " + userId); 10599 10600 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 10601 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 10602 return false; 10603 } 10604 10605 long callingId = Binder.clearCallingIdentity(); 10606 try { 10607 boolean sendAdded = false; 10608 boolean sendRemoved = false; 10609 // writer 10610 synchronized (mPackages) { 10611 pkgSetting = mSettings.mPackages.get(packageName); 10612 if (pkgSetting == null) { 10613 return false; 10614 } 10615 if (pkgSetting.getHidden(userId) != hidden) { 10616 pkgSetting.setHidden(hidden, userId); 10617 mSettings.writePackageRestrictionsLPr(userId); 10618 if (hidden) { 10619 sendRemoved = true; 10620 } else { 10621 sendAdded = true; 10622 } 10623 } 10624 } 10625 if (sendAdded) { 10626 sendPackageAddedForUser(packageName, pkgSetting, userId); 10627 return true; 10628 } 10629 if (sendRemoved) { 10630 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 10631 "hiding pkg"); 10632 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 10633 return true; 10634 } 10635 } finally { 10636 Binder.restoreCallingIdentity(callingId); 10637 } 10638 return false; 10639 } 10640 10641 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 10642 int userId) { 10643 final PackageRemovedInfo info = new PackageRemovedInfo(); 10644 info.removedPackage = packageName; 10645 info.removedUsers = new int[] {userId}; 10646 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 10647 info.sendPackageRemovedBroadcasts(true /*killApp*/); 10648 } 10649 10650 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 10651 if (pkgList.length > 0) { 10652 Bundle extras = new Bundle(1); 10653 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 10654 10655 sendPackageBroadcast( 10656 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 10657 : Intent.ACTION_PACKAGES_UNSUSPENDED, 10658 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 10659 new int[] {userId}); 10660 } 10661 } 10662 10663 /** 10664 * Returns true if application is not found or there was an error. Otherwise it returns 10665 * the hidden state of the package for the given user. 10666 */ 10667 @Override 10668 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 10669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10670 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10671 true /* requireFullPermission */, false /* checkShell */, 10672 "getApplicationHidden for user " + userId); 10673 PackageSetting pkgSetting; 10674 long callingId = Binder.clearCallingIdentity(); 10675 try { 10676 // writer 10677 synchronized (mPackages) { 10678 pkgSetting = mSettings.mPackages.get(packageName); 10679 if (pkgSetting == null) { 10680 return true; 10681 } 10682 return pkgSetting.getHidden(userId); 10683 } 10684 } finally { 10685 Binder.restoreCallingIdentity(callingId); 10686 } 10687 } 10688 10689 /** 10690 * @hide 10691 */ 10692 @Override 10693 public int installExistingPackageAsUser(String packageName, int userId) { 10694 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 10695 null); 10696 PackageSetting pkgSetting; 10697 final int uid = Binder.getCallingUid(); 10698 enforceCrossUserPermission(uid, userId, 10699 true /* requireFullPermission */, true /* checkShell */, 10700 "installExistingPackage for user " + userId); 10701 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 10702 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 10703 } 10704 10705 long callingId = Binder.clearCallingIdentity(); 10706 try { 10707 boolean installed = false; 10708 10709 // writer 10710 synchronized (mPackages) { 10711 pkgSetting = mSettings.mPackages.get(packageName); 10712 if (pkgSetting == null) { 10713 return PackageManager.INSTALL_FAILED_INVALID_URI; 10714 } 10715 if (!pkgSetting.getInstalled(userId)) { 10716 pkgSetting.setInstalled(true, userId); 10717 pkgSetting.setHidden(false, userId); 10718 mSettings.writePackageRestrictionsLPr(userId); 10719 installed = true; 10720 } 10721 } 10722 10723 if (installed) { 10724 if (pkgSetting.pkg != null) { 10725 prepareAppDataAfterInstall(pkgSetting.pkg); 10726 } 10727 sendPackageAddedForUser(packageName, pkgSetting, userId); 10728 } 10729 } finally { 10730 Binder.restoreCallingIdentity(callingId); 10731 } 10732 10733 return PackageManager.INSTALL_SUCCEEDED; 10734 } 10735 10736 boolean isUserRestricted(int userId, String restrictionKey) { 10737 Bundle restrictions = sUserManager.getUserRestrictions(userId); 10738 if (restrictions.getBoolean(restrictionKey, false)) { 10739 Log.w(TAG, "User is restricted: " + restrictionKey); 10740 return true; 10741 } 10742 return false; 10743 } 10744 10745 @Override 10746 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 10747 int userId) { 10748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 10749 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10750 true /* requireFullPermission */, true /* checkShell */, 10751 "setPackagesSuspended for user " + userId); 10752 10753 if (ArrayUtils.isEmpty(packageNames)) { 10754 return packageNames; 10755 } 10756 10757 // List of package names for whom the suspended state has changed. 10758 List<String> changedPackages = new ArrayList<>(packageNames.length); 10759 // List of package names for whom the suspended state is not set as requested in this 10760 // method. 10761 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 10762 for (int i = 0; i < packageNames.length; i++) { 10763 String packageName = packageNames[i]; 10764 long callingId = Binder.clearCallingIdentity(); 10765 try { 10766 boolean changed = false; 10767 final int appId; 10768 synchronized (mPackages) { 10769 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10770 if (pkgSetting == null) { 10771 Slog.w(TAG, "Could not find package setting for package \"" + packageName 10772 + "\". Skipping suspending/un-suspending."); 10773 unactionedPackages.add(packageName); 10774 continue; 10775 } 10776 appId = pkgSetting.appId; 10777 if (pkgSetting.getSuspended(userId) != suspended) { 10778 if (!canSuspendPackageForUserLocked(packageName, userId)) { 10779 unactionedPackages.add(packageName); 10780 continue; 10781 } 10782 pkgSetting.setSuspended(suspended, userId); 10783 mSettings.writePackageRestrictionsLPr(userId); 10784 changed = true; 10785 changedPackages.add(packageName); 10786 } 10787 } 10788 10789 if (changed && suspended) { 10790 killApplication(packageName, UserHandle.getUid(userId, appId), 10791 "suspending package"); 10792 } 10793 } finally { 10794 Binder.restoreCallingIdentity(callingId); 10795 } 10796 } 10797 10798 if (!changedPackages.isEmpty()) { 10799 sendPackagesSuspendedForUser(changedPackages.toArray( 10800 new String[changedPackages.size()]), userId, suspended); 10801 } 10802 10803 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 10804 } 10805 10806 @Override 10807 public boolean isPackageSuspendedForUser(String packageName, int userId) { 10808 enforceCrossUserPermission(Binder.getCallingUid(), userId, 10809 true /* requireFullPermission */, false /* checkShell */, 10810 "isPackageSuspendedForUser for user " + userId); 10811 synchronized (mPackages) { 10812 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 10813 return pkgSetting != null && pkgSetting.getSuspended(userId); 10814 } 10815 } 10816 10817 // TODO: investigate and add more restrictions for suspending crucial packages. 10818 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 10819 if (isPackageDeviceAdmin(packageName, userId)) { 10820 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10821 + "\": has active device admin"); 10822 return false; 10823 } 10824 10825 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 10826 if (packageName.equals(activeLauncherPackageName)) { 10827 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10828 + "\" because it is set as the active launcher"); 10829 return false; 10830 } 10831 10832 final PackageParser.Package pkg = mPackages.get(packageName); 10833 if (pkg != null && isPrivilegedApp(pkg)) { 10834 Slog.w(TAG, "Not suspending/un-suspending package \"" + packageName 10835 + "\" because it is a privileged app"); 10836 return false; 10837 } 10838 10839 return true; 10840 } 10841 10842 private String getActiveLauncherPackageName(int userId) { 10843 Intent intent = new Intent(Intent.ACTION_MAIN); 10844 intent.addCategory(Intent.CATEGORY_HOME); 10845 ResolveInfo resolveInfo = resolveIntent( 10846 intent, 10847 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 10848 PackageManager.MATCH_DEFAULT_ONLY, 10849 userId); 10850 10851 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 10852 } 10853 10854 @Override 10855 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 10856 mContext.enforceCallingOrSelfPermission( 10857 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10858 "Only package verification agents can verify applications"); 10859 10860 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10861 final PackageVerificationResponse response = new PackageVerificationResponse( 10862 verificationCode, Binder.getCallingUid()); 10863 msg.arg1 = id; 10864 msg.obj = response; 10865 mHandler.sendMessage(msg); 10866 } 10867 10868 @Override 10869 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 10870 long millisecondsToDelay) { 10871 mContext.enforceCallingOrSelfPermission( 10872 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10873 "Only package verification agents can extend verification timeouts"); 10874 10875 final PackageVerificationState state = mPendingVerification.get(id); 10876 final PackageVerificationResponse response = new PackageVerificationResponse( 10877 verificationCodeAtTimeout, Binder.getCallingUid()); 10878 10879 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 10880 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 10881 } 10882 if (millisecondsToDelay < 0) { 10883 millisecondsToDelay = 0; 10884 } 10885 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 10886 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 10887 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 10888 } 10889 10890 if ((state != null) && !state.timeoutExtended()) { 10891 state.extendTimeout(); 10892 10893 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 10894 msg.arg1 = id; 10895 msg.obj = response; 10896 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 10897 } 10898 } 10899 10900 private void broadcastPackageVerified(int verificationId, Uri packageUri, 10901 int verificationCode, UserHandle user) { 10902 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 10903 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 10904 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10905 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10906 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 10907 10908 mContext.sendBroadcastAsUser(intent, user, 10909 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 10910 } 10911 10912 private ComponentName matchComponentForVerifier(String packageName, 10913 List<ResolveInfo> receivers) { 10914 ActivityInfo targetReceiver = null; 10915 10916 final int NR = receivers.size(); 10917 for (int i = 0; i < NR; i++) { 10918 final ResolveInfo info = receivers.get(i); 10919 if (info.activityInfo == null) { 10920 continue; 10921 } 10922 10923 if (packageName.equals(info.activityInfo.packageName)) { 10924 targetReceiver = info.activityInfo; 10925 break; 10926 } 10927 } 10928 10929 if (targetReceiver == null) { 10930 return null; 10931 } 10932 10933 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 10934 } 10935 10936 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 10937 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 10938 if (pkgInfo.verifiers.length == 0) { 10939 return null; 10940 } 10941 10942 final int N = pkgInfo.verifiers.length; 10943 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 10944 for (int i = 0; i < N; i++) { 10945 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 10946 10947 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 10948 receivers); 10949 if (comp == null) { 10950 continue; 10951 } 10952 10953 final int verifierUid = getUidForVerifier(verifierInfo); 10954 if (verifierUid == -1) { 10955 continue; 10956 } 10957 10958 if (DEBUG_VERIFY) { 10959 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 10960 + " with the correct signature"); 10961 } 10962 sufficientVerifiers.add(comp); 10963 verificationState.addSufficientVerifier(verifierUid); 10964 } 10965 10966 return sufficientVerifiers; 10967 } 10968 10969 private int getUidForVerifier(VerifierInfo verifierInfo) { 10970 synchronized (mPackages) { 10971 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 10972 if (pkg == null) { 10973 return -1; 10974 } else if (pkg.mSignatures.length != 1) { 10975 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10976 + " has more than one signature; ignoring"); 10977 return -1; 10978 } 10979 10980 /* 10981 * If the public key of the package's signature does not match 10982 * our expected public key, then this is a different package and 10983 * we should skip. 10984 */ 10985 10986 final byte[] expectedPublicKey; 10987 try { 10988 final Signature verifierSig = pkg.mSignatures[0]; 10989 final PublicKey publicKey = verifierSig.getPublicKey(); 10990 expectedPublicKey = publicKey.getEncoded(); 10991 } catch (CertificateException e) { 10992 return -1; 10993 } 10994 10995 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 10996 10997 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 10998 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 10999 + " does not have the expected public key; ignoring"); 11000 return -1; 11001 } 11002 11003 return pkg.applicationInfo.uid; 11004 } 11005 } 11006 11007 @Override 11008 public void finishPackageInstall(int token) { 11009 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11010 11011 if (DEBUG_INSTALL) { 11012 Slog.v(TAG, "BM finishing package install for " + token); 11013 } 11014 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11015 11016 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11017 mHandler.sendMessage(msg); 11018 } 11019 11020 /** 11021 * Get the verification agent timeout. 11022 * 11023 * @return verification timeout in milliseconds 11024 */ 11025 private long getVerificationTimeout() { 11026 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11027 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11028 DEFAULT_VERIFICATION_TIMEOUT); 11029 } 11030 11031 /** 11032 * Get the default verification agent response code. 11033 * 11034 * @return default verification response code 11035 */ 11036 private int getDefaultVerificationResponse() { 11037 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11038 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11039 DEFAULT_VERIFICATION_RESPONSE); 11040 } 11041 11042 /** 11043 * Check whether or not package verification has been enabled. 11044 * 11045 * @return true if verification should be performed 11046 */ 11047 private boolean isVerificationEnabled(int userId, int installFlags) { 11048 if (!DEFAULT_VERIFY_ENABLE) { 11049 return false; 11050 } 11051 // Ephemeral apps don't get the full verification treatment 11052 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11053 if (DEBUG_EPHEMERAL) { 11054 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11055 } 11056 return false; 11057 } 11058 11059 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11060 11061 // Check if installing from ADB 11062 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11063 // Do not run verification in a test harness environment 11064 if (ActivityManager.isRunningInTestHarness()) { 11065 return false; 11066 } 11067 if (ensureVerifyAppsEnabled) { 11068 return true; 11069 } 11070 // Check if the developer does not want package verification for ADB installs 11071 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11072 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11073 return false; 11074 } 11075 } 11076 11077 if (ensureVerifyAppsEnabled) { 11078 return true; 11079 } 11080 11081 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11082 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11083 } 11084 11085 @Override 11086 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11087 throws RemoteException { 11088 mContext.enforceCallingOrSelfPermission( 11089 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11090 "Only intentfilter verification agents can verify applications"); 11091 11092 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11093 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11094 Binder.getCallingUid(), verificationCode, failedDomains); 11095 msg.arg1 = id; 11096 msg.obj = response; 11097 mHandler.sendMessage(msg); 11098 } 11099 11100 @Override 11101 public int getIntentVerificationStatus(String packageName, int userId) { 11102 synchronized (mPackages) { 11103 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11104 } 11105 } 11106 11107 @Override 11108 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11109 mContext.enforceCallingOrSelfPermission( 11110 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11111 11112 boolean result = false; 11113 synchronized (mPackages) { 11114 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11115 } 11116 if (result) { 11117 scheduleWritePackageRestrictionsLocked(userId); 11118 } 11119 return result; 11120 } 11121 11122 @Override 11123 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11124 String packageName) { 11125 synchronized (mPackages) { 11126 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11127 } 11128 } 11129 11130 @Override 11131 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11132 if (TextUtils.isEmpty(packageName)) { 11133 return ParceledListSlice.emptyList(); 11134 } 11135 synchronized (mPackages) { 11136 PackageParser.Package pkg = mPackages.get(packageName); 11137 if (pkg == null || pkg.activities == null) { 11138 return ParceledListSlice.emptyList(); 11139 } 11140 final int count = pkg.activities.size(); 11141 ArrayList<IntentFilter> result = new ArrayList<>(); 11142 for (int n=0; n<count; n++) { 11143 PackageParser.Activity activity = pkg.activities.get(n); 11144 if (activity.intents != null && activity.intents.size() > 0) { 11145 result.addAll(activity.intents); 11146 } 11147 } 11148 return new ParceledListSlice<>(result); 11149 } 11150 } 11151 11152 @Override 11153 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11154 mContext.enforceCallingOrSelfPermission( 11155 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11156 11157 synchronized (mPackages) { 11158 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11159 if (packageName != null) { 11160 result |= updateIntentVerificationStatus(packageName, 11161 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11162 userId); 11163 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11164 packageName, userId); 11165 } 11166 return result; 11167 } 11168 } 11169 11170 @Override 11171 public String getDefaultBrowserPackageName(int userId) { 11172 synchronized (mPackages) { 11173 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11174 } 11175 } 11176 11177 /** 11178 * Get the "allow unknown sources" setting. 11179 * 11180 * @return the current "allow unknown sources" setting 11181 */ 11182 private int getUnknownSourcesSettings() { 11183 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11184 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 11185 -1); 11186 } 11187 11188 @Override 11189 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11190 final int uid = Binder.getCallingUid(); 11191 // writer 11192 synchronized (mPackages) { 11193 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11194 if (targetPackageSetting == null) { 11195 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11196 } 11197 11198 PackageSetting installerPackageSetting; 11199 if (installerPackageName != null) { 11200 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11201 if (installerPackageSetting == null) { 11202 throw new IllegalArgumentException("Unknown installer package: " 11203 + installerPackageName); 11204 } 11205 } else { 11206 installerPackageSetting = null; 11207 } 11208 11209 Signature[] callerSignature; 11210 Object obj = mSettings.getUserIdLPr(uid); 11211 if (obj != null) { 11212 if (obj instanceof SharedUserSetting) { 11213 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11214 } else if (obj instanceof PackageSetting) { 11215 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11216 } else { 11217 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11218 } 11219 } else { 11220 throw new SecurityException("Unknown calling UID: " + uid); 11221 } 11222 11223 // Verify: can't set installerPackageName to a package that is 11224 // not signed with the same cert as the caller. 11225 if (installerPackageSetting != null) { 11226 if (compareSignatures(callerSignature, 11227 installerPackageSetting.signatures.mSignatures) 11228 != PackageManager.SIGNATURE_MATCH) { 11229 throw new SecurityException( 11230 "Caller does not have same cert as new installer package " 11231 + installerPackageName); 11232 } 11233 } 11234 11235 // Verify: if target already has an installer package, it must 11236 // be signed with the same cert as the caller. 11237 if (targetPackageSetting.installerPackageName != null) { 11238 PackageSetting setting = mSettings.mPackages.get( 11239 targetPackageSetting.installerPackageName); 11240 // If the currently set package isn't valid, then it's always 11241 // okay to change it. 11242 if (setting != null) { 11243 if (compareSignatures(callerSignature, 11244 setting.signatures.mSignatures) 11245 != PackageManager.SIGNATURE_MATCH) { 11246 throw new SecurityException( 11247 "Caller does not have same cert as old installer package " 11248 + targetPackageSetting.installerPackageName); 11249 } 11250 } 11251 } 11252 11253 // Okay! 11254 targetPackageSetting.installerPackageName = installerPackageName; 11255 scheduleWriteSettingsLocked(); 11256 } 11257 } 11258 11259 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11260 // Queue up an async operation since the package installation may take a little while. 11261 mHandler.post(new Runnable() { 11262 public void run() { 11263 mHandler.removeCallbacks(this); 11264 // Result object to be returned 11265 PackageInstalledInfo res = new PackageInstalledInfo(); 11266 res.setReturnCode(currentStatus); 11267 res.uid = -1; 11268 res.pkg = null; 11269 res.removedInfo = null; 11270 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11271 args.doPreInstall(res.returnCode); 11272 synchronized (mInstallLock) { 11273 installPackageTracedLI(args, res); 11274 } 11275 args.doPostInstall(res.returnCode, res.uid); 11276 } 11277 11278 // A restore should be performed at this point if (a) the install 11279 // succeeded, (b) the operation is not an update, and (c) the new 11280 // package has not opted out of backup participation. 11281 final boolean update = res.removedInfo != null 11282 && res.removedInfo.removedPackage != null; 11283 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11284 boolean doRestore = !update 11285 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11286 11287 // Set up the post-install work request bookkeeping. This will be used 11288 // and cleaned up by the post-install event handling regardless of whether 11289 // there's a restore pass performed. Token values are >= 1. 11290 int token; 11291 if (mNextInstallToken < 0) mNextInstallToken = 1; 11292 token = mNextInstallToken++; 11293 11294 PostInstallData data = new PostInstallData(args, res); 11295 mRunningInstalls.put(token, data); 11296 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11297 11298 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11299 // Pass responsibility to the Backup Manager. It will perform a 11300 // restore if appropriate, then pass responsibility back to the 11301 // Package Manager to run the post-install observer callbacks 11302 // and broadcasts. 11303 IBackupManager bm = IBackupManager.Stub.asInterface( 11304 ServiceManager.getService(Context.BACKUP_SERVICE)); 11305 if (bm != null) { 11306 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11307 + " to BM for possible restore"); 11308 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11309 try { 11310 // TODO: http://b/22388012 11311 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11312 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11313 } else { 11314 doRestore = false; 11315 } 11316 } catch (RemoteException e) { 11317 // can't happen; the backup manager is local 11318 } catch (Exception e) { 11319 Slog.e(TAG, "Exception trying to enqueue restore", e); 11320 doRestore = false; 11321 } 11322 } else { 11323 Slog.e(TAG, "Backup Manager not found!"); 11324 doRestore = false; 11325 } 11326 } 11327 11328 if (!doRestore) { 11329 // No restore possible, or the Backup Manager was mysteriously not 11330 // available -- just fire the post-install work request directly. 11331 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11332 11333 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11334 11335 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11336 mHandler.sendMessage(msg); 11337 } 11338 } 11339 }); 11340 } 11341 11342 private abstract class HandlerParams { 11343 private static final int MAX_RETRIES = 4; 11344 11345 /** 11346 * Number of times startCopy() has been attempted and had a non-fatal 11347 * error. 11348 */ 11349 private int mRetries = 0; 11350 11351 /** User handle for the user requesting the information or installation. */ 11352 private final UserHandle mUser; 11353 String traceMethod; 11354 int traceCookie; 11355 11356 HandlerParams(UserHandle user) { 11357 mUser = user; 11358 } 11359 11360 UserHandle getUser() { 11361 return mUser; 11362 } 11363 11364 HandlerParams setTraceMethod(String traceMethod) { 11365 this.traceMethod = traceMethod; 11366 return this; 11367 } 11368 11369 HandlerParams setTraceCookie(int traceCookie) { 11370 this.traceCookie = traceCookie; 11371 return this; 11372 } 11373 11374 final boolean startCopy() { 11375 boolean res; 11376 try { 11377 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11378 11379 if (++mRetries > MAX_RETRIES) { 11380 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11381 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11382 handleServiceError(); 11383 return false; 11384 } else { 11385 handleStartCopy(); 11386 res = true; 11387 } 11388 } catch (RemoteException e) { 11389 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11390 mHandler.sendEmptyMessage(MCS_RECONNECT); 11391 res = false; 11392 } 11393 handleReturnCode(); 11394 return res; 11395 } 11396 11397 final void serviceError() { 11398 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11399 handleServiceError(); 11400 handleReturnCode(); 11401 } 11402 11403 abstract void handleStartCopy() throws RemoteException; 11404 abstract void handleServiceError(); 11405 abstract void handleReturnCode(); 11406 } 11407 11408 class MeasureParams extends HandlerParams { 11409 private final PackageStats mStats; 11410 private boolean mSuccess; 11411 11412 private final IPackageStatsObserver mObserver; 11413 11414 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11415 super(new UserHandle(stats.userHandle)); 11416 mObserver = observer; 11417 mStats = stats; 11418 } 11419 11420 @Override 11421 public String toString() { 11422 return "MeasureParams{" 11423 + Integer.toHexString(System.identityHashCode(this)) 11424 + " " + mStats.packageName + "}"; 11425 } 11426 11427 @Override 11428 void handleStartCopy() throws RemoteException { 11429 synchronized (mInstallLock) { 11430 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11431 } 11432 11433 if (mSuccess) { 11434 final boolean mounted; 11435 if (Environment.isExternalStorageEmulated()) { 11436 mounted = true; 11437 } else { 11438 final String status = Environment.getExternalStorageState(); 11439 mounted = (Environment.MEDIA_MOUNTED.equals(status) 11440 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 11441 } 11442 11443 if (mounted) { 11444 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 11445 11446 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 11447 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 11448 11449 mStats.externalDataSize = calculateDirectorySize(mContainerService, 11450 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 11451 11452 // Always subtract cache size, since it's a subdirectory 11453 mStats.externalDataSize -= mStats.externalCacheSize; 11454 11455 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 11456 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 11457 11458 mStats.externalObbSize = calculateDirectorySize(mContainerService, 11459 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 11460 } 11461 } 11462 } 11463 11464 @Override 11465 void handleReturnCode() { 11466 if (mObserver != null) { 11467 try { 11468 mObserver.onGetStatsCompleted(mStats, mSuccess); 11469 } catch (RemoteException e) { 11470 Slog.i(TAG, "Observer no longer exists."); 11471 } 11472 } 11473 } 11474 11475 @Override 11476 void handleServiceError() { 11477 Slog.e(TAG, "Could not measure application " + mStats.packageName 11478 + " external storage"); 11479 } 11480 } 11481 11482 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 11483 throws RemoteException { 11484 long result = 0; 11485 for (File path : paths) { 11486 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 11487 } 11488 return result; 11489 } 11490 11491 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 11492 for (File path : paths) { 11493 try { 11494 mcs.clearDirectory(path.getAbsolutePath()); 11495 } catch (RemoteException e) { 11496 } 11497 } 11498 } 11499 11500 static class OriginInfo { 11501 /** 11502 * Location where install is coming from, before it has been 11503 * copied/renamed into place. This could be a single monolithic APK 11504 * file, or a cluster directory. This location may be untrusted. 11505 */ 11506 final File file; 11507 final String cid; 11508 11509 /** 11510 * Flag indicating that {@link #file} or {@link #cid} has already been 11511 * staged, meaning downstream users don't need to defensively copy the 11512 * contents. 11513 */ 11514 final boolean staged; 11515 11516 /** 11517 * Flag indicating that {@link #file} or {@link #cid} is an already 11518 * installed app that is being moved. 11519 */ 11520 final boolean existing; 11521 11522 final String resolvedPath; 11523 final File resolvedFile; 11524 11525 static OriginInfo fromNothing() { 11526 return new OriginInfo(null, null, false, false); 11527 } 11528 11529 static OriginInfo fromUntrustedFile(File file) { 11530 return new OriginInfo(file, null, false, false); 11531 } 11532 11533 static OriginInfo fromExistingFile(File file) { 11534 return new OriginInfo(file, null, false, true); 11535 } 11536 11537 static OriginInfo fromStagedFile(File file) { 11538 return new OriginInfo(file, null, true, false); 11539 } 11540 11541 static OriginInfo fromStagedContainer(String cid) { 11542 return new OriginInfo(null, cid, true, false); 11543 } 11544 11545 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 11546 this.file = file; 11547 this.cid = cid; 11548 this.staged = staged; 11549 this.existing = existing; 11550 11551 if (cid != null) { 11552 resolvedPath = PackageHelper.getSdDir(cid); 11553 resolvedFile = new File(resolvedPath); 11554 } else if (file != null) { 11555 resolvedPath = file.getAbsolutePath(); 11556 resolvedFile = file; 11557 } else { 11558 resolvedPath = null; 11559 resolvedFile = null; 11560 } 11561 } 11562 } 11563 11564 static class MoveInfo { 11565 final int moveId; 11566 final String fromUuid; 11567 final String toUuid; 11568 final String packageName; 11569 final String dataAppName; 11570 final int appId; 11571 final String seinfo; 11572 final int targetSdkVersion; 11573 11574 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 11575 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 11576 this.moveId = moveId; 11577 this.fromUuid = fromUuid; 11578 this.toUuid = toUuid; 11579 this.packageName = packageName; 11580 this.dataAppName = dataAppName; 11581 this.appId = appId; 11582 this.seinfo = seinfo; 11583 this.targetSdkVersion = targetSdkVersion; 11584 } 11585 } 11586 11587 static class VerificationInfo { 11588 /** A constant used to indicate that a uid value is not present. */ 11589 public static final int NO_UID = -1; 11590 11591 /** URI referencing where the package was downloaded from. */ 11592 final Uri originatingUri; 11593 11594 /** HTTP referrer URI associated with the originatingURI. */ 11595 final Uri referrer; 11596 11597 /** UID of the application that the install request originated from. */ 11598 final int originatingUid; 11599 11600 /** UID of application requesting the install */ 11601 final int installerUid; 11602 11603 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 11604 this.originatingUri = originatingUri; 11605 this.referrer = referrer; 11606 this.originatingUid = originatingUid; 11607 this.installerUid = installerUid; 11608 } 11609 } 11610 11611 class InstallParams extends HandlerParams { 11612 final OriginInfo origin; 11613 final MoveInfo move; 11614 final IPackageInstallObserver2 observer; 11615 int installFlags; 11616 final String installerPackageName; 11617 final String volumeUuid; 11618 private InstallArgs mArgs; 11619 private int mRet; 11620 final String packageAbiOverride; 11621 final String[] grantedRuntimePermissions; 11622 final VerificationInfo verificationInfo; 11623 11624 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 11625 int installFlags, String installerPackageName, String volumeUuid, 11626 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 11627 String[] grantedPermissions) { 11628 super(user); 11629 this.origin = origin; 11630 this.move = move; 11631 this.observer = observer; 11632 this.installFlags = installFlags; 11633 this.installerPackageName = installerPackageName; 11634 this.volumeUuid = volumeUuid; 11635 this.verificationInfo = verificationInfo; 11636 this.packageAbiOverride = packageAbiOverride; 11637 this.grantedRuntimePermissions = grantedPermissions; 11638 } 11639 11640 @Override 11641 public String toString() { 11642 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 11643 + " file=" + origin.file + " cid=" + origin.cid + "}"; 11644 } 11645 11646 private int installLocationPolicy(PackageInfoLite pkgLite) { 11647 String packageName = pkgLite.packageName; 11648 int installLocation = pkgLite.installLocation; 11649 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11650 // reader 11651 synchronized (mPackages) { 11652 // Currently installed package which the new package is attempting to replace or 11653 // null if no such package is installed. 11654 PackageParser.Package installedPkg = mPackages.get(packageName); 11655 // Package which currently owns the data which the new package will own if installed. 11656 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 11657 // will be null whereas dataOwnerPkg will contain information about the package 11658 // which was uninstalled while keeping its data. 11659 PackageParser.Package dataOwnerPkg = installedPkg; 11660 if (dataOwnerPkg == null) { 11661 PackageSetting ps = mSettings.mPackages.get(packageName); 11662 if (ps != null) { 11663 dataOwnerPkg = ps.pkg; 11664 } 11665 } 11666 11667 if (dataOwnerPkg != null) { 11668 // If installed, the package will get access to data left on the device by its 11669 // predecessor. As a security measure, this is permited only if this is not a 11670 // version downgrade or if the predecessor package is marked as debuggable and 11671 // a downgrade is explicitly requested. 11672 if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) 11673 || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) { 11674 try { 11675 checkDowngrade(dataOwnerPkg, pkgLite); 11676 } catch (PackageManagerException e) { 11677 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 11678 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 11679 } 11680 } 11681 } 11682 11683 if (installedPkg != null) { 11684 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11685 // Check for updated system application. 11686 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11687 if (onSd) { 11688 Slog.w(TAG, "Cannot install update to system app on sdcard"); 11689 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 11690 } 11691 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11692 } else { 11693 if (onSd) { 11694 // Install flag overrides everything. 11695 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11696 } 11697 // If current upgrade specifies particular preference 11698 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 11699 // Application explicitly specified internal. 11700 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11701 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 11702 // App explictly prefers external. Let policy decide 11703 } else { 11704 // Prefer previous location 11705 if (isExternal(installedPkg)) { 11706 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11707 } 11708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 11709 } 11710 } 11711 } else { 11712 // Invalid install. Return error code 11713 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 11714 } 11715 } 11716 } 11717 // All the special cases have been taken care of. 11718 // Return result based on recommended install location. 11719 if (onSd) { 11720 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 11721 } 11722 return pkgLite.recommendedInstallLocation; 11723 } 11724 11725 /* 11726 * Invoke remote method to get package information and install 11727 * location values. Override install location based on default 11728 * policy if needed and then create install arguments based 11729 * on the install location. 11730 */ 11731 public void handleStartCopy() throws RemoteException { 11732 int ret = PackageManager.INSTALL_SUCCEEDED; 11733 11734 // If we're already staged, we've firmly committed to an install location 11735 if (origin.staged) { 11736 if (origin.file != null) { 11737 installFlags |= PackageManager.INSTALL_INTERNAL; 11738 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11739 } else if (origin.cid != null) { 11740 installFlags |= PackageManager.INSTALL_EXTERNAL; 11741 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11742 } else { 11743 throw new IllegalStateException("Invalid stage location"); 11744 } 11745 } 11746 11747 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 11748 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 11749 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 11750 PackageInfoLite pkgLite = null; 11751 11752 if (onInt && onSd) { 11753 // Check if both bits are set. 11754 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 11755 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11756 } else if (onSd && ephemeral) { 11757 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 11758 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11759 } else { 11760 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 11761 packageAbiOverride); 11762 11763 if (DEBUG_EPHEMERAL && ephemeral) { 11764 Slog.v(TAG, "pkgLite for install: " + pkgLite); 11765 } 11766 11767 /* 11768 * If we have too little free space, try to free cache 11769 * before giving up. 11770 */ 11771 if (!origin.staged && pkgLite.recommendedInstallLocation 11772 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11773 // TODO: focus freeing disk space on the target device 11774 final StorageManager storage = StorageManager.from(mContext); 11775 final long lowThreshold = storage.getStorageLowBytes( 11776 Environment.getDataDirectory()); 11777 11778 final long sizeBytes = mContainerService.calculateInstalledSize( 11779 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 11780 11781 try { 11782 mInstaller.freeCache(null, sizeBytes + lowThreshold); 11783 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 11784 installFlags, packageAbiOverride); 11785 } catch (InstallerException e) { 11786 Slog.w(TAG, "Failed to free cache", e); 11787 } 11788 11789 /* 11790 * The cache free must have deleted the file we 11791 * downloaded to install. 11792 * 11793 * TODO: fix the "freeCache" call to not delete 11794 * the file we care about. 11795 */ 11796 if (pkgLite.recommendedInstallLocation 11797 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11798 pkgLite.recommendedInstallLocation 11799 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 11800 } 11801 } 11802 } 11803 11804 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11805 int loc = pkgLite.recommendedInstallLocation; 11806 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 11807 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 11808 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 11809 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 11810 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 11811 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 11812 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 11813 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 11814 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 11815 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 11816 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 11817 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 11818 } else { 11819 // Override with defaults if needed. 11820 loc = installLocationPolicy(pkgLite); 11821 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 11822 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 11823 } else if (!onSd && !onInt) { 11824 // Override install location with flags 11825 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 11826 // Set the flag to install on external media. 11827 installFlags |= PackageManager.INSTALL_EXTERNAL; 11828 installFlags &= ~PackageManager.INSTALL_INTERNAL; 11829 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 11830 if (DEBUG_EPHEMERAL) { 11831 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 11832 } 11833 installFlags |= PackageManager.INSTALL_EPHEMERAL; 11834 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 11835 |PackageManager.INSTALL_INTERNAL); 11836 } else { 11837 // Make sure the flag for installing on external 11838 // media is unset 11839 installFlags |= PackageManager.INSTALL_INTERNAL; 11840 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 11841 } 11842 } 11843 } 11844 } 11845 11846 final InstallArgs args = createInstallArgs(this); 11847 mArgs = args; 11848 11849 if (ret == PackageManager.INSTALL_SUCCEEDED) { 11850 // TODO: http://b/22976637 11851 // Apps installed for "all" users use the device owner to verify the app 11852 UserHandle verifierUser = getUser(); 11853 if (verifierUser == UserHandle.ALL) { 11854 verifierUser = UserHandle.SYSTEM; 11855 } 11856 11857 /* 11858 * Determine if we have any installed package verifiers. If we 11859 * do, then we'll defer to them to verify the packages. 11860 */ 11861 final int requiredUid = mRequiredVerifierPackage == null ? -1 11862 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 11863 verifierUser.getIdentifier()); 11864 if (!origin.existing && requiredUid != -1 11865 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 11866 final Intent verification = new Intent( 11867 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 11868 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11869 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 11870 PACKAGE_MIME_TYPE); 11871 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11872 11873 // Query all live verifiers based on current user state 11874 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 11875 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 11876 11877 if (DEBUG_VERIFY) { 11878 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 11879 + verification.toString() + " with " + pkgLite.verifiers.length 11880 + " optional verifiers"); 11881 } 11882 11883 final int verificationId = mPendingVerificationToken++; 11884 11885 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11886 11887 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 11888 installerPackageName); 11889 11890 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 11891 installFlags); 11892 11893 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 11894 pkgLite.packageName); 11895 11896 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 11897 pkgLite.versionCode); 11898 11899 if (verificationInfo != null) { 11900 if (verificationInfo.originatingUri != null) { 11901 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 11902 verificationInfo.originatingUri); 11903 } 11904 if (verificationInfo.referrer != null) { 11905 verification.putExtra(Intent.EXTRA_REFERRER, 11906 verificationInfo.referrer); 11907 } 11908 if (verificationInfo.originatingUid >= 0) { 11909 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 11910 verificationInfo.originatingUid); 11911 } 11912 if (verificationInfo.installerUid >= 0) { 11913 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 11914 verificationInfo.installerUid); 11915 } 11916 } 11917 11918 final PackageVerificationState verificationState = new PackageVerificationState( 11919 requiredUid, args); 11920 11921 mPendingVerification.append(verificationId, verificationState); 11922 11923 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 11924 receivers, verificationState); 11925 11926 /* 11927 * If any sufficient verifiers were listed in the package 11928 * manifest, attempt to ask them. 11929 */ 11930 if (sufficientVerifiers != null) { 11931 final int N = sufficientVerifiers.size(); 11932 if (N == 0) { 11933 Slog.i(TAG, "Additional verifiers required, but none installed."); 11934 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 11935 } else { 11936 for (int i = 0; i < N; i++) { 11937 final ComponentName verifierComponent = sufficientVerifiers.get(i); 11938 11939 final Intent sufficientIntent = new Intent(verification); 11940 sufficientIntent.setComponent(verifierComponent); 11941 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 11942 } 11943 } 11944 } 11945 11946 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 11947 mRequiredVerifierPackage, receivers); 11948 if (ret == PackageManager.INSTALL_SUCCEEDED 11949 && mRequiredVerifierPackage != null) { 11950 Trace.asyncTraceBegin( 11951 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 11952 /* 11953 * Send the intent to the required verification agent, 11954 * but only start the verification timeout after the 11955 * target BroadcastReceivers have run. 11956 */ 11957 verification.setComponent(requiredVerifierComponent); 11958 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 11959 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11960 new BroadcastReceiver() { 11961 @Override 11962 public void onReceive(Context context, Intent intent) { 11963 final Message msg = mHandler 11964 .obtainMessage(CHECK_PENDING_VERIFICATION); 11965 msg.arg1 = verificationId; 11966 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 11967 } 11968 }, null, 0, null, null); 11969 11970 /* 11971 * We don't want the copy to proceed until verification 11972 * succeeds, so null out this field. 11973 */ 11974 mArgs = null; 11975 } 11976 } else { 11977 /* 11978 * No package verification is enabled, so immediately start 11979 * the remote call to initiate copy using temporary file. 11980 */ 11981 ret = args.copyApk(mContainerService, true); 11982 } 11983 } 11984 11985 mRet = ret; 11986 } 11987 11988 @Override 11989 void handleReturnCode() { 11990 // If mArgs is null, then MCS couldn't be reached. When it 11991 // reconnects, it will try again to install. At that point, this 11992 // will succeed. 11993 if (mArgs != null) { 11994 processPendingInstall(mArgs, mRet); 11995 } 11996 } 11997 11998 @Override 11999 void handleServiceError() { 12000 mArgs = createInstallArgs(this); 12001 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12002 } 12003 12004 public boolean isForwardLocked() { 12005 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12006 } 12007 } 12008 12009 /** 12010 * Used during creation of InstallArgs 12011 * 12012 * @param installFlags package installation flags 12013 * @return true if should be installed on external storage 12014 */ 12015 private static boolean installOnExternalAsec(int installFlags) { 12016 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12017 return false; 12018 } 12019 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12020 return true; 12021 } 12022 return false; 12023 } 12024 12025 /** 12026 * Used during creation of InstallArgs 12027 * 12028 * @param installFlags package installation flags 12029 * @return true if should be installed as forward locked 12030 */ 12031 private static boolean installForwardLocked(int installFlags) { 12032 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12033 } 12034 12035 private InstallArgs createInstallArgs(InstallParams params) { 12036 if (params.move != null) { 12037 return new MoveInstallArgs(params); 12038 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12039 return new AsecInstallArgs(params); 12040 } else { 12041 return new FileInstallArgs(params); 12042 } 12043 } 12044 12045 /** 12046 * Create args that describe an existing installed package. Typically used 12047 * when cleaning up old installs, or used as a move source. 12048 */ 12049 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12050 String resourcePath, String[] instructionSets) { 12051 final boolean isInAsec; 12052 if (installOnExternalAsec(installFlags)) { 12053 /* Apps on SD card are always in ASEC containers. */ 12054 isInAsec = true; 12055 } else if (installForwardLocked(installFlags) 12056 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12057 /* 12058 * Forward-locked apps are only in ASEC containers if they're the 12059 * new style 12060 */ 12061 isInAsec = true; 12062 } else { 12063 isInAsec = false; 12064 } 12065 12066 if (isInAsec) { 12067 return new AsecInstallArgs(codePath, instructionSets, 12068 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12069 } else { 12070 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12071 } 12072 } 12073 12074 static abstract class InstallArgs { 12075 /** @see InstallParams#origin */ 12076 final OriginInfo origin; 12077 /** @see InstallParams#move */ 12078 final MoveInfo move; 12079 12080 final IPackageInstallObserver2 observer; 12081 // Always refers to PackageManager flags only 12082 final int installFlags; 12083 final String installerPackageName; 12084 final String volumeUuid; 12085 final UserHandle user; 12086 final String abiOverride; 12087 final String[] installGrantPermissions; 12088 /** If non-null, drop an async trace when the install completes */ 12089 final String traceMethod; 12090 final int traceCookie; 12091 12092 // The list of instruction sets supported by this app. This is currently 12093 // only used during the rmdex() phase to clean up resources. We can get rid of this 12094 // if we move dex files under the common app path. 12095 /* nullable */ String[] instructionSets; 12096 12097 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12098 int installFlags, String installerPackageName, String volumeUuid, 12099 UserHandle user, String[] instructionSets, 12100 String abiOverride, String[] installGrantPermissions, 12101 String traceMethod, int traceCookie) { 12102 this.origin = origin; 12103 this.move = move; 12104 this.installFlags = installFlags; 12105 this.observer = observer; 12106 this.installerPackageName = installerPackageName; 12107 this.volumeUuid = volumeUuid; 12108 this.user = user; 12109 this.instructionSets = instructionSets; 12110 this.abiOverride = abiOverride; 12111 this.installGrantPermissions = installGrantPermissions; 12112 this.traceMethod = traceMethod; 12113 this.traceCookie = traceCookie; 12114 } 12115 12116 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12117 abstract int doPreInstall(int status); 12118 12119 /** 12120 * Rename package into final resting place. All paths on the given 12121 * scanned package should be updated to reflect the rename. 12122 */ 12123 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12124 abstract int doPostInstall(int status, int uid); 12125 12126 /** @see PackageSettingBase#codePathString */ 12127 abstract String getCodePath(); 12128 /** @see PackageSettingBase#resourcePathString */ 12129 abstract String getResourcePath(); 12130 12131 // Need installer lock especially for dex file removal. 12132 abstract void cleanUpResourcesLI(); 12133 abstract boolean doPostDeleteLI(boolean delete); 12134 12135 /** 12136 * Called before the source arguments are copied. This is used mostly 12137 * for MoveParams when it needs to read the source file to put it in the 12138 * destination. 12139 */ 12140 int doPreCopy() { 12141 return PackageManager.INSTALL_SUCCEEDED; 12142 } 12143 12144 /** 12145 * Called after the source arguments are copied. This is used mostly for 12146 * MoveParams when it needs to read the source file to put it in the 12147 * destination. 12148 * 12149 * @return 12150 */ 12151 int doPostCopy(int uid) { 12152 return PackageManager.INSTALL_SUCCEEDED; 12153 } 12154 12155 protected boolean isFwdLocked() { 12156 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12157 } 12158 12159 protected boolean isExternalAsec() { 12160 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12161 } 12162 12163 protected boolean isEphemeral() { 12164 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12165 } 12166 12167 UserHandle getUser() { 12168 return user; 12169 } 12170 } 12171 12172 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12173 if (!allCodePaths.isEmpty()) { 12174 if (instructionSets == null) { 12175 throw new IllegalStateException("instructionSet == null"); 12176 } 12177 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12178 for (String codePath : allCodePaths) { 12179 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12180 try { 12181 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12182 } catch (InstallerException ignored) { 12183 } 12184 } 12185 } 12186 } 12187 } 12188 12189 /** 12190 * Logic to handle installation of non-ASEC applications, including copying 12191 * and renaming logic. 12192 */ 12193 class FileInstallArgs extends InstallArgs { 12194 private File codeFile; 12195 private File resourceFile; 12196 12197 // Example topology: 12198 // /data/app/com.example/base.apk 12199 // /data/app/com.example/split_foo.apk 12200 // /data/app/com.example/lib/arm/libfoo.so 12201 // /data/app/com.example/lib/arm64/libfoo.so 12202 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12203 12204 /** New install */ 12205 FileInstallArgs(InstallParams params) { 12206 super(params.origin, params.move, params.observer, params.installFlags, 12207 params.installerPackageName, params.volumeUuid, 12208 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12209 params.grantedRuntimePermissions, 12210 params.traceMethod, params.traceCookie); 12211 if (isFwdLocked()) { 12212 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12213 } 12214 } 12215 12216 /** Existing install */ 12217 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12218 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12219 null, null, null, 0); 12220 this.codeFile = (codePath != null) ? new File(codePath) : null; 12221 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12222 } 12223 12224 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12226 try { 12227 return doCopyApk(imcs, temp); 12228 } finally { 12229 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12230 } 12231 } 12232 12233 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12234 if (origin.staged) { 12235 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12236 codeFile = origin.file; 12237 resourceFile = origin.file; 12238 return PackageManager.INSTALL_SUCCEEDED; 12239 } 12240 12241 try { 12242 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12243 final File tempDir = 12244 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12245 codeFile = tempDir; 12246 resourceFile = tempDir; 12247 } catch (IOException e) { 12248 Slog.w(TAG, "Failed to create copy file: " + e); 12249 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12250 } 12251 12252 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12253 @Override 12254 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12255 if (!FileUtils.isValidExtFilename(name)) { 12256 throw new IllegalArgumentException("Invalid filename: " + name); 12257 } 12258 try { 12259 final File file = new File(codeFile, name); 12260 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12261 O_RDWR | O_CREAT, 0644); 12262 Os.chmod(file.getAbsolutePath(), 0644); 12263 return new ParcelFileDescriptor(fd); 12264 } catch (ErrnoException e) { 12265 throw new RemoteException("Failed to open: " + e.getMessage()); 12266 } 12267 } 12268 }; 12269 12270 int ret = PackageManager.INSTALL_SUCCEEDED; 12271 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12272 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12273 Slog.e(TAG, "Failed to copy package"); 12274 return ret; 12275 } 12276 12277 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12278 NativeLibraryHelper.Handle handle = null; 12279 try { 12280 handle = NativeLibraryHelper.Handle.create(codeFile); 12281 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12282 abiOverride); 12283 } catch (IOException e) { 12284 Slog.e(TAG, "Copying native libraries failed", e); 12285 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12286 } finally { 12287 IoUtils.closeQuietly(handle); 12288 } 12289 12290 return ret; 12291 } 12292 12293 int doPreInstall(int status) { 12294 if (status != PackageManager.INSTALL_SUCCEEDED) { 12295 cleanUp(); 12296 } 12297 return status; 12298 } 12299 12300 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12301 if (status != PackageManager.INSTALL_SUCCEEDED) { 12302 cleanUp(); 12303 return false; 12304 } 12305 12306 final File targetDir = codeFile.getParentFile(); 12307 final File beforeCodeFile = codeFile; 12308 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12309 12310 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12311 try { 12312 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12313 } catch (ErrnoException e) { 12314 Slog.w(TAG, "Failed to rename", e); 12315 return false; 12316 } 12317 12318 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12319 Slog.w(TAG, "Failed to restorecon"); 12320 return false; 12321 } 12322 12323 // Reflect the rename internally 12324 codeFile = afterCodeFile; 12325 resourceFile = afterCodeFile; 12326 12327 // Reflect the rename in scanned details 12328 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12329 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12330 afterCodeFile, pkg.baseCodePath)); 12331 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12332 afterCodeFile, pkg.splitCodePaths)); 12333 12334 // Reflect the rename in app info 12335 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12336 pkg.setApplicationInfoCodePath(pkg.codePath); 12337 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12338 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12339 pkg.setApplicationInfoResourcePath(pkg.codePath); 12340 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12341 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12342 12343 return true; 12344 } 12345 12346 int doPostInstall(int status, int uid) { 12347 if (status != PackageManager.INSTALL_SUCCEEDED) { 12348 cleanUp(); 12349 } 12350 return status; 12351 } 12352 12353 @Override 12354 String getCodePath() { 12355 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12356 } 12357 12358 @Override 12359 String getResourcePath() { 12360 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12361 } 12362 12363 private boolean cleanUp() { 12364 if (codeFile == null || !codeFile.exists()) { 12365 return false; 12366 } 12367 12368 removeCodePathLI(codeFile); 12369 12370 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12371 resourceFile.delete(); 12372 } 12373 12374 return true; 12375 } 12376 12377 void cleanUpResourcesLI() { 12378 // Try enumerating all code paths before deleting 12379 List<String> allCodePaths = Collections.EMPTY_LIST; 12380 if (codeFile != null && codeFile.exists()) { 12381 try { 12382 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12383 allCodePaths = pkg.getAllCodePaths(); 12384 } catch (PackageParserException e) { 12385 // Ignored; we tried our best 12386 } 12387 } 12388 12389 cleanUp(); 12390 removeDexFiles(allCodePaths, instructionSets); 12391 } 12392 12393 boolean doPostDeleteLI(boolean delete) { 12394 // XXX err, shouldn't we respect the delete flag? 12395 cleanUpResourcesLI(); 12396 return true; 12397 } 12398 } 12399 12400 private boolean isAsecExternal(String cid) { 12401 final String asecPath = PackageHelper.getSdFilesystem(cid); 12402 return !asecPath.startsWith(mAsecInternalPath); 12403 } 12404 12405 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12406 PackageManagerException { 12407 if (copyRet < 0) { 12408 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12409 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12410 throw new PackageManagerException(copyRet, message); 12411 } 12412 } 12413 } 12414 12415 /** 12416 * Extract the MountService "container ID" from the full code path of an 12417 * .apk. 12418 */ 12419 static String cidFromCodePath(String fullCodePath) { 12420 int eidx = fullCodePath.lastIndexOf("/"); 12421 String subStr1 = fullCodePath.substring(0, eidx); 12422 int sidx = subStr1.lastIndexOf("/"); 12423 return subStr1.substring(sidx+1, eidx); 12424 } 12425 12426 /** 12427 * Logic to handle installation of ASEC applications, including copying and 12428 * renaming logic. 12429 */ 12430 class AsecInstallArgs extends InstallArgs { 12431 static final String RES_FILE_NAME = "pkg.apk"; 12432 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 12433 12434 String cid; 12435 String packagePath; 12436 String resourcePath; 12437 12438 /** New install */ 12439 AsecInstallArgs(InstallParams params) { 12440 super(params.origin, params.move, params.observer, params.installFlags, 12441 params.installerPackageName, params.volumeUuid, 12442 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12443 params.grantedRuntimePermissions, 12444 params.traceMethod, params.traceCookie); 12445 } 12446 12447 /** Existing install */ 12448 AsecInstallArgs(String fullCodePath, String[] instructionSets, 12449 boolean isExternal, boolean isForwardLocked) { 12450 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 12451 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12452 instructionSets, null, null, null, 0); 12453 // Hackily pretend we're still looking at a full code path 12454 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 12455 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 12456 } 12457 12458 // Extract cid from fullCodePath 12459 int eidx = fullCodePath.lastIndexOf("/"); 12460 String subStr1 = fullCodePath.substring(0, eidx); 12461 int sidx = subStr1.lastIndexOf("/"); 12462 cid = subStr1.substring(sidx+1, eidx); 12463 setMountPath(subStr1); 12464 } 12465 12466 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 12467 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 12468 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 12469 instructionSets, null, null, null, 0); 12470 this.cid = cid; 12471 setMountPath(PackageHelper.getSdDir(cid)); 12472 } 12473 12474 void createCopyFile() { 12475 cid = mInstallerService.allocateExternalStageCidLegacy(); 12476 } 12477 12478 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12479 if (origin.staged && origin.cid != null) { 12480 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 12481 cid = origin.cid; 12482 setMountPath(PackageHelper.getSdDir(cid)); 12483 return PackageManager.INSTALL_SUCCEEDED; 12484 } 12485 12486 if (temp) { 12487 createCopyFile(); 12488 } else { 12489 /* 12490 * Pre-emptively destroy the container since it's destroyed if 12491 * copying fails due to it existing anyway. 12492 */ 12493 PackageHelper.destroySdDir(cid); 12494 } 12495 12496 final String newMountPath = imcs.copyPackageToContainer( 12497 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 12498 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 12499 12500 if (newMountPath != null) { 12501 setMountPath(newMountPath); 12502 return PackageManager.INSTALL_SUCCEEDED; 12503 } else { 12504 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12505 } 12506 } 12507 12508 @Override 12509 String getCodePath() { 12510 return packagePath; 12511 } 12512 12513 @Override 12514 String getResourcePath() { 12515 return resourcePath; 12516 } 12517 12518 int doPreInstall(int status) { 12519 if (status != PackageManager.INSTALL_SUCCEEDED) { 12520 // Destroy container 12521 PackageHelper.destroySdDir(cid); 12522 } else { 12523 boolean mounted = PackageHelper.isContainerMounted(cid); 12524 if (!mounted) { 12525 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 12526 Process.SYSTEM_UID); 12527 if (newMountPath != null) { 12528 setMountPath(newMountPath); 12529 } else { 12530 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12531 } 12532 } 12533 } 12534 return status; 12535 } 12536 12537 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12538 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 12539 String newMountPath = null; 12540 if (PackageHelper.isContainerMounted(cid)) { 12541 // Unmount the container 12542 if (!PackageHelper.unMountSdDir(cid)) { 12543 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 12544 return false; 12545 } 12546 } 12547 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12548 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 12549 " which might be stale. Will try to clean up."); 12550 // Clean up the stale container and proceed to recreate. 12551 if (!PackageHelper.destroySdDir(newCacheId)) { 12552 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 12553 return false; 12554 } 12555 // Successfully cleaned up stale container. Try to rename again. 12556 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 12557 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 12558 + " inspite of cleaning it up."); 12559 return false; 12560 } 12561 } 12562 if (!PackageHelper.isContainerMounted(newCacheId)) { 12563 Slog.w(TAG, "Mounting container " + newCacheId); 12564 newMountPath = PackageHelper.mountSdDir(newCacheId, 12565 getEncryptKey(), Process.SYSTEM_UID); 12566 } else { 12567 newMountPath = PackageHelper.getSdDir(newCacheId); 12568 } 12569 if (newMountPath == null) { 12570 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 12571 return false; 12572 } 12573 Log.i(TAG, "Succesfully renamed " + cid + 12574 " to " + newCacheId + 12575 " at new path: " + newMountPath); 12576 cid = newCacheId; 12577 12578 final File beforeCodeFile = new File(packagePath); 12579 setMountPath(newMountPath); 12580 final File afterCodeFile = new File(packagePath); 12581 12582 // Reflect the rename in scanned details 12583 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12584 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12585 afterCodeFile, pkg.baseCodePath)); 12586 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12587 afterCodeFile, pkg.splitCodePaths)); 12588 12589 // Reflect the rename in app info 12590 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12591 pkg.setApplicationInfoCodePath(pkg.codePath); 12592 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12593 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12594 pkg.setApplicationInfoResourcePath(pkg.codePath); 12595 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12596 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12597 12598 return true; 12599 } 12600 12601 private void setMountPath(String mountPath) { 12602 final File mountFile = new File(mountPath); 12603 12604 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 12605 if (monolithicFile.exists()) { 12606 packagePath = monolithicFile.getAbsolutePath(); 12607 if (isFwdLocked()) { 12608 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 12609 } else { 12610 resourcePath = packagePath; 12611 } 12612 } else { 12613 packagePath = mountFile.getAbsolutePath(); 12614 resourcePath = packagePath; 12615 } 12616 } 12617 12618 int doPostInstall(int status, int uid) { 12619 if (status != PackageManager.INSTALL_SUCCEEDED) { 12620 cleanUp(); 12621 } else { 12622 final int groupOwner; 12623 final String protectedFile; 12624 if (isFwdLocked()) { 12625 groupOwner = UserHandle.getSharedAppGid(uid); 12626 protectedFile = RES_FILE_NAME; 12627 } else { 12628 groupOwner = -1; 12629 protectedFile = null; 12630 } 12631 12632 if (uid < Process.FIRST_APPLICATION_UID 12633 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 12634 Slog.e(TAG, "Failed to finalize " + cid); 12635 PackageHelper.destroySdDir(cid); 12636 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12637 } 12638 12639 boolean mounted = PackageHelper.isContainerMounted(cid); 12640 if (!mounted) { 12641 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 12642 } 12643 } 12644 return status; 12645 } 12646 12647 private void cleanUp() { 12648 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 12649 12650 // Destroy secure container 12651 PackageHelper.destroySdDir(cid); 12652 } 12653 12654 private List<String> getAllCodePaths() { 12655 final File codeFile = new File(getCodePath()); 12656 if (codeFile != null && codeFile.exists()) { 12657 try { 12658 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12659 return pkg.getAllCodePaths(); 12660 } catch (PackageParserException e) { 12661 // Ignored; we tried our best 12662 } 12663 } 12664 return Collections.EMPTY_LIST; 12665 } 12666 12667 void cleanUpResourcesLI() { 12668 // Enumerate all code paths before deleting 12669 cleanUpResourcesLI(getAllCodePaths()); 12670 } 12671 12672 private void cleanUpResourcesLI(List<String> allCodePaths) { 12673 cleanUp(); 12674 removeDexFiles(allCodePaths, instructionSets); 12675 } 12676 12677 String getPackageName() { 12678 return getAsecPackageName(cid); 12679 } 12680 12681 boolean doPostDeleteLI(boolean delete) { 12682 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 12683 final List<String> allCodePaths = getAllCodePaths(); 12684 boolean mounted = PackageHelper.isContainerMounted(cid); 12685 if (mounted) { 12686 // Unmount first 12687 if (PackageHelper.unMountSdDir(cid)) { 12688 mounted = false; 12689 } 12690 } 12691 if (!mounted && delete) { 12692 cleanUpResourcesLI(allCodePaths); 12693 } 12694 return !mounted; 12695 } 12696 12697 @Override 12698 int doPreCopy() { 12699 if (isFwdLocked()) { 12700 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 12701 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 12702 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12703 } 12704 } 12705 12706 return PackageManager.INSTALL_SUCCEEDED; 12707 } 12708 12709 @Override 12710 int doPostCopy(int uid) { 12711 if (isFwdLocked()) { 12712 if (uid < Process.FIRST_APPLICATION_UID 12713 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 12714 RES_FILE_NAME)) { 12715 Slog.e(TAG, "Failed to finalize " + cid); 12716 PackageHelper.destroySdDir(cid); 12717 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12718 } 12719 } 12720 12721 return PackageManager.INSTALL_SUCCEEDED; 12722 } 12723 } 12724 12725 /** 12726 * Logic to handle movement of existing installed applications. 12727 */ 12728 class MoveInstallArgs extends InstallArgs { 12729 private File codeFile; 12730 private File resourceFile; 12731 12732 /** New install */ 12733 MoveInstallArgs(InstallParams params) { 12734 super(params.origin, params.move, params.observer, params.installFlags, 12735 params.installerPackageName, params.volumeUuid, 12736 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 12737 params.grantedRuntimePermissions, 12738 params.traceMethod, params.traceCookie); 12739 } 12740 12741 int copyApk(IMediaContainerService imcs, boolean temp) { 12742 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 12743 + move.fromUuid + " to " + move.toUuid); 12744 synchronized (mInstaller) { 12745 try { 12746 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 12747 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 12748 } catch (InstallerException e) { 12749 Slog.w(TAG, "Failed to move app", e); 12750 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12751 } 12752 } 12753 12754 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 12755 resourceFile = codeFile; 12756 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 12757 12758 return PackageManager.INSTALL_SUCCEEDED; 12759 } 12760 12761 int doPreInstall(int status) { 12762 if (status != PackageManager.INSTALL_SUCCEEDED) { 12763 cleanUp(move.toUuid); 12764 } 12765 return status; 12766 } 12767 12768 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12769 if (status != PackageManager.INSTALL_SUCCEEDED) { 12770 cleanUp(move.toUuid); 12771 return false; 12772 } 12773 12774 // Reflect the move in app info 12775 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12776 pkg.setApplicationInfoCodePath(pkg.codePath); 12777 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12778 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12779 pkg.setApplicationInfoResourcePath(pkg.codePath); 12780 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12781 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12782 12783 return true; 12784 } 12785 12786 int doPostInstall(int status, int uid) { 12787 if (status == PackageManager.INSTALL_SUCCEEDED) { 12788 cleanUp(move.fromUuid); 12789 } else { 12790 cleanUp(move.toUuid); 12791 } 12792 return status; 12793 } 12794 12795 @Override 12796 String getCodePath() { 12797 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12798 } 12799 12800 @Override 12801 String getResourcePath() { 12802 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12803 } 12804 12805 private boolean cleanUp(String volumeUuid) { 12806 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 12807 move.dataAppName); 12808 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 12809 synchronized (mInstallLock) { 12810 // Clean up both app data and code 12811 removeDataDirsLI(volumeUuid, move.packageName); 12812 removeCodePathLI(codeFile); 12813 } 12814 return true; 12815 } 12816 12817 void cleanUpResourcesLI() { 12818 throw new UnsupportedOperationException(); 12819 } 12820 12821 boolean doPostDeleteLI(boolean delete) { 12822 throw new UnsupportedOperationException(); 12823 } 12824 } 12825 12826 static String getAsecPackageName(String packageCid) { 12827 int idx = packageCid.lastIndexOf("-"); 12828 if (idx == -1) { 12829 return packageCid; 12830 } 12831 return packageCid.substring(0, idx); 12832 } 12833 12834 // Utility method used to create code paths based on package name and available index. 12835 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 12836 String idxStr = ""; 12837 int idx = 1; 12838 // Fall back to default value of idx=1 if prefix is not 12839 // part of oldCodePath 12840 if (oldCodePath != null) { 12841 String subStr = oldCodePath; 12842 // Drop the suffix right away 12843 if (suffix != null && subStr.endsWith(suffix)) { 12844 subStr = subStr.substring(0, subStr.length() - suffix.length()); 12845 } 12846 // If oldCodePath already contains prefix find out the 12847 // ending index to either increment or decrement. 12848 int sidx = subStr.lastIndexOf(prefix); 12849 if (sidx != -1) { 12850 subStr = subStr.substring(sidx + prefix.length()); 12851 if (subStr != null) { 12852 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 12853 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 12854 } 12855 try { 12856 idx = Integer.parseInt(subStr); 12857 if (idx <= 1) { 12858 idx++; 12859 } else { 12860 idx--; 12861 } 12862 } catch(NumberFormatException e) { 12863 } 12864 } 12865 } 12866 } 12867 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 12868 return prefix + idxStr; 12869 } 12870 12871 private File getNextCodePath(File targetDir, String packageName) { 12872 int suffix = 1; 12873 File result; 12874 do { 12875 result = new File(targetDir, packageName + "-" + suffix); 12876 suffix++; 12877 } while (result.exists()); 12878 return result; 12879 } 12880 12881 // Utility method that returns the relative package path with respect 12882 // to the installation directory. Like say for /data/data/com.test-1.apk 12883 // string com.test-1 is returned. 12884 static String deriveCodePathName(String codePath) { 12885 if (codePath == null) { 12886 return null; 12887 } 12888 final File codeFile = new File(codePath); 12889 final String name = codeFile.getName(); 12890 if (codeFile.isDirectory()) { 12891 return name; 12892 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 12893 final int lastDot = name.lastIndexOf('.'); 12894 return name.substring(0, lastDot); 12895 } else { 12896 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 12897 return null; 12898 } 12899 } 12900 12901 static class PackageInstalledInfo { 12902 String name; 12903 int uid; 12904 // The set of users that originally had this package installed. 12905 int[] origUsers; 12906 // The set of users that now have this package installed. 12907 int[] newUsers; 12908 PackageParser.Package pkg; 12909 int returnCode; 12910 String returnMsg; 12911 PackageRemovedInfo removedInfo; 12912 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 12913 12914 public void setError(int code, String msg) { 12915 setReturnCode(code); 12916 setReturnMessage(msg); 12917 Slog.w(TAG, msg); 12918 } 12919 12920 public void setError(String msg, PackageParserException e) { 12921 setReturnCode(e.error); 12922 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12923 Slog.w(TAG, msg, e); 12924 } 12925 12926 public void setError(String msg, PackageManagerException e) { 12927 returnCode = e.error; 12928 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 12929 Slog.w(TAG, msg, e); 12930 } 12931 12932 public void setReturnCode(int returnCode) { 12933 this.returnCode = returnCode; 12934 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12935 for (int i = 0; i < childCount; i++) { 12936 addedChildPackages.valueAt(i).returnCode = returnCode; 12937 } 12938 } 12939 12940 private void setReturnMessage(String returnMsg) { 12941 this.returnMsg = returnMsg; 12942 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 12943 for (int i = 0; i < childCount; i++) { 12944 addedChildPackages.valueAt(i).returnMsg = returnMsg; 12945 } 12946 } 12947 12948 // In some error cases we want to convey more info back to the observer 12949 String origPackage; 12950 String origPermission; 12951 } 12952 12953 /* 12954 * Install a non-existing package. 12955 */ 12956 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 12957 UserHandle user, String installerPackageName, String volumeUuid, 12958 PackageInstalledInfo res) { 12959 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 12960 12961 // Remember this for later, in case we need to rollback this install 12962 String pkgName = pkg.packageName; 12963 12964 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 12965 12966 synchronized(mPackages) { 12967 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 12968 // A package with the same name is already installed, though 12969 // it has been renamed to an older name. The package we 12970 // are trying to install should be installed as an update to 12971 // the existing one, but that has not been requested, so bail. 12972 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12973 + " without first uninstalling package running as " 12974 + mSettings.mRenamedPackages.get(pkgName)); 12975 return; 12976 } 12977 if (mPackages.containsKey(pkgName)) { 12978 // Don't allow installation over an existing package with the same name. 12979 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 12980 + " without first uninstalling."); 12981 return; 12982 } 12983 } 12984 12985 try { 12986 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 12987 System.currentTimeMillis(), user); 12988 12989 updateSettingsLI(newPackage, installerPackageName, null, res, user); 12990 12991 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12992 prepareAppDataAfterInstall(newPackage); 12993 12994 } else { 12995 // Remove package from internal structures, but keep around any 12996 // data that might have already existed 12997 deletePackageLI(pkgName, UserHandle.ALL, false, null, 12998 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 12999 } 13000 } catch (PackageManagerException e) { 13001 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13002 } 13003 13004 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13005 } 13006 13007 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13008 // Can't rotate keys during boot or if sharedUser. 13009 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13010 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13011 return false; 13012 } 13013 // app is using upgradeKeySets; make sure all are valid 13014 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13015 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13016 for (int i = 0; i < upgradeKeySets.length; i++) { 13017 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13018 Slog.wtf(TAG, "Package " 13019 + (oldPs.name != null ? oldPs.name : "<null>") 13020 + " contains upgrade-key-set reference to unknown key-set: " 13021 + upgradeKeySets[i] 13022 + " reverting to signatures check."); 13023 return false; 13024 } 13025 } 13026 return true; 13027 } 13028 13029 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13030 // Upgrade keysets are being used. Determine if new package has a superset of the 13031 // required keys. 13032 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13033 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13034 for (int i = 0; i < upgradeKeySets.length; i++) { 13035 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13036 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13037 return true; 13038 } 13039 } 13040 return false; 13041 } 13042 13043 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 13044 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13045 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13046 13047 final PackageParser.Package oldPackage; 13048 final String pkgName = pkg.packageName; 13049 final int[] allUsers; 13050 13051 // First find the old package info and check signatures 13052 synchronized(mPackages) { 13053 oldPackage = mPackages.get(pkgName); 13054 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13055 if (isEphemeral && !oldIsEphemeral) { 13056 // can't downgrade from full to ephemeral 13057 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13058 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13059 return; 13060 } 13061 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13062 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13063 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13064 if (!checkUpgradeKeySetLP(ps, pkg)) { 13065 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13066 "New package not signed by keys specified by upgrade-keysets: " 13067 + pkgName); 13068 return; 13069 } 13070 } else { 13071 // default to original signature matching 13072 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13073 != PackageManager.SIGNATURE_MATCH) { 13074 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13075 "New package has a different signature: " + pkgName); 13076 return; 13077 } 13078 } 13079 13080 // In case of rollback, remember per-user/profile install state 13081 allUsers = sUserManager.getUserIds(); 13082 } 13083 13084 // Update what is removed 13085 res.removedInfo = new PackageRemovedInfo(); 13086 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13087 res.removedInfo.removedPackage = oldPackage.packageName; 13088 res.removedInfo.isUpdate = true; 13089 final int childCount = (oldPackage.childPackages != null) 13090 ? oldPackage.childPackages.size() : 0; 13091 for (int i = 0; i < childCount; i++) { 13092 boolean childPackageUpdated = false; 13093 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13094 if (res.addedChildPackages != null) { 13095 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13096 if (childRes != null) { 13097 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13098 childRes.removedInfo.removedPackage = childPkg.packageName; 13099 childRes.removedInfo.isUpdate = true; 13100 childPackageUpdated = true; 13101 } 13102 } 13103 if (!childPackageUpdated) { 13104 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13105 childRemovedRes.removedPackage = childPkg.packageName; 13106 childRemovedRes.isUpdate = false; 13107 childRemovedRes.dataRemoved = true; 13108 synchronized (mPackages) { 13109 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13110 if (childPs != null) { 13111 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13112 } 13113 } 13114 if (res.removedInfo.removedChildPackages == null) { 13115 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13116 } 13117 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13118 } 13119 } 13120 13121 boolean sysPkg = (isSystemApp(oldPackage)); 13122 if (sysPkg) { 13123 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13124 user, allUsers, installerPackageName, res); 13125 } else { 13126 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 13127 user, allUsers, installerPackageName, res); 13128 } 13129 } 13130 13131 public List<String> getPreviousCodePaths(String packageName) { 13132 final PackageSetting ps = mSettings.mPackages.get(packageName); 13133 final List<String> result = new ArrayList<String>(); 13134 if (ps != null && ps.oldCodePaths != null) { 13135 result.addAll(ps.oldCodePaths); 13136 } 13137 return result; 13138 } 13139 13140 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 13141 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13142 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13143 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13144 + deletedPackage); 13145 13146 String pkgName = deletedPackage.packageName; 13147 boolean deletedPkg = true; 13148 boolean addedPkg = false; 13149 boolean updatedSettings = false; 13150 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13151 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13152 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13153 13154 final long origUpdateTime = (pkg.mExtras != null) 13155 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13156 13157 // First delete the existing package while retaining the data directory 13158 if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13159 res.removedInfo, true, pkg)) { 13160 // If the existing package wasn't successfully deleted 13161 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13162 deletedPkg = false; 13163 } else { 13164 // Successfully deleted the old package; proceed with replace. 13165 13166 // If deleted package lived in a container, give users a chance to 13167 // relinquish resources before killing. 13168 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13169 if (DEBUG_INSTALL) { 13170 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13171 } 13172 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13173 final ArrayList<String> pkgList = new ArrayList<String>(1); 13174 pkgList.add(deletedPackage.applicationInfo.packageName); 13175 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13176 } 13177 13178 deleteCodeCacheDirsLI(pkg); 13179 13180 try { 13181 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13182 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13183 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13184 13185 // Update the in-memory copy of the previous code paths. 13186 PackageSetting ps = mSettings.mPackages.get(pkgName); 13187 if (!killApp) { 13188 if (ps.oldCodePaths == null) { 13189 ps.oldCodePaths = new ArraySet<>(); 13190 } 13191 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13192 if (deletedPackage.splitCodePaths != null) { 13193 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13194 } 13195 } else { 13196 ps.oldCodePaths = null; 13197 } 13198 if (ps.childPackageNames != null) { 13199 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13200 final String childPkgName = ps.childPackageNames.get(i); 13201 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13202 childPs.oldCodePaths = ps.oldCodePaths; 13203 } 13204 } 13205 prepareAppDataAfterInstall(newPackage); 13206 addedPkg = true; 13207 } catch (PackageManagerException e) { 13208 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13209 } 13210 } 13211 13212 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13213 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13214 13215 // Revert all internal state mutations and added folders for the failed install 13216 if (addedPkg) { 13217 deletePackageLI(pkgName, null, true, allUsers, deleteFlags, 13218 res.removedInfo, true, null); 13219 } 13220 13221 // Restore the old package 13222 if (deletedPkg) { 13223 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13224 File restoreFile = new File(deletedPackage.codePath); 13225 // Parse old package 13226 boolean oldExternal = isExternal(deletedPackage); 13227 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13228 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13229 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13230 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13231 try { 13232 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13233 null); 13234 } catch (PackageManagerException e) { 13235 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13236 + e.getMessage()); 13237 return; 13238 } 13239 13240 synchronized (mPackages) { 13241 // Ensure the installer package name up to date 13242 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13243 13244 // Update permissions for restored package 13245 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13246 13247 mSettings.writeLPr(); 13248 } 13249 13250 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13251 } 13252 } else { 13253 synchronized (mPackages) { 13254 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13255 if (ps != null) { 13256 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13257 if (res.removedInfo.removedChildPackages != null) { 13258 final int childCount = res.removedInfo.removedChildPackages.size(); 13259 // Iterate in reverse as we may modify the collection 13260 for (int i = childCount - 1; i >= 0; i--) { 13261 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13262 if (res.addedChildPackages.containsKey(childPackageName)) { 13263 res.removedInfo.removedChildPackages.removeAt(i); 13264 } else { 13265 PackageRemovedInfo childInfo = res.removedInfo 13266 .removedChildPackages.valueAt(i); 13267 childInfo.removedForAllUsers = mPackages.get( 13268 childInfo.removedPackage) == null; 13269 } 13270 } 13271 } 13272 } 13273 } 13274 } 13275 } 13276 13277 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 13278 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13279 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13280 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13281 + ", old=" + deletedPackage); 13282 13283 final boolean disabledSystem; 13284 13285 // Set the system/privileged flags as needed 13286 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13287 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13288 != 0) { 13289 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13290 } 13291 13292 // Kill package processes including services, providers, etc. 13293 killPackage(deletedPackage, "replace sys pkg"); 13294 13295 // Remove existing system package 13296 removePackageLI(deletedPackage, true); 13297 13298 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13299 if (!disabledSystem) { 13300 // We didn't need to disable the .apk as a current system package, 13301 // which means we are replacing another update that is already 13302 // installed. We need to make sure to delete the older one's .apk. 13303 res.removedInfo.args = createInstallArgsForExisting(0, 13304 deletedPackage.applicationInfo.getCodePath(), 13305 deletedPackage.applicationInfo.getResourcePath(), 13306 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13307 } else { 13308 res.removedInfo.args = null; 13309 } 13310 13311 // Successfully disabled the old package. Now proceed with re-installation 13312 deleteCodeCacheDirsLI(pkg); 13313 13314 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13315 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13316 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13317 13318 PackageParser.Package newPackage = null; 13319 try { 13320 // Add the package to the internal data structures 13321 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13322 13323 // Set the update and install times 13324 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13325 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13326 System.currentTimeMillis()); 13327 13328 // Check for shared user id changes 13329 String invalidPackageName = getParentOrChildPackageChangedSharedUser( 13330 deletedPackage, newPackage); 13331 if (invalidPackageName != null) { 13332 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13333 "Forbidding shared user change from " + deletedPkgSetting.sharedUser 13334 + " to " + invalidPackageName); 13335 } 13336 13337 // Update the package dynamic state if succeeded 13338 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13339 // Now that the install succeeded make sure we remove data 13340 // directories for any child package the update removed. 13341 final int deletedChildCount = (deletedPackage.childPackages != null) 13342 ? deletedPackage.childPackages.size() : 0; 13343 final int newChildCount = (newPackage.childPackages != null) 13344 ? newPackage.childPackages.size() : 0; 13345 for (int i = 0; i < deletedChildCount; i++) { 13346 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13347 boolean childPackageDeleted = true; 13348 for (int j = 0; j < newChildCount; j++) { 13349 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13350 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13351 childPackageDeleted = false; 13352 break; 13353 } 13354 } 13355 if (childPackageDeleted) { 13356 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13357 deletedChildPkg.packageName); 13358 if (ps != null && res.removedInfo.removedChildPackages != null) { 13359 PackageRemovedInfo removedChildRes = res.removedInfo 13360 .removedChildPackages.get(deletedChildPkg.packageName); 13361 removePackageDataLI(ps, allUsers, removedChildRes, 0, false); 13362 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13363 } 13364 } 13365 } 13366 13367 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13368 prepareAppDataAfterInstall(newPackage); 13369 } 13370 } catch (PackageManagerException e) { 13371 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13372 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13373 } 13374 13375 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13376 // Re installation failed. Restore old information 13377 // Remove new pkg information 13378 if (newPackage != null) { 13379 removeInstalledPackageLI(newPackage, true); 13380 } 13381 // Add back the old system package 13382 try { 13383 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13384 } catch (PackageManagerException e) { 13385 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13386 } 13387 13388 synchronized (mPackages) { 13389 if (disabledSystem) { 13390 enableSystemPackageLPw(deletedPackage); 13391 } 13392 13393 // Ensure the installer package name up to date 13394 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13395 13396 // Update permissions for restored package 13397 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13398 13399 mSettings.writeLPr(); 13400 } 13401 13402 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13403 + " after failed upgrade"); 13404 } 13405 } 13406 13407 /** 13408 * Checks whether the parent or any of the child packages have a change shared 13409 * user. For a package to be a valid update the shred users of the parent and 13410 * the children should match. We may later support changing child shared users. 13411 * @param oldPkg The updated package. 13412 * @param newPkg The update package. 13413 * @return The shared user that change between the versions. 13414 */ 13415 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 13416 PackageParser.Package newPkg) { 13417 // Check parent shared user 13418 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 13419 return newPkg.packageName; 13420 } 13421 // Check child shared users 13422 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13423 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 13424 for (int i = 0; i < newChildCount; i++) { 13425 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 13426 // If this child was present, did it have the same shared user? 13427 for (int j = 0; j < oldChildCount; j++) { 13428 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 13429 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 13430 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 13431 return newChildPkg.packageName; 13432 } 13433 } 13434 } 13435 return null; 13436 } 13437 13438 private void removeNativeBinariesLI(PackageSetting ps) { 13439 // Remove the lib path for the parent package 13440 if (ps != null) { 13441 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 13442 // Remove the lib path for the child packages 13443 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 13444 for (int i = 0; i < childCount; i++) { 13445 PackageSetting childPs = null; 13446 synchronized (mPackages) { 13447 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 13448 } 13449 if (childPs != null) { 13450 NativeLibraryHelper.removeNativeBinariesLI(childPs 13451 .legacyNativeLibraryPathString); 13452 } 13453 } 13454 } 13455 } 13456 13457 private void enableSystemPackageLPw(PackageParser.Package pkg) { 13458 // Enable the parent package 13459 mSettings.enableSystemPackageLPw(pkg.packageName); 13460 // Enable the child packages 13461 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13462 for (int i = 0; i < childCount; i++) { 13463 PackageParser.Package childPkg = pkg.childPackages.get(i); 13464 mSettings.enableSystemPackageLPw(childPkg.packageName); 13465 } 13466 } 13467 13468 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 13469 PackageParser.Package newPkg) { 13470 // Disable the parent package (parent always replaced) 13471 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 13472 // Disable the child packages 13473 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 13474 for (int i = 0; i < childCount; i++) { 13475 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 13476 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 13477 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 13478 } 13479 return disabled; 13480 } 13481 13482 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 13483 String installerPackageName) { 13484 // Enable the parent package 13485 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 13486 // Enable the child packages 13487 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13488 for (int i = 0; i < childCount; i++) { 13489 PackageParser.Package childPkg = pkg.childPackages.get(i); 13490 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 13491 } 13492 } 13493 13494 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 13495 // Collect all used permissions in the UID 13496 ArraySet<String> usedPermissions = new ArraySet<>(); 13497 final int packageCount = su.packages.size(); 13498 for (int i = 0; i < packageCount; i++) { 13499 PackageSetting ps = su.packages.valueAt(i); 13500 if (ps.pkg == null) { 13501 continue; 13502 } 13503 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 13504 for (int j = 0; j < requestedPermCount; j++) { 13505 String permission = ps.pkg.requestedPermissions.get(j); 13506 BasePermission bp = mSettings.mPermissions.get(permission); 13507 if (bp != null) { 13508 usedPermissions.add(permission); 13509 } 13510 } 13511 } 13512 13513 PermissionsState permissionsState = su.getPermissionsState(); 13514 // Prune install permissions 13515 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 13516 final int installPermCount = installPermStates.size(); 13517 for (int i = installPermCount - 1; i >= 0; i--) { 13518 PermissionState permissionState = installPermStates.get(i); 13519 if (!usedPermissions.contains(permissionState.getName())) { 13520 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13521 if (bp != null) { 13522 permissionsState.revokeInstallPermission(bp); 13523 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 13524 PackageManager.MASK_PERMISSION_FLAGS, 0); 13525 } 13526 } 13527 } 13528 13529 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 13530 13531 // Prune runtime permissions 13532 for (int userId : allUserIds) { 13533 List<PermissionState> runtimePermStates = permissionsState 13534 .getRuntimePermissionStates(userId); 13535 final int runtimePermCount = runtimePermStates.size(); 13536 for (int i = runtimePermCount - 1; i >= 0; i--) { 13537 PermissionState permissionState = runtimePermStates.get(i); 13538 if (!usedPermissions.contains(permissionState.getName())) { 13539 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 13540 if (bp != null) { 13541 permissionsState.revokeRuntimePermission(bp, userId); 13542 permissionsState.updatePermissionFlags(bp, userId, 13543 PackageManager.MASK_PERMISSION_FLAGS, 0); 13544 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 13545 runtimePermissionChangedUserIds, userId); 13546 } 13547 } 13548 } 13549 } 13550 13551 return runtimePermissionChangedUserIds; 13552 } 13553 13554 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 13555 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 13556 // Update the parent package setting 13557 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 13558 res, user); 13559 // Update the child packages setting 13560 final int childCount = (newPackage.childPackages != null) 13561 ? newPackage.childPackages.size() : 0; 13562 for (int i = 0; i < childCount; i++) { 13563 PackageParser.Package childPackage = newPackage.childPackages.get(i); 13564 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 13565 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 13566 childRes.origUsers, childRes, user); 13567 } 13568 } 13569 13570 private void updateSettingsInternalLI(PackageParser.Package newPackage, 13571 String installerPackageName, int[] allUsers, int[] installedForUsers, 13572 PackageInstalledInfo res, UserHandle user) { 13573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 13574 13575 String pkgName = newPackage.packageName; 13576 synchronized (mPackages) { 13577 //write settings. the installStatus will be incomplete at this stage. 13578 //note that the new package setting would have already been 13579 //added to mPackages. It hasn't been persisted yet. 13580 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 13581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13582 mSettings.writeLPr(); 13583 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13584 } 13585 13586 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 13587 synchronized (mPackages) { 13588 updatePermissionsLPw(newPackage.packageName, newPackage, 13589 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 13590 ? UPDATE_PERMISSIONS_ALL : 0)); 13591 // For system-bundled packages, we assume that installing an upgraded version 13592 // of the package implies that the user actually wants to run that new code, 13593 // so we enable the package. 13594 PackageSetting ps = mSettings.mPackages.get(pkgName); 13595 final int userId = user.getIdentifier(); 13596 if (ps != null) { 13597 if (isSystemApp(newPackage)) { 13598 if (DEBUG_INSTALL) { 13599 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 13600 } 13601 // Enable system package for requested users 13602 if (res.origUsers != null) { 13603 for (int origUserId : res.origUsers) { 13604 if (userId == UserHandle.USER_ALL || userId == origUserId) { 13605 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 13606 origUserId, installerPackageName); 13607 } 13608 } 13609 } 13610 // Also convey the prior install/uninstall state 13611 if (allUsers != null && installedForUsers != null) { 13612 for (int currentUserId : allUsers) { 13613 final boolean installed = ArrayUtils.contains( 13614 installedForUsers, currentUserId); 13615 if (DEBUG_INSTALL) { 13616 Slog.d(TAG, " user " + currentUserId + " => " + installed); 13617 } 13618 ps.setInstalled(installed, currentUserId); 13619 } 13620 // these install state changes will be persisted in the 13621 // upcoming call to mSettings.writeLPr(). 13622 } 13623 } 13624 // It's implied that when a user requests installation, they want the app to be 13625 // installed and enabled. 13626 if (userId != UserHandle.USER_ALL) { 13627 ps.setInstalled(true, userId); 13628 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 13629 } 13630 } 13631 res.name = pkgName; 13632 res.uid = newPackage.applicationInfo.uid; 13633 res.pkg = newPackage; 13634 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 13635 mSettings.setInstallerPackageName(pkgName, installerPackageName); 13636 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13637 //to update install status 13638 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 13639 mSettings.writeLPr(); 13640 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13641 } 13642 13643 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13644 } 13645 13646 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 13647 try { 13648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 13649 installPackageLI(args, res); 13650 } finally { 13651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13652 } 13653 } 13654 13655 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 13656 final int installFlags = args.installFlags; 13657 final String installerPackageName = args.installerPackageName; 13658 final String volumeUuid = args.volumeUuid; 13659 final File tmpPackageFile = new File(args.getCodePath()); 13660 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 13661 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 13662 || (args.volumeUuid != null)); 13663 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 13664 boolean replace = false; 13665 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 13666 if (args.move != null) { 13667 // moving a complete application; perform an initial scan on the new install location 13668 scanFlags |= SCAN_INITIAL; 13669 } 13670 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 13671 scanFlags |= SCAN_DONT_KILL_APP; 13672 } 13673 13674 // Result object to be returned 13675 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13676 13677 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 13678 13679 // Sanity check 13680 if (ephemeral && (forwardLocked || onExternal)) { 13681 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 13682 + " external=" + onExternal); 13683 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13684 return; 13685 } 13686 13687 // Retrieve PackageSettings and parse package 13688 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 13689 | PackageParser.PARSE_ENFORCE_CODE 13690 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 13691 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 13692 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 13693 PackageParser pp = new PackageParser(); 13694 pp.setSeparateProcesses(mSeparateProcesses); 13695 pp.setDisplayMetrics(mMetrics); 13696 13697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 13698 final PackageParser.Package pkg; 13699 try { 13700 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 13701 } catch (PackageParserException e) { 13702 res.setError("Failed parse during installPackageLI", e); 13703 return; 13704 } finally { 13705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13706 } 13707 13708 // If we are installing a clustered package add results for the children 13709 if (pkg.childPackages != null) { 13710 synchronized (mPackages) { 13711 final int childCount = pkg.childPackages.size(); 13712 for (int i = 0; i < childCount; i++) { 13713 PackageParser.Package childPkg = pkg.childPackages.get(i); 13714 PackageInstalledInfo childRes = new PackageInstalledInfo(); 13715 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13716 childRes.pkg = childPkg; 13717 childRes.name = childPkg.packageName; 13718 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13719 if (childPs != null) { 13720 childRes.origUsers = childPs.queryInstalledUsers( 13721 sUserManager.getUserIds(), true); 13722 } 13723 if ((mPackages.containsKey(childPkg.packageName))) { 13724 childRes.removedInfo = new PackageRemovedInfo(); 13725 childRes.removedInfo.removedPackage = childPkg.packageName; 13726 } 13727 if (res.addedChildPackages == null) { 13728 res.addedChildPackages = new ArrayMap<>(); 13729 } 13730 res.addedChildPackages.put(childPkg.packageName, childRes); 13731 } 13732 } 13733 } 13734 13735 // If package doesn't declare API override, mark that we have an install 13736 // time CPU ABI override. 13737 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 13738 pkg.cpuAbiOverride = args.abiOverride; 13739 } 13740 13741 String pkgName = res.name = pkg.packageName; 13742 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 13743 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 13744 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 13745 return; 13746 } 13747 } 13748 13749 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 13750 try { 13751 PackageParser.collectCertificates(pkg, parseFlags); 13752 } catch (PackageParserException e) { 13753 res.setError("Failed collect during installPackageLI", e); 13754 return; 13755 } finally { 13756 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13757 } 13758 13759 // Get rid of all references to package scan path via parser. 13760 pp = null; 13761 String oldCodePath = null; 13762 boolean systemApp = false; 13763 synchronized (mPackages) { 13764 // Check if installing already existing package 13765 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13766 String oldName = mSettings.mRenamedPackages.get(pkgName); 13767 if (pkg.mOriginalPackages != null 13768 && pkg.mOriginalPackages.contains(oldName) 13769 && mPackages.containsKey(oldName)) { 13770 // This package is derived from an original package, 13771 // and this device has been updating from that original 13772 // name. We must continue using the original name, so 13773 // rename the new package here. 13774 pkg.setPackageName(oldName); 13775 pkgName = pkg.packageName; 13776 replace = true; 13777 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 13778 + oldName + " pkgName=" + pkgName); 13779 } else if (mPackages.containsKey(pkgName)) { 13780 // This package, under its official name, already exists 13781 // on the device; we should replace it. 13782 replace = true; 13783 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 13784 } 13785 13786 // Child packages are installed through the parent package 13787 if (pkg.parentPackage != null) { 13788 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13789 "Package " + pkg.packageName + " is child of package " 13790 + pkg.parentPackage.parentPackage + ". Child packages " 13791 + "can be updated only through the parent package."); 13792 return; 13793 } 13794 13795 if (replace) { 13796 // Prevent apps opting out from runtime permissions 13797 PackageParser.Package oldPackage = mPackages.get(pkgName); 13798 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 13799 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 13800 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 13801 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 13802 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 13803 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 13804 + " doesn't support runtime permissions but the old" 13805 + " target SDK " + oldTargetSdk + " does."); 13806 return; 13807 } 13808 13809 // Prevent installing of child packages 13810 if (oldPackage.parentPackage != null) { 13811 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 13812 "Package " + pkg.packageName + " is child of package " 13813 + oldPackage.parentPackage + ". Child packages " 13814 + "can be updated only through the parent package."); 13815 return; 13816 } 13817 } 13818 } 13819 13820 PackageSetting ps = mSettings.mPackages.get(pkgName); 13821 if (ps != null) { 13822 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 13823 13824 // Quick sanity check that we're signed correctly if updating; 13825 // we'll check this again later when scanning, but we want to 13826 // bail early here before tripping over redefined permissions. 13827 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13828 if (!checkUpgradeKeySetLP(ps, pkg)) { 13829 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 13830 + pkg.packageName + " upgrade keys do not match the " 13831 + "previously installed version"); 13832 return; 13833 } 13834 } else { 13835 try { 13836 verifySignaturesLP(ps, pkg); 13837 } catch (PackageManagerException e) { 13838 res.setError(e.error, e.getMessage()); 13839 return; 13840 } 13841 } 13842 13843 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 13844 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 13845 systemApp = (ps.pkg.applicationInfo.flags & 13846 ApplicationInfo.FLAG_SYSTEM) != 0; 13847 } 13848 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13849 } 13850 13851 // Check whether the newly-scanned package wants to define an already-defined perm 13852 int N = pkg.permissions.size(); 13853 for (int i = N-1; i >= 0; i--) { 13854 PackageParser.Permission perm = pkg.permissions.get(i); 13855 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 13856 if (bp != null) { 13857 // If the defining package is signed with our cert, it's okay. This 13858 // also includes the "updating the same package" case, of course. 13859 // "updating same package" could also involve key-rotation. 13860 final boolean sigsOk; 13861 if (bp.sourcePackage.equals(pkg.packageName) 13862 && (bp.packageSetting instanceof PackageSetting) 13863 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 13864 scanFlags))) { 13865 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 13866 } else { 13867 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 13868 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 13869 } 13870 if (!sigsOk) { 13871 // If the owning package is the system itself, we log but allow 13872 // install to proceed; we fail the install on all other permission 13873 // redefinitions. 13874 if (!bp.sourcePackage.equals("android")) { 13875 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 13876 + pkg.packageName + " attempting to redeclare permission " 13877 + perm.info.name + " already owned by " + bp.sourcePackage); 13878 res.origPermission = perm.info.name; 13879 res.origPackage = bp.sourcePackage; 13880 return; 13881 } else { 13882 Slog.w(TAG, "Package " + pkg.packageName 13883 + " attempting to redeclare system permission " 13884 + perm.info.name + "; ignoring new declaration"); 13885 pkg.permissions.remove(i); 13886 } 13887 } 13888 } 13889 } 13890 } 13891 13892 if (systemApp) { 13893 if (onExternal) { 13894 // Abort update; system app can't be replaced with app on sdcard 13895 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 13896 "Cannot install updates to system apps on sdcard"); 13897 return; 13898 } else if (ephemeral) { 13899 // Abort update; system app can't be replaced with an ephemeral app 13900 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 13901 "Cannot update a system app with an ephemeral app"); 13902 return; 13903 } 13904 } 13905 13906 if (args.move != null) { 13907 // We did an in-place move, so dex is ready to roll 13908 scanFlags |= SCAN_NO_DEX; 13909 scanFlags |= SCAN_MOVE; 13910 13911 synchronized (mPackages) { 13912 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13913 if (ps == null) { 13914 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 13915 "Missing settings for moved package " + pkgName); 13916 } 13917 13918 // We moved the entire application as-is, so bring over the 13919 // previously derived ABI information. 13920 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 13921 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 13922 } 13923 13924 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 13925 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 13926 scanFlags |= SCAN_NO_DEX; 13927 13928 try { 13929 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 13930 args.abiOverride : pkg.cpuAbiOverride); 13931 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 13932 true /* extract libs */); 13933 } catch (PackageManagerException pme) { 13934 Slog.e(TAG, "Error deriving application ABI", pme); 13935 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 13936 return; 13937 } 13938 13939 13940 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 13941 // Do not run PackageDexOptimizer through the local performDexOpt 13942 // method because `pkg` is not in `mPackages` yet. 13943 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 13944 false /* useProfiles */, true /* extractOnly */); 13945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13946 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 13947 String msg = "Extracking package failed for " + pkgName; 13948 res.setError(INSTALL_FAILED_DEXOPT, msg); 13949 return; 13950 } 13951 } 13952 13953 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 13954 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 13955 return; 13956 } 13957 13958 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 13959 13960 if (replace) { 13961 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 13962 installerPackageName, res); 13963 } else { 13964 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 13965 args.user, installerPackageName, volumeUuid, res); 13966 } 13967 synchronized (mPackages) { 13968 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13969 if (ps != null) { 13970 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 13971 } 13972 13973 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 13974 for (int i = 0; i < childCount; i++) { 13975 PackageParser.Package childPkg = pkg.childPackages.get(i); 13976 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13977 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13978 if (childPs != null) { 13979 childRes.newUsers = childPs.queryInstalledUsers( 13980 sUserManager.getUserIds(), true); 13981 } 13982 } 13983 } 13984 } 13985 13986 private void startIntentFilterVerifications(int userId, boolean replacing, 13987 PackageParser.Package pkg) { 13988 if (mIntentFilterVerifierComponent == null) { 13989 Slog.w(TAG, "No IntentFilter verification will not be done as " 13990 + "there is no IntentFilterVerifier available!"); 13991 return; 13992 } 13993 13994 final int verifierUid = getPackageUid( 13995 mIntentFilterVerifierComponent.getPackageName(), 13996 MATCH_DEBUG_TRIAGED_MISSING, 13997 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 13998 13999 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14000 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14001 mHandler.sendMessage(msg); 14002 14003 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14004 for (int i = 0; i < childCount; i++) { 14005 PackageParser.Package childPkg = pkg.childPackages.get(i); 14006 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14007 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14008 mHandler.sendMessage(msg); 14009 } 14010 } 14011 14012 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14013 PackageParser.Package pkg) { 14014 int size = pkg.activities.size(); 14015 if (size == 0) { 14016 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14017 "No activity, so no need to verify any IntentFilter!"); 14018 return; 14019 } 14020 14021 final boolean hasDomainURLs = hasDomainURLs(pkg); 14022 if (!hasDomainURLs) { 14023 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14024 "No domain URLs, so no need to verify any IntentFilter!"); 14025 return; 14026 } 14027 14028 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14029 + " if any IntentFilter from the " + size 14030 + " Activities needs verification ..."); 14031 14032 int count = 0; 14033 final String packageName = pkg.packageName; 14034 14035 synchronized (mPackages) { 14036 // If this is a new install and we see that we've already run verification for this 14037 // package, we have nothing to do: it means the state was restored from backup. 14038 if (!replacing) { 14039 IntentFilterVerificationInfo ivi = 14040 mSettings.getIntentFilterVerificationLPr(packageName); 14041 if (ivi != null) { 14042 if (DEBUG_DOMAIN_VERIFICATION) { 14043 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14044 + ivi.getStatusString()); 14045 } 14046 return; 14047 } 14048 } 14049 14050 // If any filters need to be verified, then all need to be. 14051 boolean needToVerify = false; 14052 for (PackageParser.Activity a : pkg.activities) { 14053 for (ActivityIntentInfo filter : a.intents) { 14054 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14055 if (DEBUG_DOMAIN_VERIFICATION) { 14056 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14057 } 14058 needToVerify = true; 14059 break; 14060 } 14061 } 14062 } 14063 14064 if (needToVerify) { 14065 final int verificationId = mIntentFilterVerificationToken++; 14066 for (PackageParser.Activity a : pkg.activities) { 14067 for (ActivityIntentInfo filter : a.intents) { 14068 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14069 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14070 "Verification needed for IntentFilter:" + filter.toString()); 14071 mIntentFilterVerifier.addOneIntentFilterVerification( 14072 verifierUid, userId, verificationId, filter, packageName); 14073 count++; 14074 } 14075 } 14076 } 14077 } 14078 } 14079 14080 if (count > 0) { 14081 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14082 + " IntentFilter verification" + (count > 1 ? "s" : "") 14083 + " for userId:" + userId); 14084 mIntentFilterVerifier.startVerifications(userId); 14085 } else { 14086 if (DEBUG_DOMAIN_VERIFICATION) { 14087 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14088 } 14089 } 14090 } 14091 14092 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14093 final ComponentName cn = filter.activity.getComponentName(); 14094 final String packageName = cn.getPackageName(); 14095 14096 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14097 packageName); 14098 if (ivi == null) { 14099 return true; 14100 } 14101 int status = ivi.getStatus(); 14102 switch (status) { 14103 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14104 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14105 return true; 14106 14107 default: 14108 // Nothing to do 14109 return false; 14110 } 14111 } 14112 14113 private static boolean isMultiArch(ApplicationInfo info) { 14114 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14115 } 14116 14117 private static boolean isExternal(PackageParser.Package pkg) { 14118 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14119 } 14120 14121 private static boolean isExternal(PackageSetting ps) { 14122 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14123 } 14124 14125 private static boolean isEphemeral(PackageParser.Package pkg) { 14126 return pkg.applicationInfo.isEphemeralApp(); 14127 } 14128 14129 private static boolean isEphemeral(PackageSetting ps) { 14130 return ps.pkg != null && isEphemeral(ps.pkg); 14131 } 14132 14133 private static boolean isSystemApp(PackageParser.Package pkg) { 14134 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14135 } 14136 14137 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14138 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14139 } 14140 14141 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14142 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14143 } 14144 14145 private static boolean isSystemApp(PackageSetting ps) { 14146 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14147 } 14148 14149 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14150 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14151 } 14152 14153 private int packageFlagsToInstallFlags(PackageSetting ps) { 14154 int installFlags = 0; 14155 if (isEphemeral(ps)) { 14156 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14157 } 14158 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14159 // This existing package was an external ASEC install when we have 14160 // the external flag without a UUID 14161 installFlags |= PackageManager.INSTALL_EXTERNAL; 14162 } 14163 if (ps.isForwardLocked()) { 14164 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14165 } 14166 return installFlags; 14167 } 14168 14169 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14170 if (isExternal(pkg)) { 14171 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14172 return StorageManager.UUID_PRIMARY_PHYSICAL; 14173 } else { 14174 return pkg.volumeUuid; 14175 } 14176 } else { 14177 return StorageManager.UUID_PRIVATE_INTERNAL; 14178 } 14179 } 14180 14181 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14182 if (isExternal(pkg)) { 14183 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14184 return mSettings.getExternalVersion(); 14185 } else { 14186 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14187 } 14188 } else { 14189 return mSettings.getInternalVersion(); 14190 } 14191 } 14192 14193 private void deleteTempPackageFiles() { 14194 final FilenameFilter filter = new FilenameFilter() { 14195 public boolean accept(File dir, String name) { 14196 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14197 } 14198 }; 14199 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14200 file.delete(); 14201 } 14202 } 14203 14204 @Override 14205 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14206 int flags) { 14207 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14208 flags); 14209 } 14210 14211 @Override 14212 public void deletePackage(final String packageName, 14213 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 14214 mContext.enforceCallingOrSelfPermission( 14215 android.Manifest.permission.DELETE_PACKAGES, null); 14216 Preconditions.checkNotNull(packageName); 14217 Preconditions.checkNotNull(observer); 14218 final int uid = Binder.getCallingUid(); 14219 final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0; 14220 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14221 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14222 mContext.enforceCallingOrSelfPermission( 14223 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14224 "deletePackage for user " + userId); 14225 } 14226 14227 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14228 try { 14229 observer.onPackageDeleted(packageName, 14230 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14231 } catch (RemoteException re) { 14232 } 14233 return; 14234 } 14235 14236 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14237 try { 14238 observer.onPackageDeleted(packageName, 14239 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14240 } catch (RemoteException re) { 14241 } 14242 return; 14243 } 14244 14245 if (DEBUG_REMOVE) { 14246 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14247 + " deleteAllUsers: " + deleteAllUsers ); 14248 } 14249 // Queue up an async operation since the package deletion may take a little while. 14250 mHandler.post(new Runnable() { 14251 public void run() { 14252 mHandler.removeCallbacks(this); 14253 int returnCode; 14254 if (!deleteAllUsers) { 14255 returnCode = deletePackageX(packageName, userId, flags); 14256 } else { 14257 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14258 // If nobody is blocking uninstall, proceed with delete for all users 14259 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14260 returnCode = deletePackageX(packageName, userId, flags); 14261 } else { 14262 // Otherwise uninstall individually for users with blockUninstalls=false 14263 final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS; 14264 for (int userId : users) { 14265 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14266 returnCode = deletePackageX(packageName, userId, userFlags); 14267 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14268 Slog.w(TAG, "Package delete failed for user " + userId 14269 + ", returnCode " + returnCode); 14270 } 14271 } 14272 } 14273 // The app has only been marked uninstalled for certain users. 14274 // We still need to report that delete was blocked 14275 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14276 } 14277 } 14278 try { 14279 observer.onPackageDeleted(packageName, returnCode, null); 14280 } catch (RemoteException e) { 14281 Log.i(TAG, "Observer no longer exists."); 14282 } //end catch 14283 } //end run 14284 }); 14285 } 14286 14287 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14288 int[] result = EMPTY_INT_ARRAY; 14289 for (int userId : userIds) { 14290 if (getBlockUninstallForUser(packageName, userId)) { 14291 result = ArrayUtils.appendInt(result, userId); 14292 } 14293 } 14294 return result; 14295 } 14296 14297 @Override 14298 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14299 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14300 } 14301 14302 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14303 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14304 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14305 try { 14306 if (dpm != null) { 14307 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14308 /* callingUserOnly =*/ false); 14309 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14310 : deviceOwnerComponentName.getPackageName(); 14311 // Does the package contains the device owner? 14312 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14313 // this check is probably not needed, since DO should be registered as a device 14314 // admin on some user too. (Original bug for this: b/17657954) 14315 if (packageName.equals(deviceOwnerPackageName)) { 14316 return true; 14317 } 14318 // Does it contain a device admin for any user? 14319 int[] users; 14320 if (userId == UserHandle.USER_ALL) { 14321 users = sUserManager.getUserIds(); 14322 } else { 14323 users = new int[]{userId}; 14324 } 14325 for (int i = 0; i < users.length; ++i) { 14326 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14327 return true; 14328 } 14329 } 14330 } 14331 } catch (RemoteException e) { 14332 } 14333 return false; 14334 } 14335 14336 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14337 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14338 } 14339 14340 /** 14341 * This method is an internal method that could be get invoked either 14342 * to delete an installed package or to clean up a failed installation. 14343 * After deleting an installed package, a broadcast is sent to notify any 14344 * listeners that the package has been installed. For cleaning up a failed 14345 * installation, the broadcast is not necessary since the package's 14346 * installation wouldn't have sent the initial broadcast either 14347 * The key steps in deleting a package are 14348 * deleting the package information in internal structures like mPackages, 14349 * deleting the packages base directories through installd 14350 * updating mSettings to reflect current status 14351 * persisting settings for later use 14352 * sending a broadcast if necessary 14353 */ 14354 private int deletePackageX(String packageName, int userId, int flags) { 14355 final PackageRemovedInfo info = new PackageRemovedInfo(); 14356 final boolean res; 14357 14358 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 14359 ? UserHandle.ALL : new UserHandle(userId); 14360 14361 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14362 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14363 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14364 } 14365 14366 PackageSetting uninstalledPs = null; 14367 14368 // for the uninstall-updates case and restricted profiles, remember the per- 14369 // user handle installed state 14370 int[] allUsers; 14371 synchronized (mPackages) { 14372 uninstalledPs = mSettings.mPackages.get(packageName); 14373 if (uninstalledPs == null) { 14374 Slog.w(TAG, "Not removing non-existent package " + packageName); 14375 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14376 } 14377 allUsers = sUserManager.getUserIds(); 14378 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14379 } 14380 14381 synchronized (mInstallLock) { 14382 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14383 res = deletePackageLI(packageName, removeForUser, true, allUsers, 14384 flags | REMOVE_CHATTY, info, true, null); 14385 synchronized (mPackages) { 14386 if (res) { 14387 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14388 } 14389 } 14390 } 14391 14392 if (res) { 14393 final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0; 14394 info.sendPackageRemovedBroadcasts(killApp); 14395 info.sendSystemPackageUpdatedBroadcasts(); 14396 info.sendSystemPackageAppearedBroadcasts(); 14397 } 14398 // Force a gc here. 14399 Runtime.getRuntime().gc(); 14400 // Delete the resources here after sending the broadcast to let 14401 // other processes clean up before deleting resources. 14402 if (info.args != null) { 14403 synchronized (mInstallLock) { 14404 info.args.doPostDeleteLI(true); 14405 } 14406 } 14407 14408 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14409 } 14410 14411 class PackageRemovedInfo { 14412 String removedPackage; 14413 int uid = -1; 14414 int removedAppId = -1; 14415 int[] origUsers; 14416 int[] removedUsers = null; 14417 boolean isRemovedPackageSystemUpdate = false; 14418 boolean isUpdate; 14419 boolean dataRemoved; 14420 boolean removedForAllUsers; 14421 // Clean up resources deleted packages. 14422 InstallArgs args = null; 14423 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 14424 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 14425 14426 void sendPackageRemovedBroadcasts(boolean killApp) { 14427 sendPackageRemovedBroadcastInternal(killApp); 14428 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 14429 for (int i = 0; i < childCount; i++) { 14430 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14431 childInfo.sendPackageRemovedBroadcastInternal(killApp); 14432 } 14433 } 14434 14435 void sendSystemPackageUpdatedBroadcasts() { 14436 if (isRemovedPackageSystemUpdate) { 14437 sendSystemPackageUpdatedBroadcastsInternal(); 14438 final int childCount = (removedChildPackages != null) 14439 ? removedChildPackages.size() : 0; 14440 for (int i = 0; i < childCount; i++) { 14441 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 14442 if (childInfo.isRemovedPackageSystemUpdate) { 14443 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 14444 } 14445 } 14446 } 14447 } 14448 14449 void sendSystemPackageAppearedBroadcasts() { 14450 final int packageCount = (appearedChildPackages != null) 14451 ? appearedChildPackages.size() : 0; 14452 for (int i = 0; i < packageCount; i++) { 14453 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 14454 for (int userId : installedInfo.newUsers) { 14455 sendPackageAddedForUser(installedInfo.name, true, 14456 UserHandle.getAppId(installedInfo.uid), userId); 14457 } 14458 } 14459 } 14460 14461 private void sendSystemPackageUpdatedBroadcastsInternal() { 14462 Bundle extras = new Bundle(2); 14463 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14464 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14465 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 14466 extras, 0, null, null, null); 14467 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 14468 extras, 0, null, null, null); 14469 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 14470 null, 0, removedPackage, null, null); 14471 } 14472 14473 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 14474 Bundle extras = new Bundle(2); 14475 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 14476 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 14477 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 14478 if (isUpdate || isRemovedPackageSystemUpdate) { 14479 extras.putBoolean(Intent.EXTRA_REPLACING, true); 14480 } 14481 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 14482 if (removedPackage != null) { 14483 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 14484 extras, 0, null, null, removedUsers); 14485 if (dataRemoved && !isRemovedPackageSystemUpdate) { 14486 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 14487 removedPackage, extras, 0, null, null, removedUsers); 14488 } 14489 } 14490 if (removedAppId >= 0) { 14491 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 14492 removedUsers); 14493 } 14494 } 14495 } 14496 14497 /* 14498 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 14499 * flag is not set, the data directory is removed as well. 14500 * make sure this flag is set for partially installed apps. If not its meaningless to 14501 * delete a partially installed application. 14502 */ 14503 private void removePackageDataLI(PackageSetting ps, int[] allUserHandles, 14504 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 14505 String packageName = ps.name; 14506 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 14507 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 14508 // Retrieve object to delete permissions for shared user later on 14509 final PackageSetting deletedPs; 14510 // reader 14511 synchronized (mPackages) { 14512 deletedPs = mSettings.mPackages.get(packageName); 14513 if (outInfo != null) { 14514 outInfo.removedPackage = packageName; 14515 outInfo.removedUsers = deletedPs != null 14516 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 14517 : null; 14518 } 14519 } 14520 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14521 removeDataDirsLI(ps.volumeUuid, packageName); 14522 if (outInfo != null) { 14523 outInfo.dataRemoved = true; 14524 } 14525 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 14526 } 14527 // writer 14528 synchronized (mPackages) { 14529 if (deletedPs != null) { 14530 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 14531 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 14532 clearDefaultBrowserIfNeeded(packageName); 14533 if (outInfo != null) { 14534 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 14535 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 14536 } 14537 updatePermissionsLPw(deletedPs.name, null, 0); 14538 if (deletedPs.sharedUser != null) { 14539 // Remove permissions associated with package. Since runtime 14540 // permissions are per user we have to kill the removed package 14541 // or packages running under the shared user of the removed 14542 // package if revoking the permissions requested only by the removed 14543 // package is successful and this causes a change in gids. 14544 for (int userId : UserManagerService.getInstance().getUserIds()) { 14545 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 14546 userId); 14547 if (userIdToKill == UserHandle.USER_ALL 14548 || userIdToKill >= UserHandle.USER_SYSTEM) { 14549 // If gids changed for this user, kill all affected packages. 14550 mHandler.post(new Runnable() { 14551 @Override 14552 public void run() { 14553 // This has to happen with no lock held. 14554 killApplication(deletedPs.name, deletedPs.appId, 14555 KILL_APP_REASON_GIDS_CHANGED); 14556 } 14557 }); 14558 break; 14559 } 14560 } 14561 } 14562 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 14563 } 14564 // make sure to preserve per-user disabled state if this removal was just 14565 // a downgrade of a system app to the factory package 14566 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 14567 if (DEBUG_REMOVE) { 14568 Slog.d(TAG, "Propagating install state across downgrade"); 14569 } 14570 for (int userId : allUserHandles) { 14571 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14572 if (DEBUG_REMOVE) { 14573 Slog.d(TAG, " user " + userId + " => " + installed); 14574 } 14575 ps.setInstalled(installed, userId); 14576 } 14577 } 14578 } 14579 // can downgrade to reader 14580 if (writeSettings) { 14581 // Save settings now 14582 mSettings.writeLPr(); 14583 } 14584 } 14585 if (outInfo != null) { 14586 // A user ID was deleted here. Go through all users and remove it 14587 // from KeyStore. 14588 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 14589 } 14590 } 14591 14592 static boolean locationIsPrivileged(File path) { 14593 try { 14594 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 14595 .getCanonicalPath(); 14596 return path.getCanonicalPath().startsWith(privilegedAppDir); 14597 } catch (IOException e) { 14598 Slog.e(TAG, "Unable to access code path " + path); 14599 } 14600 return false; 14601 } 14602 14603 /* 14604 * Tries to delete system package. 14605 */ 14606 private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg, 14607 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 14608 boolean writeSettings) { 14609 if (deletedPs.parentPackageName != null) { 14610 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 14611 return false; 14612 } 14613 14614 final boolean applyUserRestrictions 14615 = (allUserHandles != null) && (outInfo.origUsers != null); 14616 final PackageSetting disabledPs; 14617 // Confirm if the system package has been updated 14618 // An updated system app can be deleted. This will also have to restore 14619 // the system pkg from system partition 14620 // reader 14621 synchronized (mPackages) { 14622 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 14623 } 14624 14625 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 14626 + " disabledPs=" + disabledPs); 14627 14628 if (disabledPs == null) { 14629 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 14630 return false; 14631 } else if (DEBUG_REMOVE) { 14632 Slog.d(TAG, "Deleting system pkg from data partition"); 14633 } 14634 14635 if (DEBUG_REMOVE) { 14636 if (applyUserRestrictions) { 14637 Slog.d(TAG, "Remembering install states:"); 14638 for (int userId : allUserHandles) { 14639 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 14640 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 14641 } 14642 } 14643 } 14644 14645 // Delete the updated package 14646 outInfo.isRemovedPackageSystemUpdate = true; 14647 if (outInfo.removedChildPackages != null) { 14648 final int childCount = (deletedPs.childPackageNames != null) 14649 ? deletedPs.childPackageNames.size() : 0; 14650 for (int i = 0; i < childCount; i++) { 14651 String childPackageName = deletedPs.childPackageNames.get(i); 14652 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 14653 .contains(childPackageName)) { 14654 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14655 childPackageName); 14656 if (childInfo != null) { 14657 childInfo.isRemovedPackageSystemUpdate = true; 14658 } 14659 } 14660 } 14661 } 14662 14663 if (disabledPs.versionCode < deletedPs.versionCode) { 14664 // Delete data for downgrades 14665 flags &= ~PackageManager.DELETE_KEEP_DATA; 14666 } else { 14667 // Preserve data by setting flag 14668 flags |= PackageManager.DELETE_KEEP_DATA; 14669 } 14670 14671 boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles, 14672 outInfo, writeSettings, disabledPs.pkg); 14673 if (!ret) { 14674 return false; 14675 } 14676 14677 // writer 14678 synchronized (mPackages) { 14679 // Reinstate the old system package 14680 enableSystemPackageLPw(disabledPs.pkg); 14681 // Remove any native libraries from the upgraded package. 14682 removeNativeBinariesLI(deletedPs); 14683 } 14684 14685 // Install the system package 14686 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 14687 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 14688 if (locationIsPrivileged(disabledPs.codePath)) { 14689 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 14690 } 14691 14692 final PackageParser.Package newPkg; 14693 try { 14694 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 14695 } catch (PackageManagerException e) { 14696 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 14697 + e.getMessage()); 14698 return false; 14699 } 14700 14701 prepareAppDataAfterInstall(newPkg); 14702 14703 // writer 14704 synchronized (mPackages) { 14705 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 14706 14707 // Propagate the permissions state as we do not want to drop on the floor 14708 // runtime permissions. The update permissions method below will take 14709 // care of removing obsolete permissions and grant install permissions. 14710 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 14711 updatePermissionsLPw(newPkg.packageName, newPkg, 14712 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 14713 14714 if (applyUserRestrictions) { 14715 if (DEBUG_REMOVE) { 14716 Slog.d(TAG, "Propagating install state across reinstall"); 14717 } 14718 for (int userId : allUserHandles) { 14719 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 14720 if (DEBUG_REMOVE) { 14721 Slog.d(TAG, " user " + userId + " => " + installed); 14722 } 14723 ps.setInstalled(installed, userId); 14724 14725 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 14726 } 14727 // Regardless of writeSettings we need to ensure that this restriction 14728 // state propagation is persisted 14729 mSettings.writeAllUsersPackageRestrictionsLPr(); 14730 } 14731 // can downgrade to reader here 14732 if (writeSettings) { 14733 mSettings.writeLPr(); 14734 } 14735 } 14736 return true; 14737 } 14738 14739 private boolean deleteInstalledPackageLI(PackageSetting ps, 14740 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 14741 PackageRemovedInfo outInfo, boolean writeSettings, 14742 PackageParser.Package replacingPackage) { 14743 synchronized (mPackages) { 14744 if (outInfo != null) { 14745 outInfo.uid = ps.appId; 14746 } 14747 14748 if (outInfo != null && outInfo.removedChildPackages != null) { 14749 final int childCount = (ps.childPackageNames != null) 14750 ? ps.childPackageNames.size() : 0; 14751 for (int i = 0; i < childCount; i++) { 14752 String childPackageName = ps.childPackageNames.get(i); 14753 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 14754 if (childPs == null) { 14755 return false; 14756 } 14757 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 14758 childPackageName); 14759 if (childInfo != null) { 14760 childInfo.uid = childPs.appId; 14761 } 14762 } 14763 } 14764 } 14765 14766 // Delete package data from internal structures and also remove data if flag is set 14767 removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings); 14768 14769 // Delete the child packages data 14770 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14771 for (int i = 0; i < childCount; i++) { 14772 PackageSetting childPs; 14773 synchronized (mPackages) { 14774 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14775 } 14776 if (childPs != null) { 14777 PackageRemovedInfo childOutInfo = (outInfo != null 14778 && outInfo.removedChildPackages != null) 14779 ? outInfo.removedChildPackages.get(childPs.name) : null; 14780 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 14781 && (replacingPackage != null 14782 && !replacingPackage.hasChildPackage(childPs.name)) 14783 ? flags & ~DELETE_KEEP_DATA : flags; 14784 removePackageDataLI(childPs, allUserHandles, childOutInfo, 14785 deleteFlags, writeSettings); 14786 } 14787 } 14788 14789 // Delete application code and resources only for parent packages 14790 if (ps.parentPackageName == null) { 14791 if (deleteCodeAndResources && (outInfo != null)) { 14792 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 14793 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 14794 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 14795 } 14796 } 14797 14798 return true; 14799 } 14800 14801 @Override 14802 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 14803 int userId) { 14804 mContext.enforceCallingOrSelfPermission( 14805 android.Manifest.permission.DELETE_PACKAGES, null); 14806 synchronized (mPackages) { 14807 PackageSetting ps = mSettings.mPackages.get(packageName); 14808 if (ps == null) { 14809 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 14810 return false; 14811 } 14812 if (!ps.getInstalled(userId)) { 14813 // Can't block uninstall for an app that is not installed or enabled. 14814 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 14815 return false; 14816 } 14817 ps.setBlockUninstall(blockUninstall, userId); 14818 mSettings.writePackageRestrictionsLPr(userId); 14819 } 14820 return true; 14821 } 14822 14823 @Override 14824 public boolean getBlockUninstallForUser(String packageName, int userId) { 14825 synchronized (mPackages) { 14826 PackageSetting ps = mSettings.mPackages.get(packageName); 14827 if (ps == null) { 14828 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 14829 return false; 14830 } 14831 return ps.getBlockUninstall(userId); 14832 } 14833 } 14834 14835 @Override 14836 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 14837 int callingUid = Binder.getCallingUid(); 14838 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 14839 throw new SecurityException( 14840 "setRequiredForSystemUser can only be run by the system or root"); 14841 } 14842 synchronized (mPackages) { 14843 PackageSetting ps = mSettings.mPackages.get(packageName); 14844 if (ps == null) { 14845 Log.w(TAG, "Package doesn't exist: " + packageName); 14846 return false; 14847 } 14848 if (systemUserApp) { 14849 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14850 } else { 14851 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 14852 } 14853 mSettings.writeLPr(); 14854 } 14855 return true; 14856 } 14857 14858 /* 14859 * This method handles package deletion in general 14860 */ 14861 private boolean deletePackageLI(String packageName, UserHandle user, 14862 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 14863 PackageRemovedInfo outInfo, boolean writeSettings, 14864 PackageParser.Package replacingPackage) { 14865 if (packageName == null) { 14866 Slog.w(TAG, "Attempt to delete null packageName."); 14867 return false; 14868 } 14869 14870 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 14871 14872 PackageSetting ps; 14873 14874 synchronized (mPackages) { 14875 ps = mSettings.mPackages.get(packageName); 14876 if (ps == null) { 14877 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 14878 return false; 14879 } 14880 14881 if (ps.parentPackageName != null && (!isSystemApp(ps) 14882 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 14883 if (DEBUG_REMOVE) { 14884 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 14885 + ((user == null) ? UserHandle.USER_ALL : user)); 14886 } 14887 final int removedUserId = (user != null) ? user.getIdentifier() 14888 : UserHandle.USER_ALL; 14889 if (!clearPackageStateForUser(ps, removedUserId, outInfo)) { 14890 return false; 14891 } 14892 markPackageUninstalledForUserLPw(ps, user); 14893 scheduleWritePackageRestrictionsLocked(user); 14894 return true; 14895 } 14896 } 14897 14898 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 14899 && user.getIdentifier() != UserHandle.USER_ALL)) { 14900 // The caller is asking that the package only be deleted for a single 14901 // user. To do this, we just mark its uninstalled state and delete 14902 // its data. If this is a system app, we only allow this to happen if 14903 // they have set the special DELETE_SYSTEM_APP which requests different 14904 // semantics than normal for uninstalling system apps. 14905 markPackageUninstalledForUserLPw(ps, user); 14906 14907 if (!isSystemApp(ps)) { 14908 // Do not uninstall the APK if an app should be cached 14909 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 14910 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 14911 // Other user still have this package installed, so all 14912 // we need to do is clear this user's data and save that 14913 // it is uninstalled. 14914 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 14915 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14916 return false; 14917 } 14918 scheduleWritePackageRestrictionsLocked(user); 14919 return true; 14920 } else { 14921 // We need to set it back to 'installed' so the uninstall 14922 // broadcasts will be sent correctly. 14923 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 14924 ps.setInstalled(true, user.getIdentifier()); 14925 } 14926 } else { 14927 // This is a system app, so we assume that the 14928 // other users still have this package installed, so all 14929 // we need to do is clear this user's data and save that 14930 // it is uninstalled. 14931 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 14932 if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) { 14933 return false; 14934 } 14935 scheduleWritePackageRestrictionsLocked(user); 14936 return true; 14937 } 14938 } 14939 14940 // If we are deleting a composite package for all users, keep track 14941 // of result for each child. 14942 if (ps.childPackageNames != null && outInfo != null) { 14943 synchronized (mPackages) { 14944 final int childCount = ps.childPackageNames.size(); 14945 outInfo.removedChildPackages = new ArrayMap<>(childCount); 14946 for (int i = 0; i < childCount; i++) { 14947 String childPackageName = ps.childPackageNames.get(i); 14948 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 14949 childInfo.removedPackage = childPackageName; 14950 outInfo.removedChildPackages.put(childPackageName, childInfo); 14951 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 14952 if (childPs != null) { 14953 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 14954 } 14955 } 14956 } 14957 } 14958 14959 boolean ret = false; 14960 if (isSystemApp(ps)) { 14961 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 14962 // When an updated system application is deleted we delete the existing resources 14963 // as well and fall back to existing code in system partition 14964 ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 14965 } else { 14966 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 14967 // Kill application pre-emptively especially for apps on sd. 14968 final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14969 if (killApp) { 14970 killApplication(packageName, ps.appId, "uninstall pkg"); 14971 } 14972 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles, 14973 outInfo, writeSettings, replacingPackage); 14974 } 14975 14976 // Take a note whether we deleted the package for all users 14977 if (outInfo != null) { 14978 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14979 if (outInfo.removedChildPackages != null) { 14980 synchronized (mPackages) { 14981 final int childCount = outInfo.removedChildPackages.size(); 14982 for (int i = 0; i < childCount; i++) { 14983 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 14984 if (childInfo != null) { 14985 childInfo.removedForAllUsers = mPackages.get( 14986 childInfo.removedPackage) == null; 14987 } 14988 } 14989 } 14990 } 14991 // If we uninstalled an update to a system app there may be some 14992 // child packages that appeared as they are declared in the system 14993 // app but were not declared in the update. 14994 if (isSystemApp(ps)) { 14995 synchronized (mPackages) { 14996 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 14997 final int childCount = (updatedPs.childPackageNames != null) 14998 ? updatedPs.childPackageNames.size() : 0; 14999 for (int i = 0; i < childCount; i++) { 15000 String childPackageName = updatedPs.childPackageNames.get(i); 15001 if (outInfo.removedChildPackages == null 15002 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15003 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15004 if (childPs == null) { 15005 continue; 15006 } 15007 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15008 installRes.name = childPackageName; 15009 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15010 installRes.pkg = mPackages.get(childPackageName); 15011 installRes.uid = childPs.pkg.applicationInfo.uid; 15012 if (outInfo.appearedChildPackages == null) { 15013 outInfo.appearedChildPackages = new ArrayMap<>(); 15014 } 15015 outInfo.appearedChildPackages.put(childPackageName, installRes); 15016 } 15017 } 15018 } 15019 } 15020 } 15021 15022 return ret; 15023 } 15024 15025 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15026 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15027 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15028 for (int nextUserId : userIds) { 15029 if (DEBUG_REMOVE) { 15030 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15031 } 15032 ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT, 15033 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15034 false /*hidden*/, false /*suspended*/, null, null, null, 15035 false /*blockUninstall*/, 15036 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15037 } 15038 } 15039 15040 private boolean clearPackageStateForUser(PackageSetting ps, int userId, 15041 PackageRemovedInfo outInfo) { 15042 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15043 : new int[] {userId}; 15044 for (int nextUserId : userIds) { 15045 if (DEBUG_REMOVE) { 15046 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15047 + nextUserId); 15048 } 15049 final int flags = StorageManager.FLAG_STORAGE_CE| StorageManager.FLAG_STORAGE_DE; 15050 try { 15051 mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags); 15052 } catch (InstallerException e) { 15053 Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e); 15054 return false; 15055 } 15056 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15057 schedulePackageCleaning(ps.name, nextUserId, false); 15058 synchronized (mPackages) { 15059 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15060 scheduleWritePackageRestrictionsLocked(nextUserId); 15061 } 15062 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15063 } 15064 } 15065 15066 if (outInfo != null) { 15067 outInfo.removedPackage = ps.name; 15068 outInfo.removedAppId = ps.appId; 15069 outInfo.removedUsers = userIds; 15070 } 15071 15072 return true; 15073 } 15074 15075 private final class ClearStorageConnection implements ServiceConnection { 15076 IMediaContainerService mContainerService; 15077 15078 @Override 15079 public void onServiceConnected(ComponentName name, IBinder service) { 15080 synchronized (this) { 15081 mContainerService = IMediaContainerService.Stub.asInterface(service); 15082 notifyAll(); 15083 } 15084 } 15085 15086 @Override 15087 public void onServiceDisconnected(ComponentName name) { 15088 } 15089 } 15090 15091 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15092 final boolean mounted; 15093 if (Environment.isExternalStorageEmulated()) { 15094 mounted = true; 15095 } else { 15096 final String status = Environment.getExternalStorageState(); 15097 15098 mounted = status.equals(Environment.MEDIA_MOUNTED) 15099 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15100 } 15101 15102 if (!mounted) { 15103 return; 15104 } 15105 15106 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15107 int[] users; 15108 if (userId == UserHandle.USER_ALL) { 15109 users = sUserManager.getUserIds(); 15110 } else { 15111 users = new int[] { userId }; 15112 } 15113 final ClearStorageConnection conn = new ClearStorageConnection(); 15114 if (mContext.bindServiceAsUser( 15115 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15116 try { 15117 for (int curUser : users) { 15118 long timeout = SystemClock.uptimeMillis() + 5000; 15119 synchronized (conn) { 15120 long now = SystemClock.uptimeMillis(); 15121 while (conn.mContainerService == null && now < timeout) { 15122 try { 15123 conn.wait(timeout - now); 15124 } catch (InterruptedException e) { 15125 } 15126 } 15127 } 15128 if (conn.mContainerService == null) { 15129 return; 15130 } 15131 15132 final UserEnvironment userEnv = new UserEnvironment(curUser); 15133 clearDirectory(conn.mContainerService, 15134 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15135 if (allData) { 15136 clearDirectory(conn.mContainerService, 15137 userEnv.buildExternalStorageAppDataDirs(packageName)); 15138 clearDirectory(conn.mContainerService, 15139 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15140 } 15141 } 15142 } finally { 15143 mContext.unbindService(conn); 15144 } 15145 } 15146 } 15147 15148 @Override 15149 public void clearApplicationUserData(final String packageName, 15150 final IPackageDataObserver observer, final int userId) { 15151 mContext.enforceCallingOrSelfPermission( 15152 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15153 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15154 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15155 // Queue up an async operation since the package deletion may take a little while. 15156 mHandler.post(new Runnable() { 15157 public void run() { 15158 mHandler.removeCallbacks(this); 15159 final boolean succeeded; 15160 synchronized (mInstallLock) { 15161 succeeded = clearApplicationUserDataLI(packageName, userId); 15162 } 15163 clearExternalStorageDataSync(packageName, userId, true); 15164 if (succeeded) { 15165 // invoke DeviceStorageMonitor's update method to clear any notifications 15166 DeviceStorageMonitorInternal 15167 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15168 if (dsm != null) { 15169 dsm.checkMemory(); 15170 } 15171 } 15172 if(observer != null) { 15173 try { 15174 observer.onRemoveCompleted(packageName, succeeded); 15175 } catch (RemoteException e) { 15176 Log.i(TAG, "Observer no longer exists."); 15177 } 15178 } //end if observer 15179 } //end run 15180 }); 15181 } 15182 15183 private boolean clearApplicationUserDataLI(String packageName, int userId) { 15184 if (packageName == null) { 15185 Slog.w(TAG, "Attempt to delete null packageName."); 15186 return false; 15187 } 15188 15189 // Try finding details about the requested package 15190 PackageParser.Package pkg; 15191 synchronized (mPackages) { 15192 pkg = mPackages.get(packageName); 15193 if (pkg == null) { 15194 final PackageSetting ps = mSettings.mPackages.get(packageName); 15195 if (ps != null) { 15196 pkg = ps.pkg; 15197 } 15198 } 15199 15200 if (pkg == null) { 15201 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15202 return false; 15203 } 15204 15205 PackageSetting ps = (PackageSetting) pkg.mExtras; 15206 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15207 } 15208 15209 // Always delete data directories for package, even if we found no other 15210 // record of app. This helps users recover from UID mismatches without 15211 // resorting to a full data wipe. 15212 // TODO: triage flags as part of 26466827 15213 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15214 try { 15215 mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags); 15216 } catch (InstallerException e) { 15217 Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e); 15218 return false; 15219 } 15220 15221 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15222 removeKeystoreDataIfNeeded(userId, appId); 15223 15224 // Create a native library symlink only if we have native libraries 15225 // and if the native libraries are 32 bit libraries. We do not provide 15226 // this symlink for 64 bit libraries. 15227 if (pkg.applicationInfo.primaryCpuAbi != null && 15228 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 15229 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 15230 try { 15231 mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 15232 nativeLibPath, userId); 15233 } catch (InstallerException e) { 15234 Slog.w(TAG, "Failed linking native library dir", e); 15235 return false; 15236 } 15237 } 15238 15239 return true; 15240 } 15241 15242 /** 15243 * Reverts user permission state changes (permissions and flags) in 15244 * all packages for a given user. 15245 * 15246 * @param userId The device user for which to do a reset. 15247 */ 15248 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15249 final int packageCount = mPackages.size(); 15250 for (int i = 0; i < packageCount; i++) { 15251 PackageParser.Package pkg = mPackages.valueAt(i); 15252 PackageSetting ps = (PackageSetting) pkg.mExtras; 15253 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15254 } 15255 } 15256 15257 /** 15258 * Reverts user permission state changes (permissions and flags). 15259 * 15260 * @param ps The package for which to reset. 15261 * @param userId The device user for which to do a reset. 15262 */ 15263 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15264 final PackageSetting ps, final int userId) { 15265 if (ps.pkg == null) { 15266 return; 15267 } 15268 15269 // These are flags that can change base on user actions. 15270 final int userSettableMask = FLAG_PERMISSION_USER_SET 15271 | FLAG_PERMISSION_USER_FIXED 15272 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15273 | FLAG_PERMISSION_REVIEW_REQUIRED; 15274 15275 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15276 | FLAG_PERMISSION_POLICY_FIXED; 15277 15278 boolean writeInstallPermissions = false; 15279 boolean writeRuntimePermissions = false; 15280 15281 final int permissionCount = ps.pkg.requestedPermissions.size(); 15282 for (int i = 0; i < permissionCount; i++) { 15283 String permission = ps.pkg.requestedPermissions.get(i); 15284 15285 BasePermission bp = mSettings.mPermissions.get(permission); 15286 if (bp == null) { 15287 continue; 15288 } 15289 15290 // If shared user we just reset the state to which only this app contributed. 15291 if (ps.sharedUser != null) { 15292 boolean used = false; 15293 final int packageCount = ps.sharedUser.packages.size(); 15294 for (int j = 0; j < packageCount; j++) { 15295 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15296 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15297 && pkg.pkg.requestedPermissions.contains(permission)) { 15298 used = true; 15299 break; 15300 } 15301 } 15302 if (used) { 15303 continue; 15304 } 15305 } 15306 15307 PermissionsState permissionsState = ps.getPermissionsState(); 15308 15309 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15310 15311 // Always clear the user settable flags. 15312 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15313 bp.name) != null; 15314 // If permission review is enabled and this is a legacy app, mark the 15315 // permission as requiring a review as this is the initial state. 15316 int flags = 0; 15317 if (Build.PERMISSIONS_REVIEW_REQUIRED 15318 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15319 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15320 } 15321 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15322 if (hasInstallState) { 15323 writeInstallPermissions = true; 15324 } else { 15325 writeRuntimePermissions = true; 15326 } 15327 } 15328 15329 // Below is only runtime permission handling. 15330 if (!bp.isRuntime()) { 15331 continue; 15332 } 15333 15334 // Never clobber system or policy. 15335 if ((oldFlags & policyOrSystemFlags) != 0) { 15336 continue; 15337 } 15338 15339 // If this permission was granted by default, make sure it is. 15340 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15341 if (permissionsState.grantRuntimePermission(bp, userId) 15342 != PERMISSION_OPERATION_FAILURE) { 15343 writeRuntimePermissions = true; 15344 } 15345 // If permission review is enabled the permissions for a legacy apps 15346 // are represented as constantly granted runtime ones, so don't revoke. 15347 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15348 // Otherwise, reset the permission. 15349 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15350 switch (revokeResult) { 15351 case PERMISSION_OPERATION_SUCCESS: { 15352 writeRuntimePermissions = true; 15353 } break; 15354 15355 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15356 writeRuntimePermissions = true; 15357 final int appId = ps.appId; 15358 mHandler.post(new Runnable() { 15359 @Override 15360 public void run() { 15361 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 15362 } 15363 }); 15364 } break; 15365 } 15366 } 15367 } 15368 15369 // Synchronously write as we are taking permissions away. 15370 if (writeRuntimePermissions) { 15371 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15372 } 15373 15374 // Synchronously write as we are taking permissions away. 15375 if (writeInstallPermissions) { 15376 mSettings.writeLPr(); 15377 } 15378 } 15379 15380 /** 15381 * Remove entries from the keystore daemon. Will only remove it if the 15382 * {@code appId} is valid. 15383 */ 15384 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 15385 if (appId < 0) { 15386 return; 15387 } 15388 15389 final KeyStore keyStore = KeyStore.getInstance(); 15390 if (keyStore != null) { 15391 if (userId == UserHandle.USER_ALL) { 15392 for (final int individual : sUserManager.getUserIds()) { 15393 keyStore.clearUid(UserHandle.getUid(individual, appId)); 15394 } 15395 } else { 15396 keyStore.clearUid(UserHandle.getUid(userId, appId)); 15397 } 15398 } else { 15399 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 15400 } 15401 } 15402 15403 @Override 15404 public void deleteApplicationCacheFiles(final String packageName, 15405 final IPackageDataObserver observer) { 15406 mContext.enforceCallingOrSelfPermission( 15407 android.Manifest.permission.DELETE_CACHE_FILES, null); 15408 // Queue up an async operation since the package deletion may take a little while. 15409 final int userId = UserHandle.getCallingUserId(); 15410 mHandler.post(new Runnable() { 15411 public void run() { 15412 mHandler.removeCallbacks(this); 15413 final boolean succeded; 15414 synchronized (mInstallLock) { 15415 succeded = deleteApplicationCacheFilesLI(packageName, userId); 15416 } 15417 clearExternalStorageDataSync(packageName, userId, false); 15418 if (observer != null) { 15419 try { 15420 observer.onRemoveCompleted(packageName, succeded); 15421 } catch (RemoteException e) { 15422 Log.i(TAG, "Observer no longer exists."); 15423 } 15424 } //end if observer 15425 } //end run 15426 }); 15427 } 15428 15429 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 15430 if (packageName == null) { 15431 Slog.w(TAG, "Attempt to delete null packageName."); 15432 return false; 15433 } 15434 PackageParser.Package p; 15435 synchronized (mPackages) { 15436 p = mPackages.get(packageName); 15437 } 15438 if (p == null) { 15439 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15440 return false; 15441 } 15442 final ApplicationInfo applicationInfo = p.applicationInfo; 15443 if (applicationInfo == null) { 15444 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15445 return false; 15446 } 15447 // TODO: triage flags as part of 26466827 15448 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15449 try { 15450 mInstaller.clearAppData(p.volumeUuid, packageName, userId, 15451 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 15452 } catch (InstallerException e) { 15453 Slog.w(TAG, "Couldn't remove cache files for package " 15454 + packageName + " u" + userId, e); 15455 return false; 15456 } 15457 return true; 15458 } 15459 15460 @Override 15461 public void getPackageSizeInfo(final String packageName, int userHandle, 15462 final IPackageStatsObserver observer) { 15463 mContext.enforceCallingOrSelfPermission( 15464 android.Manifest.permission.GET_PACKAGE_SIZE, null); 15465 if (packageName == null) { 15466 throw new IllegalArgumentException("Attempt to get size of null packageName"); 15467 } 15468 15469 PackageStats stats = new PackageStats(packageName, userHandle); 15470 15471 /* 15472 * Queue up an async operation since the package measurement may take a 15473 * little while. 15474 */ 15475 Message msg = mHandler.obtainMessage(INIT_COPY); 15476 msg.obj = new MeasureParams(stats, observer); 15477 mHandler.sendMessage(msg); 15478 } 15479 15480 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 15481 PackageStats pStats) { 15482 if (packageName == null) { 15483 Slog.w(TAG, "Attempt to get size of null packageName."); 15484 return false; 15485 } 15486 PackageParser.Package p; 15487 boolean dataOnly = false; 15488 String libDirRoot = null; 15489 String asecPath = null; 15490 PackageSetting ps = null; 15491 synchronized (mPackages) { 15492 p = mPackages.get(packageName); 15493 ps = mSettings.mPackages.get(packageName); 15494 if(p == null) { 15495 dataOnly = true; 15496 if((ps == null) || (ps.pkg == null)) { 15497 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 15498 return false; 15499 } 15500 p = ps.pkg; 15501 } 15502 if (ps != null) { 15503 libDirRoot = ps.legacyNativeLibraryPathString; 15504 } 15505 if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) { 15506 final long token = Binder.clearCallingIdentity(); 15507 try { 15508 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 15509 if (secureContainerId != null) { 15510 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 15511 } 15512 } finally { 15513 Binder.restoreCallingIdentity(token); 15514 } 15515 } 15516 } 15517 String publicSrcDir = null; 15518 if(!dataOnly) { 15519 final ApplicationInfo applicationInfo = p.applicationInfo; 15520 if (applicationInfo == null) { 15521 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 15522 return false; 15523 } 15524 if (p.isForwardLocked()) { 15525 publicSrcDir = applicationInfo.getBaseResourcePath(); 15526 } 15527 } 15528 // TODO: extend to measure size of split APKs 15529 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 15530 // not just the first level. 15531 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 15532 // just the primary. 15533 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 15534 15535 String apkPath; 15536 File packageDir = new File(p.codePath); 15537 15538 if (packageDir.isDirectory() && p.canHaveOatDir()) { 15539 apkPath = packageDir.getAbsolutePath(); 15540 // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice 15541 if (libDirRoot != null && libDirRoot.startsWith(apkPath)) { 15542 libDirRoot = null; 15543 } 15544 } else { 15545 apkPath = p.baseCodePath; 15546 } 15547 15548 // TODO: triage flags as part of 26466827 15549 final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE; 15550 try { 15551 mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath, 15552 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 15553 } catch (InstallerException e) { 15554 return false; 15555 } 15556 15557 // Fix-up for forward-locked applications in ASEC containers. 15558 if (!isExternal(p)) { 15559 pStats.codeSize += pStats.externalCodeSize; 15560 pStats.externalCodeSize = 0L; 15561 } 15562 15563 return true; 15564 } 15565 15566 private int getUidTargetSdkVersionLockedLPr(int uid) { 15567 Object obj = mSettings.getUserIdLPr(uid); 15568 if (obj instanceof SharedUserSetting) { 15569 final SharedUserSetting sus = (SharedUserSetting) obj; 15570 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 15571 final Iterator<PackageSetting> it = sus.packages.iterator(); 15572 while (it.hasNext()) { 15573 final PackageSetting ps = it.next(); 15574 if (ps.pkg != null) { 15575 int v = ps.pkg.applicationInfo.targetSdkVersion; 15576 if (v < vers) vers = v; 15577 } 15578 } 15579 return vers; 15580 } else if (obj instanceof PackageSetting) { 15581 final PackageSetting ps = (PackageSetting) obj; 15582 if (ps.pkg != null) { 15583 return ps.pkg.applicationInfo.targetSdkVersion; 15584 } 15585 } 15586 return Build.VERSION_CODES.CUR_DEVELOPMENT; 15587 } 15588 15589 @Override 15590 public void addPreferredActivity(IntentFilter filter, int match, 15591 ComponentName[] set, ComponentName activity, int userId) { 15592 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15593 "Adding preferred"); 15594 } 15595 15596 private void addPreferredActivityInternal(IntentFilter filter, int match, 15597 ComponentName[] set, ComponentName activity, boolean always, int userId, 15598 String opname) { 15599 // writer 15600 int callingUid = Binder.getCallingUid(); 15601 enforceCrossUserPermission(callingUid, userId, 15602 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 15603 if (filter.countActions() == 0) { 15604 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15605 return; 15606 } 15607 synchronized (mPackages) { 15608 if (mContext.checkCallingOrSelfPermission( 15609 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15610 != PackageManager.PERMISSION_GRANTED) { 15611 if (getUidTargetSdkVersionLockedLPr(callingUid) 15612 < Build.VERSION_CODES.FROYO) { 15613 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 15614 + callingUid); 15615 return; 15616 } 15617 mContext.enforceCallingOrSelfPermission( 15618 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15619 } 15620 15621 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 15622 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 15623 + userId + ":"); 15624 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15625 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 15626 scheduleWritePackageRestrictionsLocked(userId); 15627 } 15628 } 15629 15630 @Override 15631 public void replacePreferredActivity(IntentFilter filter, int match, 15632 ComponentName[] set, ComponentName activity, int userId) { 15633 if (filter.countActions() != 1) { 15634 throw new IllegalArgumentException( 15635 "replacePreferredActivity expects filter to have only 1 action."); 15636 } 15637 if (filter.countDataAuthorities() != 0 15638 || filter.countDataPaths() != 0 15639 || filter.countDataSchemes() > 1 15640 || filter.countDataTypes() != 0) { 15641 throw new IllegalArgumentException( 15642 "replacePreferredActivity expects filter to have no data authorities, " + 15643 "paths, or types; and at most one scheme."); 15644 } 15645 15646 final int callingUid = Binder.getCallingUid(); 15647 enforceCrossUserPermission(callingUid, userId, 15648 true /* requireFullPermission */, false /* checkShell */, 15649 "replace preferred activity"); 15650 synchronized (mPackages) { 15651 if (mContext.checkCallingOrSelfPermission( 15652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15653 != PackageManager.PERMISSION_GRANTED) { 15654 if (getUidTargetSdkVersionLockedLPr(callingUid) 15655 < Build.VERSION_CODES.FROYO) { 15656 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 15657 + Binder.getCallingUid()); 15658 return; 15659 } 15660 mContext.enforceCallingOrSelfPermission( 15661 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15662 } 15663 15664 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15665 if (pir != null) { 15666 // Get all of the existing entries that exactly match this filter. 15667 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 15668 if (existing != null && existing.size() == 1) { 15669 PreferredActivity cur = existing.get(0); 15670 if (DEBUG_PREFERRED) { 15671 Slog.i(TAG, "Checking replace of preferred:"); 15672 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15673 if (!cur.mPref.mAlways) { 15674 Slog.i(TAG, " -- CUR; not mAlways!"); 15675 } else { 15676 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 15677 Slog.i(TAG, " -- CUR: mSet=" 15678 + Arrays.toString(cur.mPref.mSetComponents)); 15679 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 15680 Slog.i(TAG, " -- NEW: mMatch=" 15681 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 15682 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 15683 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 15684 } 15685 } 15686 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 15687 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 15688 && cur.mPref.sameSet(set)) { 15689 // Setting the preferred activity to what it happens to be already 15690 if (DEBUG_PREFERRED) { 15691 Slog.i(TAG, "Replacing with same preferred activity " 15692 + cur.mPref.mShortComponent + " for user " 15693 + userId + ":"); 15694 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15695 } 15696 return; 15697 } 15698 } 15699 15700 if (existing != null) { 15701 if (DEBUG_PREFERRED) { 15702 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 15703 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15704 } 15705 for (int i = 0; i < existing.size(); i++) { 15706 PreferredActivity pa = existing.get(i); 15707 if (DEBUG_PREFERRED) { 15708 Slog.i(TAG, "Removing existing preferred activity " 15709 + pa.mPref.mComponent + ":"); 15710 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 15711 } 15712 pir.removeFilter(pa); 15713 } 15714 } 15715 } 15716 addPreferredActivityInternal(filter, match, set, activity, true, userId, 15717 "Replacing preferred"); 15718 } 15719 } 15720 15721 @Override 15722 public void clearPackagePreferredActivities(String packageName) { 15723 final int uid = Binder.getCallingUid(); 15724 // writer 15725 synchronized (mPackages) { 15726 PackageParser.Package pkg = mPackages.get(packageName); 15727 if (pkg == null || pkg.applicationInfo.uid != uid) { 15728 if (mContext.checkCallingOrSelfPermission( 15729 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 15730 != PackageManager.PERMISSION_GRANTED) { 15731 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 15732 < Build.VERSION_CODES.FROYO) { 15733 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 15734 + Binder.getCallingUid()); 15735 return; 15736 } 15737 mContext.enforceCallingOrSelfPermission( 15738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15739 } 15740 } 15741 15742 int user = UserHandle.getCallingUserId(); 15743 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 15744 scheduleWritePackageRestrictionsLocked(user); 15745 } 15746 } 15747 } 15748 15749 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15750 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 15751 ArrayList<PreferredActivity> removed = null; 15752 boolean changed = false; 15753 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 15754 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 15755 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 15756 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 15757 continue; 15758 } 15759 Iterator<PreferredActivity> it = pir.filterIterator(); 15760 while (it.hasNext()) { 15761 PreferredActivity pa = it.next(); 15762 // Mark entry for removal only if it matches the package name 15763 // and the entry is of type "always". 15764 if (packageName == null || 15765 (pa.mPref.mComponent.getPackageName().equals(packageName) 15766 && pa.mPref.mAlways)) { 15767 if (removed == null) { 15768 removed = new ArrayList<PreferredActivity>(); 15769 } 15770 removed.add(pa); 15771 } 15772 } 15773 if (removed != null) { 15774 for (int j=0; j<removed.size(); j++) { 15775 PreferredActivity pa = removed.get(j); 15776 pir.removeFilter(pa); 15777 } 15778 changed = true; 15779 } 15780 } 15781 return changed; 15782 } 15783 15784 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15785 private void clearIntentFilterVerificationsLPw(int userId) { 15786 final int packageCount = mPackages.size(); 15787 for (int i = 0; i < packageCount; i++) { 15788 PackageParser.Package pkg = mPackages.valueAt(i); 15789 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 15790 } 15791 } 15792 15793 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 15794 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 15795 if (userId == UserHandle.USER_ALL) { 15796 if (mSettings.removeIntentFilterVerificationLPw(packageName, 15797 sUserManager.getUserIds())) { 15798 for (int oneUserId : sUserManager.getUserIds()) { 15799 scheduleWritePackageRestrictionsLocked(oneUserId); 15800 } 15801 } 15802 } else { 15803 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 15804 scheduleWritePackageRestrictionsLocked(userId); 15805 } 15806 } 15807 } 15808 15809 void clearDefaultBrowserIfNeeded(String packageName) { 15810 for (int oneUserId : sUserManager.getUserIds()) { 15811 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 15812 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 15813 if (packageName.equals(defaultBrowserPackageName)) { 15814 setDefaultBrowserPackageName(null, oneUserId); 15815 } 15816 } 15817 } 15818 15819 @Override 15820 public void resetApplicationPreferences(int userId) { 15821 mContext.enforceCallingOrSelfPermission( 15822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 15823 // writer 15824 synchronized (mPackages) { 15825 final long identity = Binder.clearCallingIdentity(); 15826 try { 15827 clearPackagePreferredActivitiesLPw(null, userId); 15828 mSettings.applyDefaultPreferredAppsLPw(this, userId); 15829 // TODO: We have to reset the default SMS and Phone. This requires 15830 // significant refactoring to keep all default apps in the package 15831 // manager (cleaner but more work) or have the services provide 15832 // callbacks to the package manager to request a default app reset. 15833 applyFactoryDefaultBrowserLPw(userId); 15834 clearIntentFilterVerificationsLPw(userId); 15835 primeDomainVerificationsLPw(userId); 15836 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 15837 scheduleWritePackageRestrictionsLocked(userId); 15838 } finally { 15839 Binder.restoreCallingIdentity(identity); 15840 } 15841 } 15842 } 15843 15844 @Override 15845 public int getPreferredActivities(List<IntentFilter> outFilters, 15846 List<ComponentName> outActivities, String packageName) { 15847 15848 int num = 0; 15849 final int userId = UserHandle.getCallingUserId(); 15850 // reader 15851 synchronized (mPackages) { 15852 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 15853 if (pir != null) { 15854 final Iterator<PreferredActivity> it = pir.filterIterator(); 15855 while (it.hasNext()) { 15856 final PreferredActivity pa = it.next(); 15857 if (packageName == null 15858 || (pa.mPref.mComponent.getPackageName().equals(packageName) 15859 && pa.mPref.mAlways)) { 15860 if (outFilters != null) { 15861 outFilters.add(new IntentFilter(pa)); 15862 } 15863 if (outActivities != null) { 15864 outActivities.add(pa.mPref.mComponent); 15865 } 15866 } 15867 } 15868 } 15869 } 15870 15871 return num; 15872 } 15873 15874 @Override 15875 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 15876 int userId) { 15877 int callingUid = Binder.getCallingUid(); 15878 if (callingUid != Process.SYSTEM_UID) { 15879 throw new SecurityException( 15880 "addPersistentPreferredActivity can only be run by the system"); 15881 } 15882 if (filter.countActions() == 0) { 15883 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 15884 return; 15885 } 15886 synchronized (mPackages) { 15887 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 15888 ":"); 15889 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 15890 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 15891 new PersistentPreferredActivity(filter, activity)); 15892 scheduleWritePackageRestrictionsLocked(userId); 15893 } 15894 } 15895 15896 @Override 15897 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 15898 int callingUid = Binder.getCallingUid(); 15899 if (callingUid != Process.SYSTEM_UID) { 15900 throw new SecurityException( 15901 "clearPackagePersistentPreferredActivities can only be run by the system"); 15902 } 15903 ArrayList<PersistentPreferredActivity> removed = null; 15904 boolean changed = false; 15905 synchronized (mPackages) { 15906 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 15907 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 15908 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 15909 .valueAt(i); 15910 if (userId != thisUserId) { 15911 continue; 15912 } 15913 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 15914 while (it.hasNext()) { 15915 PersistentPreferredActivity ppa = it.next(); 15916 // Mark entry for removal only if it matches the package name. 15917 if (ppa.mComponent.getPackageName().equals(packageName)) { 15918 if (removed == null) { 15919 removed = new ArrayList<PersistentPreferredActivity>(); 15920 } 15921 removed.add(ppa); 15922 } 15923 } 15924 if (removed != null) { 15925 for (int j=0; j<removed.size(); j++) { 15926 PersistentPreferredActivity ppa = removed.get(j); 15927 ppir.removeFilter(ppa); 15928 } 15929 changed = true; 15930 } 15931 } 15932 15933 if (changed) { 15934 scheduleWritePackageRestrictionsLocked(userId); 15935 } 15936 } 15937 } 15938 15939 /** 15940 * Common machinery for picking apart a restored XML blob and passing 15941 * it to a caller-supplied functor to be applied to the running system. 15942 */ 15943 private void restoreFromXml(XmlPullParser parser, int userId, 15944 String expectedStartTag, BlobXmlRestorer functor) 15945 throws IOException, XmlPullParserException { 15946 int type; 15947 while ((type = parser.next()) != XmlPullParser.START_TAG 15948 && type != XmlPullParser.END_DOCUMENT) { 15949 } 15950 if (type != XmlPullParser.START_TAG) { 15951 // oops didn't find a start tag?! 15952 if (DEBUG_BACKUP) { 15953 Slog.e(TAG, "Didn't find start tag during restore"); 15954 } 15955 return; 15956 } 15957Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 15958 // this is supposed to be TAG_PREFERRED_BACKUP 15959 if (!expectedStartTag.equals(parser.getName())) { 15960 if (DEBUG_BACKUP) { 15961 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 15962 } 15963 return; 15964 } 15965 15966 // skip interfering stuff, then we're aligned with the backing implementation 15967 while ((type = parser.next()) == XmlPullParser.TEXT) { } 15968Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 15969 functor.apply(parser, userId); 15970 } 15971 15972 private interface BlobXmlRestorer { 15973 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 15974 } 15975 15976 /** 15977 * Non-Binder method, support for the backup/restore mechanism: write the 15978 * full set of preferred activities in its canonical XML format. Returns the 15979 * XML output as a byte array, or null if there is none. 15980 */ 15981 @Override 15982 public byte[] getPreferredActivityBackup(int userId) { 15983 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 15984 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 15985 } 15986 15987 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 15988 try { 15989 final XmlSerializer serializer = new FastXmlSerializer(); 15990 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 15991 serializer.startDocument(null, true); 15992 serializer.startTag(null, TAG_PREFERRED_BACKUP); 15993 15994 synchronized (mPackages) { 15995 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 15996 } 15997 15998 serializer.endTag(null, TAG_PREFERRED_BACKUP); 15999 serializer.endDocument(); 16000 serializer.flush(); 16001 } catch (Exception e) { 16002 if (DEBUG_BACKUP) { 16003 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16004 } 16005 return null; 16006 } 16007 16008 return dataStream.toByteArray(); 16009 } 16010 16011 @Override 16012 public void restorePreferredActivities(byte[] backup, int userId) { 16013 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16014 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16015 } 16016 16017 try { 16018 final XmlPullParser parser = Xml.newPullParser(); 16019 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16020 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16021 new BlobXmlRestorer() { 16022 @Override 16023 public void apply(XmlPullParser parser, int userId) 16024 throws XmlPullParserException, IOException { 16025 synchronized (mPackages) { 16026 mSettings.readPreferredActivitiesLPw(parser, userId); 16027 } 16028 } 16029 } ); 16030 } catch (Exception e) { 16031 if (DEBUG_BACKUP) { 16032 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16033 } 16034 } 16035 } 16036 16037 /** 16038 * Non-Binder method, support for the backup/restore mechanism: write the 16039 * default browser (etc) settings in its canonical XML format. Returns the default 16040 * browser XML representation as a byte array, or null if there is none. 16041 */ 16042 @Override 16043 public byte[] getDefaultAppsBackup(int userId) { 16044 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16045 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16046 } 16047 16048 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16049 try { 16050 final XmlSerializer serializer = new FastXmlSerializer(); 16051 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16052 serializer.startDocument(null, true); 16053 serializer.startTag(null, TAG_DEFAULT_APPS); 16054 16055 synchronized (mPackages) { 16056 mSettings.writeDefaultAppsLPr(serializer, userId); 16057 } 16058 16059 serializer.endTag(null, TAG_DEFAULT_APPS); 16060 serializer.endDocument(); 16061 serializer.flush(); 16062 } catch (Exception e) { 16063 if (DEBUG_BACKUP) { 16064 Slog.e(TAG, "Unable to write default apps for backup", e); 16065 } 16066 return null; 16067 } 16068 16069 return dataStream.toByteArray(); 16070 } 16071 16072 @Override 16073 public void restoreDefaultApps(byte[] backup, int userId) { 16074 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16075 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16076 } 16077 16078 try { 16079 final XmlPullParser parser = Xml.newPullParser(); 16080 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16081 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16082 new BlobXmlRestorer() { 16083 @Override 16084 public void apply(XmlPullParser parser, int userId) 16085 throws XmlPullParserException, IOException { 16086 synchronized (mPackages) { 16087 mSettings.readDefaultAppsLPw(parser, userId); 16088 } 16089 } 16090 } ); 16091 } catch (Exception e) { 16092 if (DEBUG_BACKUP) { 16093 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16094 } 16095 } 16096 } 16097 16098 @Override 16099 public byte[] getIntentFilterVerificationBackup(int userId) { 16100 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16101 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16102 } 16103 16104 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16105 try { 16106 final XmlSerializer serializer = new FastXmlSerializer(); 16107 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16108 serializer.startDocument(null, true); 16109 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16110 16111 synchronized (mPackages) { 16112 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16113 } 16114 16115 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16116 serializer.endDocument(); 16117 serializer.flush(); 16118 } catch (Exception e) { 16119 if (DEBUG_BACKUP) { 16120 Slog.e(TAG, "Unable to write default apps for backup", e); 16121 } 16122 return null; 16123 } 16124 16125 return dataStream.toByteArray(); 16126 } 16127 16128 @Override 16129 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16130 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16131 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16132 } 16133 16134 try { 16135 final XmlPullParser parser = Xml.newPullParser(); 16136 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16137 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16138 new BlobXmlRestorer() { 16139 @Override 16140 public void apply(XmlPullParser parser, int userId) 16141 throws XmlPullParserException, IOException { 16142 synchronized (mPackages) { 16143 mSettings.readAllDomainVerificationsLPr(parser, userId); 16144 mSettings.writeLPr(); 16145 } 16146 } 16147 } ); 16148 } catch (Exception e) { 16149 if (DEBUG_BACKUP) { 16150 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16151 } 16152 } 16153 } 16154 16155 @Override 16156 public byte[] getPermissionGrantBackup(int userId) { 16157 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16158 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16159 } 16160 16161 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16162 try { 16163 final XmlSerializer serializer = new FastXmlSerializer(); 16164 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16165 serializer.startDocument(null, true); 16166 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16167 16168 synchronized (mPackages) { 16169 serializeRuntimePermissionGrantsLPr(serializer, userId); 16170 } 16171 16172 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16173 serializer.endDocument(); 16174 serializer.flush(); 16175 } catch (Exception e) { 16176 if (DEBUG_BACKUP) { 16177 Slog.e(TAG, "Unable to write default apps for backup", e); 16178 } 16179 return null; 16180 } 16181 16182 return dataStream.toByteArray(); 16183 } 16184 16185 @Override 16186 public void restorePermissionGrants(byte[] backup, int userId) { 16187 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16188 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16189 } 16190 16191 try { 16192 final XmlPullParser parser = Xml.newPullParser(); 16193 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16194 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16195 new BlobXmlRestorer() { 16196 @Override 16197 public void apply(XmlPullParser parser, int userId) 16198 throws XmlPullParserException, IOException { 16199 synchronized (mPackages) { 16200 processRestoredPermissionGrantsLPr(parser, userId); 16201 } 16202 } 16203 } ); 16204 } catch (Exception e) { 16205 if (DEBUG_BACKUP) { 16206 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16207 } 16208 } 16209 } 16210 16211 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16212 throws IOException { 16213 serializer.startTag(null, TAG_ALL_GRANTS); 16214 16215 final int N = mSettings.mPackages.size(); 16216 for (int i = 0; i < N; i++) { 16217 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16218 boolean pkgGrantsKnown = false; 16219 16220 PermissionsState packagePerms = ps.getPermissionsState(); 16221 16222 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16223 final int grantFlags = state.getFlags(); 16224 // only look at grants that are not system/policy fixed 16225 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16226 final boolean isGranted = state.isGranted(); 16227 // And only back up the user-twiddled state bits 16228 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16229 final String packageName = mSettings.mPackages.keyAt(i); 16230 if (!pkgGrantsKnown) { 16231 serializer.startTag(null, TAG_GRANT); 16232 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16233 pkgGrantsKnown = true; 16234 } 16235 16236 final boolean userSet = 16237 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16238 final boolean userFixed = 16239 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16240 final boolean revoke = 16241 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16242 16243 serializer.startTag(null, TAG_PERMISSION); 16244 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16245 if (isGranted) { 16246 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16247 } 16248 if (userSet) { 16249 serializer.attribute(null, ATTR_USER_SET, "true"); 16250 } 16251 if (userFixed) { 16252 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16253 } 16254 if (revoke) { 16255 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16256 } 16257 serializer.endTag(null, TAG_PERMISSION); 16258 } 16259 } 16260 } 16261 16262 if (pkgGrantsKnown) { 16263 serializer.endTag(null, TAG_GRANT); 16264 } 16265 } 16266 16267 serializer.endTag(null, TAG_ALL_GRANTS); 16268 } 16269 16270 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16271 throws XmlPullParserException, IOException { 16272 String pkgName = null; 16273 int outerDepth = parser.getDepth(); 16274 int type; 16275 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16276 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16277 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16278 continue; 16279 } 16280 16281 final String tagName = parser.getName(); 16282 if (tagName.equals(TAG_GRANT)) { 16283 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16284 if (DEBUG_BACKUP) { 16285 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16286 } 16287 } else if (tagName.equals(TAG_PERMISSION)) { 16288 16289 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16290 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16291 16292 int newFlagSet = 0; 16293 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16294 newFlagSet |= FLAG_PERMISSION_USER_SET; 16295 } 16296 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16297 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16298 } 16299 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16300 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16301 } 16302 if (DEBUG_BACKUP) { 16303 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16304 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16305 } 16306 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16307 if (ps != null) { 16308 // Already installed so we apply the grant immediately 16309 if (DEBUG_BACKUP) { 16310 Slog.v(TAG, " + already installed; applying"); 16311 } 16312 PermissionsState perms = ps.getPermissionsState(); 16313 BasePermission bp = mSettings.mPermissions.get(permName); 16314 if (bp != null) { 16315 if (isGranted) { 16316 perms.grantRuntimePermission(bp, userId); 16317 } 16318 if (newFlagSet != 0) { 16319 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16320 } 16321 } 16322 } else { 16323 // Need to wait for post-restore install to apply the grant 16324 if (DEBUG_BACKUP) { 16325 Slog.v(TAG, " - not yet installed; saving for later"); 16326 } 16327 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16328 isGranted, newFlagSet, userId); 16329 } 16330 } else { 16331 PackageManagerService.reportSettingsProblem(Log.WARN, 16332 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16333 XmlUtils.skipCurrentTag(parser); 16334 } 16335 } 16336 16337 scheduleWriteSettingsLocked(); 16338 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16339 } 16340 16341 @Override 16342 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16343 int sourceUserId, int targetUserId, int flags) { 16344 mContext.enforceCallingOrSelfPermission( 16345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16346 int callingUid = Binder.getCallingUid(); 16347 enforceOwnerRights(ownerPackage, callingUid); 16348 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16349 if (intentFilter.countActions() == 0) { 16350 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16351 return; 16352 } 16353 synchronized (mPackages) { 16354 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16355 ownerPackage, targetUserId, flags); 16356 CrossProfileIntentResolver resolver = 16357 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16358 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16359 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16360 if (existing != null) { 16361 int size = existing.size(); 16362 for (int i = 0; i < size; i++) { 16363 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16364 return; 16365 } 16366 } 16367 } 16368 resolver.addFilter(newFilter); 16369 scheduleWritePackageRestrictionsLocked(sourceUserId); 16370 } 16371 } 16372 16373 @Override 16374 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16375 mContext.enforceCallingOrSelfPermission( 16376 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16377 int callingUid = Binder.getCallingUid(); 16378 enforceOwnerRights(ownerPackage, callingUid); 16379 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16380 synchronized (mPackages) { 16381 CrossProfileIntentResolver resolver = 16382 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16383 ArraySet<CrossProfileIntentFilter> set = 16384 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16385 for (CrossProfileIntentFilter filter : set) { 16386 if (filter.getOwnerPackage().equals(ownerPackage)) { 16387 resolver.removeFilter(filter); 16388 } 16389 } 16390 scheduleWritePackageRestrictionsLocked(sourceUserId); 16391 } 16392 } 16393 16394 // Enforcing that callingUid is owning pkg on userId 16395 private void enforceOwnerRights(String pkg, int callingUid) { 16396 // The system owns everything. 16397 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16398 return; 16399 } 16400 int callingUserId = UserHandle.getUserId(callingUid); 16401 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16402 if (pi == null) { 16403 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16404 + callingUserId); 16405 } 16406 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16407 throw new SecurityException("Calling uid " + callingUid 16408 + " does not own package " + pkg); 16409 } 16410 } 16411 16412 @Override 16413 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16414 Intent intent = new Intent(Intent.ACTION_MAIN); 16415 intent.addCategory(Intent.CATEGORY_HOME); 16416 16417 final int callingUserId = UserHandle.getCallingUserId(); 16418 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16419 PackageManager.GET_META_DATA, callingUserId); 16420 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16421 true, false, false, callingUserId); 16422 16423 allHomeCandidates.clear(); 16424 if (list != null) { 16425 for (ResolveInfo ri : list) { 16426 allHomeCandidates.add(ri); 16427 } 16428 } 16429 return (preferred == null || preferred.activityInfo == null) 16430 ? null 16431 : new ComponentName(preferred.activityInfo.packageName, 16432 preferred.activityInfo.name); 16433 } 16434 16435 @Override 16436 public void setApplicationEnabledSetting(String appPackageName, 16437 int newState, int flags, int userId, String callingPackage) { 16438 if (!sUserManager.exists(userId)) return; 16439 if (callingPackage == null) { 16440 callingPackage = Integer.toString(Binder.getCallingUid()); 16441 } 16442 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 16443 } 16444 16445 @Override 16446 public void setComponentEnabledSetting(ComponentName componentName, 16447 int newState, int flags, int userId) { 16448 if (!sUserManager.exists(userId)) return; 16449 setEnabledSetting(componentName.getPackageName(), 16450 componentName.getClassName(), newState, flags, userId, null); 16451 } 16452 16453 private void setEnabledSetting(final String packageName, String className, int newState, 16454 final int flags, int userId, String callingPackage) { 16455 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 16456 || newState == COMPONENT_ENABLED_STATE_ENABLED 16457 || newState == COMPONENT_ENABLED_STATE_DISABLED 16458 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 16459 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 16460 throw new IllegalArgumentException("Invalid new component state: " 16461 + newState); 16462 } 16463 PackageSetting pkgSetting; 16464 final int uid = Binder.getCallingUid(); 16465 final int permission = mContext.checkCallingOrSelfPermission( 16466 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16467 enforceCrossUserPermission(uid, userId, 16468 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 16469 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16470 boolean sendNow = false; 16471 boolean isApp = (className == null); 16472 String componentName = isApp ? packageName : className; 16473 int packageUid = -1; 16474 ArrayList<String> components; 16475 16476 // writer 16477 synchronized (mPackages) { 16478 pkgSetting = mSettings.mPackages.get(packageName); 16479 if (pkgSetting == null) { 16480 if (className == null) { 16481 throw new IllegalArgumentException("Unknown package: " + packageName); 16482 } 16483 throw new IllegalArgumentException( 16484 "Unknown component: " + packageName + "/" + className); 16485 } 16486 // Allow root and verify that userId is not being specified by a different user 16487 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 16488 throw new SecurityException( 16489 "Permission Denial: attempt to change component state from pid=" 16490 + Binder.getCallingPid() 16491 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 16492 } 16493 if (className == null) { 16494 // We're dealing with an application/package level state change 16495 if (pkgSetting.getEnabled(userId) == newState) { 16496 // Nothing to do 16497 return; 16498 } 16499 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 16500 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 16501 // Don't care about who enables an app. 16502 callingPackage = null; 16503 } 16504 pkgSetting.setEnabled(newState, userId, callingPackage); 16505 // pkgSetting.pkg.mSetEnabled = newState; 16506 } else { 16507 // We're dealing with a component level state change 16508 // First, verify that this is a valid class name. 16509 PackageParser.Package pkg = pkgSetting.pkg; 16510 if (pkg == null || !pkg.hasComponentClassName(className)) { 16511 if (pkg != null && 16512 pkg.applicationInfo.targetSdkVersion >= 16513 Build.VERSION_CODES.JELLY_BEAN) { 16514 throw new IllegalArgumentException("Component class " + className 16515 + " does not exist in " + packageName); 16516 } else { 16517 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 16518 + className + " does not exist in " + packageName); 16519 } 16520 } 16521 switch (newState) { 16522 case COMPONENT_ENABLED_STATE_ENABLED: 16523 if (!pkgSetting.enableComponentLPw(className, userId)) { 16524 return; 16525 } 16526 break; 16527 case COMPONENT_ENABLED_STATE_DISABLED: 16528 if (!pkgSetting.disableComponentLPw(className, userId)) { 16529 return; 16530 } 16531 break; 16532 case COMPONENT_ENABLED_STATE_DEFAULT: 16533 if (!pkgSetting.restoreComponentLPw(className, userId)) { 16534 return; 16535 } 16536 break; 16537 default: 16538 Slog.e(TAG, "Invalid new component state: " + newState); 16539 return; 16540 } 16541 } 16542 scheduleWritePackageRestrictionsLocked(userId); 16543 components = mPendingBroadcasts.get(userId, packageName); 16544 final boolean newPackage = components == null; 16545 if (newPackage) { 16546 components = new ArrayList<String>(); 16547 } 16548 if (!components.contains(componentName)) { 16549 components.add(componentName); 16550 } 16551 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 16552 sendNow = true; 16553 // Purge entry from pending broadcast list if another one exists already 16554 // since we are sending one right away. 16555 mPendingBroadcasts.remove(userId, packageName); 16556 } else { 16557 if (newPackage) { 16558 mPendingBroadcasts.put(userId, packageName, components); 16559 } 16560 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 16561 // Schedule a message 16562 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 16563 } 16564 } 16565 } 16566 16567 long callingId = Binder.clearCallingIdentity(); 16568 try { 16569 if (sendNow) { 16570 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 16571 sendPackageChangedBroadcast(packageName, 16572 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 16573 } 16574 } finally { 16575 Binder.restoreCallingIdentity(callingId); 16576 } 16577 } 16578 16579 private void sendPackageChangedBroadcast(String packageName, 16580 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 16581 if (DEBUG_INSTALL) 16582 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 16583 + componentNames); 16584 Bundle extras = new Bundle(4); 16585 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 16586 String nameList[] = new String[componentNames.size()]; 16587 componentNames.toArray(nameList); 16588 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 16589 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 16590 extras.putInt(Intent.EXTRA_UID, packageUid); 16591 // If this is not reporting a change of the overall package, then only send it 16592 // to registered receivers. We don't want to launch a swath of apps for every 16593 // little component state change. 16594 final int flags = !componentNames.contains(packageName) 16595 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 16596 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 16597 new int[] {UserHandle.getUserId(packageUid)}); 16598 } 16599 16600 @Override 16601 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 16602 if (!sUserManager.exists(userId)) return; 16603 final int uid = Binder.getCallingUid(); 16604 final int permission = mContext.checkCallingOrSelfPermission( 16605 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 16606 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 16607 enforceCrossUserPermission(uid, userId, 16608 true /* requireFullPermission */, true /* checkShell */, "stop package"); 16609 // writer 16610 synchronized (mPackages) { 16611 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 16612 allowedByPermission, uid, userId)) { 16613 scheduleWritePackageRestrictionsLocked(userId); 16614 } 16615 } 16616 } 16617 16618 @Override 16619 public String getInstallerPackageName(String packageName) { 16620 // reader 16621 synchronized (mPackages) { 16622 return mSettings.getInstallerPackageNameLPr(packageName); 16623 } 16624 } 16625 16626 @Override 16627 public int getApplicationEnabledSetting(String packageName, int userId) { 16628 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16629 int uid = Binder.getCallingUid(); 16630 enforceCrossUserPermission(uid, userId, 16631 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 16632 // reader 16633 synchronized (mPackages) { 16634 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 16635 } 16636 } 16637 16638 @Override 16639 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 16640 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 16641 int uid = Binder.getCallingUid(); 16642 enforceCrossUserPermission(uid, userId, 16643 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 16644 // reader 16645 synchronized (mPackages) { 16646 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 16647 } 16648 } 16649 16650 @Override 16651 public void enterSafeMode() { 16652 enforceSystemOrRoot("Only the system can request entering safe mode"); 16653 16654 if (!mSystemReady) { 16655 mSafeMode = true; 16656 } 16657 } 16658 16659 @Override 16660 public void systemReady() { 16661 mSystemReady = true; 16662 16663 // Read the compatibilty setting when the system is ready. 16664 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 16665 mContext.getContentResolver(), 16666 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 16667 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 16668 if (DEBUG_SETTINGS) { 16669 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 16670 } 16671 16672 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 16673 16674 synchronized (mPackages) { 16675 // Verify that all of the preferred activity components actually 16676 // exist. It is possible for applications to be updated and at 16677 // that point remove a previously declared activity component that 16678 // had been set as a preferred activity. We try to clean this up 16679 // the next time we encounter that preferred activity, but it is 16680 // possible for the user flow to never be able to return to that 16681 // situation so here we do a sanity check to make sure we haven't 16682 // left any junk around. 16683 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 16684 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16685 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16686 removed.clear(); 16687 for (PreferredActivity pa : pir.filterSet()) { 16688 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 16689 removed.add(pa); 16690 } 16691 } 16692 if (removed.size() > 0) { 16693 for (int r=0; r<removed.size(); r++) { 16694 PreferredActivity pa = removed.get(r); 16695 Slog.w(TAG, "Removing dangling preferred activity: " 16696 + pa.mPref.mComponent); 16697 pir.removeFilter(pa); 16698 } 16699 mSettings.writePackageRestrictionsLPr( 16700 mSettings.mPreferredActivities.keyAt(i)); 16701 } 16702 } 16703 16704 for (int userId : UserManagerService.getInstance().getUserIds()) { 16705 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 16706 grantPermissionsUserIds = ArrayUtils.appendInt( 16707 grantPermissionsUserIds, userId); 16708 } 16709 } 16710 } 16711 sUserManager.systemReady(); 16712 16713 // If we upgraded grant all default permissions before kicking off. 16714 for (int userId : grantPermissionsUserIds) { 16715 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 16716 } 16717 16718 // Kick off any messages waiting for system ready 16719 if (mPostSystemReadyMessages != null) { 16720 for (Message msg : mPostSystemReadyMessages) { 16721 msg.sendToTarget(); 16722 } 16723 mPostSystemReadyMessages = null; 16724 } 16725 16726 // Watch for external volumes that come and go over time 16727 final StorageManager storage = mContext.getSystemService(StorageManager.class); 16728 storage.registerListener(mStorageListener); 16729 16730 mInstallerService.systemReady(); 16731 mPackageDexOptimizer.systemReady(); 16732 16733 MountServiceInternal mountServiceInternal = LocalServices.getService( 16734 MountServiceInternal.class); 16735 mountServiceInternal.addExternalStoragePolicy( 16736 new MountServiceInternal.ExternalStorageMountPolicy() { 16737 @Override 16738 public int getMountMode(int uid, String packageName) { 16739 if (Process.isIsolated(uid)) { 16740 return Zygote.MOUNT_EXTERNAL_NONE; 16741 } 16742 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 16743 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16744 } 16745 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16746 return Zygote.MOUNT_EXTERNAL_DEFAULT; 16747 } 16748 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 16749 return Zygote.MOUNT_EXTERNAL_READ; 16750 } 16751 return Zygote.MOUNT_EXTERNAL_WRITE; 16752 } 16753 16754 @Override 16755 public boolean hasExternalStorage(int uid, String packageName) { 16756 return true; 16757 } 16758 }); 16759 } 16760 16761 @Override 16762 public boolean isSafeMode() { 16763 return mSafeMode; 16764 } 16765 16766 @Override 16767 public boolean hasSystemUidErrors() { 16768 return mHasSystemUidErrors; 16769 } 16770 16771 static String arrayToString(int[] array) { 16772 StringBuffer buf = new StringBuffer(128); 16773 buf.append('['); 16774 if (array != null) { 16775 for (int i=0; i<array.length; i++) { 16776 if (i > 0) buf.append(", "); 16777 buf.append(array[i]); 16778 } 16779 } 16780 buf.append(']'); 16781 return buf.toString(); 16782 } 16783 16784 static class DumpState { 16785 public static final int DUMP_LIBS = 1 << 0; 16786 public static final int DUMP_FEATURES = 1 << 1; 16787 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 16788 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 16789 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 16790 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 16791 public static final int DUMP_PERMISSIONS = 1 << 6; 16792 public static final int DUMP_PACKAGES = 1 << 7; 16793 public static final int DUMP_SHARED_USERS = 1 << 8; 16794 public static final int DUMP_MESSAGES = 1 << 9; 16795 public static final int DUMP_PROVIDERS = 1 << 10; 16796 public static final int DUMP_VERIFIERS = 1 << 11; 16797 public static final int DUMP_PREFERRED = 1 << 12; 16798 public static final int DUMP_PREFERRED_XML = 1 << 13; 16799 public static final int DUMP_KEYSETS = 1 << 14; 16800 public static final int DUMP_VERSION = 1 << 15; 16801 public static final int DUMP_INSTALLS = 1 << 16; 16802 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 16803 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 16804 16805 public static final int OPTION_SHOW_FILTERS = 1 << 0; 16806 16807 private int mTypes; 16808 16809 private int mOptions; 16810 16811 private boolean mTitlePrinted; 16812 16813 private SharedUserSetting mSharedUser; 16814 16815 public boolean isDumping(int type) { 16816 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 16817 return true; 16818 } 16819 16820 return (mTypes & type) != 0; 16821 } 16822 16823 public void setDump(int type) { 16824 mTypes |= type; 16825 } 16826 16827 public boolean isOptionEnabled(int option) { 16828 return (mOptions & option) != 0; 16829 } 16830 16831 public void setOptionEnabled(int option) { 16832 mOptions |= option; 16833 } 16834 16835 public boolean onTitlePrinted() { 16836 final boolean printed = mTitlePrinted; 16837 mTitlePrinted = true; 16838 return printed; 16839 } 16840 16841 public boolean getTitlePrinted() { 16842 return mTitlePrinted; 16843 } 16844 16845 public void setTitlePrinted(boolean enabled) { 16846 mTitlePrinted = enabled; 16847 } 16848 16849 public SharedUserSetting getSharedUser() { 16850 return mSharedUser; 16851 } 16852 16853 public void setSharedUser(SharedUserSetting user) { 16854 mSharedUser = user; 16855 } 16856 } 16857 16858 @Override 16859 public void onShellCommand(FileDescriptor in, FileDescriptor out, 16860 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 16861 (new PackageManagerShellCommand(this)).exec( 16862 this, in, out, err, args, resultReceiver); 16863 } 16864 16865 @Override 16866 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 16867 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 16868 != PackageManager.PERMISSION_GRANTED) { 16869 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 16870 + Binder.getCallingPid() 16871 + ", uid=" + Binder.getCallingUid() 16872 + " without permission " 16873 + android.Manifest.permission.DUMP); 16874 return; 16875 } 16876 16877 DumpState dumpState = new DumpState(); 16878 boolean fullPreferred = false; 16879 boolean checkin = false; 16880 16881 String packageName = null; 16882 ArraySet<String> permissionNames = null; 16883 16884 int opti = 0; 16885 while (opti < args.length) { 16886 String opt = args[opti]; 16887 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 16888 break; 16889 } 16890 opti++; 16891 16892 if ("-a".equals(opt)) { 16893 // Right now we only know how to print all. 16894 } else if ("-h".equals(opt)) { 16895 pw.println("Package manager dump options:"); 16896 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 16897 pw.println(" --checkin: dump for a checkin"); 16898 pw.println(" -f: print details of intent filters"); 16899 pw.println(" -h: print this help"); 16900 pw.println(" cmd may be one of:"); 16901 pw.println(" l[ibraries]: list known shared libraries"); 16902 pw.println(" f[eatures]: list device features"); 16903 pw.println(" k[eysets]: print known keysets"); 16904 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 16905 pw.println(" perm[issions]: dump permissions"); 16906 pw.println(" permission [name ...]: dump declaration and use of given permission"); 16907 pw.println(" pref[erred]: print preferred package settings"); 16908 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 16909 pw.println(" prov[iders]: dump content providers"); 16910 pw.println(" p[ackages]: dump installed packages"); 16911 pw.println(" s[hared-users]: dump shared user IDs"); 16912 pw.println(" m[essages]: print collected runtime messages"); 16913 pw.println(" v[erifiers]: print package verifier info"); 16914 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 16915 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 16916 pw.println(" version: print database version info"); 16917 pw.println(" write: write current settings now"); 16918 pw.println(" installs: details about install sessions"); 16919 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 16920 pw.println(" <package.name>: info about given package"); 16921 return; 16922 } else if ("--checkin".equals(opt)) { 16923 checkin = true; 16924 } else if ("-f".equals(opt)) { 16925 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16926 } else { 16927 pw.println("Unknown argument: " + opt + "; use -h for help"); 16928 } 16929 } 16930 16931 // Is the caller requesting to dump a particular piece of data? 16932 if (opti < args.length) { 16933 String cmd = args[opti]; 16934 opti++; 16935 // Is this a package name? 16936 if ("android".equals(cmd) || cmd.contains(".")) { 16937 packageName = cmd; 16938 // When dumping a single package, we always dump all of its 16939 // filter information since the amount of data will be reasonable. 16940 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 16941 } else if ("check-permission".equals(cmd)) { 16942 if (opti >= args.length) { 16943 pw.println("Error: check-permission missing permission argument"); 16944 return; 16945 } 16946 String perm = args[opti]; 16947 opti++; 16948 if (opti >= args.length) { 16949 pw.println("Error: check-permission missing package argument"); 16950 return; 16951 } 16952 String pkg = args[opti]; 16953 opti++; 16954 int user = UserHandle.getUserId(Binder.getCallingUid()); 16955 if (opti < args.length) { 16956 try { 16957 user = Integer.parseInt(args[opti]); 16958 } catch (NumberFormatException e) { 16959 pw.println("Error: check-permission user argument is not a number: " 16960 + args[opti]); 16961 return; 16962 } 16963 } 16964 pw.println(checkPermission(perm, pkg, user)); 16965 return; 16966 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 16967 dumpState.setDump(DumpState.DUMP_LIBS); 16968 } else if ("f".equals(cmd) || "features".equals(cmd)) { 16969 dumpState.setDump(DumpState.DUMP_FEATURES); 16970 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 16971 if (opti >= args.length) { 16972 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 16973 | DumpState.DUMP_SERVICE_RESOLVERS 16974 | DumpState.DUMP_RECEIVER_RESOLVERS 16975 | DumpState.DUMP_CONTENT_RESOLVERS); 16976 } else { 16977 while (opti < args.length) { 16978 String name = args[opti]; 16979 if ("a".equals(name) || "activity".equals(name)) { 16980 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 16981 } else if ("s".equals(name) || "service".equals(name)) { 16982 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 16983 } else if ("r".equals(name) || "receiver".equals(name)) { 16984 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 16985 } else if ("c".equals(name) || "content".equals(name)) { 16986 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 16987 } else { 16988 pw.println("Error: unknown resolver table type: " + name); 16989 return; 16990 } 16991 opti++; 16992 } 16993 } 16994 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 16995 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 16996 } else if ("permission".equals(cmd)) { 16997 if (opti >= args.length) { 16998 pw.println("Error: permission requires permission name"); 16999 return; 17000 } 17001 permissionNames = new ArraySet<>(); 17002 while (opti < args.length) { 17003 permissionNames.add(args[opti]); 17004 opti++; 17005 } 17006 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17007 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17008 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17009 dumpState.setDump(DumpState.DUMP_PREFERRED); 17010 } else if ("preferred-xml".equals(cmd)) { 17011 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17012 if (opti < args.length && "--full".equals(args[opti])) { 17013 fullPreferred = true; 17014 opti++; 17015 } 17016 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17017 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17018 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17019 dumpState.setDump(DumpState.DUMP_PACKAGES); 17020 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17021 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17022 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17023 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17024 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17025 dumpState.setDump(DumpState.DUMP_MESSAGES); 17026 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17027 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17028 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17029 || "intent-filter-verifiers".equals(cmd)) { 17030 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17031 } else if ("version".equals(cmd)) { 17032 dumpState.setDump(DumpState.DUMP_VERSION); 17033 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17034 dumpState.setDump(DumpState.DUMP_KEYSETS); 17035 } else if ("installs".equals(cmd)) { 17036 dumpState.setDump(DumpState.DUMP_INSTALLS); 17037 } else if ("write".equals(cmd)) { 17038 synchronized (mPackages) { 17039 mSettings.writeLPr(); 17040 pw.println("Settings written."); 17041 return; 17042 } 17043 } 17044 } 17045 17046 if (checkin) { 17047 pw.println("vers,1"); 17048 } 17049 17050 // reader 17051 synchronized (mPackages) { 17052 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17053 if (!checkin) { 17054 if (dumpState.onTitlePrinted()) 17055 pw.println(); 17056 pw.println("Database versions:"); 17057 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17058 } 17059 } 17060 17061 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17062 if (!checkin) { 17063 if (dumpState.onTitlePrinted()) 17064 pw.println(); 17065 pw.println("Verifiers:"); 17066 pw.print(" Required: "); 17067 pw.print(mRequiredVerifierPackage); 17068 pw.print(" (uid="); 17069 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17070 UserHandle.USER_SYSTEM)); 17071 pw.println(")"); 17072 } else if (mRequiredVerifierPackage != null) { 17073 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17074 pw.print(","); 17075 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17076 UserHandle.USER_SYSTEM)); 17077 } 17078 } 17079 17080 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17081 packageName == null) { 17082 if (mIntentFilterVerifierComponent != null) { 17083 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17084 if (!checkin) { 17085 if (dumpState.onTitlePrinted()) 17086 pw.println(); 17087 pw.println("Intent Filter Verifier:"); 17088 pw.print(" Using: "); 17089 pw.print(verifierPackageName); 17090 pw.print(" (uid="); 17091 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17092 UserHandle.USER_SYSTEM)); 17093 pw.println(")"); 17094 } else if (verifierPackageName != null) { 17095 pw.print("ifv,"); pw.print(verifierPackageName); 17096 pw.print(","); 17097 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17098 UserHandle.USER_SYSTEM)); 17099 } 17100 } else { 17101 pw.println(); 17102 pw.println("No Intent Filter Verifier available!"); 17103 } 17104 } 17105 17106 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17107 boolean printedHeader = false; 17108 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17109 while (it.hasNext()) { 17110 String name = it.next(); 17111 SharedLibraryEntry ent = mSharedLibraries.get(name); 17112 if (!checkin) { 17113 if (!printedHeader) { 17114 if (dumpState.onTitlePrinted()) 17115 pw.println(); 17116 pw.println("Libraries:"); 17117 printedHeader = true; 17118 } 17119 pw.print(" "); 17120 } else { 17121 pw.print("lib,"); 17122 } 17123 pw.print(name); 17124 if (!checkin) { 17125 pw.print(" -> "); 17126 } 17127 if (ent.path != null) { 17128 if (!checkin) { 17129 pw.print("(jar) "); 17130 pw.print(ent.path); 17131 } else { 17132 pw.print(",jar,"); 17133 pw.print(ent.path); 17134 } 17135 } else { 17136 if (!checkin) { 17137 pw.print("(apk) "); 17138 pw.print(ent.apk); 17139 } else { 17140 pw.print(",apk,"); 17141 pw.print(ent.apk); 17142 } 17143 } 17144 pw.println(); 17145 } 17146 } 17147 17148 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17149 if (dumpState.onTitlePrinted()) 17150 pw.println(); 17151 if (!checkin) { 17152 pw.println("Features:"); 17153 } 17154 17155 for (FeatureInfo feat : mAvailableFeatures.values()) { 17156 if (checkin) { 17157 pw.print("feat,"); 17158 pw.print(feat.name); 17159 pw.print(","); 17160 pw.println(feat.version); 17161 } else { 17162 pw.print(" "); 17163 pw.print(feat.name); 17164 if (feat.version > 0) { 17165 pw.print(" version="); 17166 pw.print(feat.version); 17167 } 17168 pw.println(); 17169 } 17170 } 17171 } 17172 17173 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17174 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17175 : "Activity Resolver Table:", " ", packageName, 17176 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17177 dumpState.setTitlePrinted(true); 17178 } 17179 } 17180 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17181 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17182 : "Receiver Resolver Table:", " ", packageName, 17183 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17184 dumpState.setTitlePrinted(true); 17185 } 17186 } 17187 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17188 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17189 : "Service Resolver Table:", " ", packageName, 17190 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17191 dumpState.setTitlePrinted(true); 17192 } 17193 } 17194 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17195 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17196 : "Provider Resolver Table:", " ", packageName, 17197 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17198 dumpState.setTitlePrinted(true); 17199 } 17200 } 17201 17202 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17203 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17204 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17205 int user = mSettings.mPreferredActivities.keyAt(i); 17206 if (pir.dump(pw, 17207 dumpState.getTitlePrinted() 17208 ? "\nPreferred Activities User " + user + ":" 17209 : "Preferred Activities User " + user + ":", " ", 17210 packageName, true, false)) { 17211 dumpState.setTitlePrinted(true); 17212 } 17213 } 17214 } 17215 17216 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17217 pw.flush(); 17218 FileOutputStream fout = new FileOutputStream(fd); 17219 BufferedOutputStream str = new BufferedOutputStream(fout); 17220 XmlSerializer serializer = new FastXmlSerializer(); 17221 try { 17222 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17223 serializer.startDocument(null, true); 17224 serializer.setFeature( 17225 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17226 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17227 serializer.endDocument(); 17228 serializer.flush(); 17229 } catch (IllegalArgumentException e) { 17230 pw.println("Failed writing: " + e); 17231 } catch (IllegalStateException e) { 17232 pw.println("Failed writing: " + e); 17233 } catch (IOException e) { 17234 pw.println("Failed writing: " + e); 17235 } 17236 } 17237 17238 if (!checkin 17239 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17240 && packageName == null) { 17241 pw.println(); 17242 int count = mSettings.mPackages.size(); 17243 if (count == 0) { 17244 pw.println("No applications!"); 17245 pw.println(); 17246 } else { 17247 final String prefix = " "; 17248 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17249 if (allPackageSettings.size() == 0) { 17250 pw.println("No domain preferred apps!"); 17251 pw.println(); 17252 } else { 17253 pw.println("App verification status:"); 17254 pw.println(); 17255 count = 0; 17256 for (PackageSetting ps : allPackageSettings) { 17257 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17258 if (ivi == null || ivi.getPackageName() == null) continue; 17259 pw.println(prefix + "Package: " + ivi.getPackageName()); 17260 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17261 pw.println(prefix + "Status: " + ivi.getStatusString()); 17262 pw.println(); 17263 count++; 17264 } 17265 if (count == 0) { 17266 pw.println(prefix + "No app verification established."); 17267 pw.println(); 17268 } 17269 for (int userId : sUserManager.getUserIds()) { 17270 pw.println("App linkages for user " + userId + ":"); 17271 pw.println(); 17272 count = 0; 17273 for (PackageSetting ps : allPackageSettings) { 17274 final long status = ps.getDomainVerificationStatusForUser(userId); 17275 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17276 continue; 17277 } 17278 pw.println(prefix + "Package: " + ps.name); 17279 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17280 String statusStr = IntentFilterVerificationInfo. 17281 getStatusStringFromValue(status); 17282 pw.println(prefix + "Status: " + statusStr); 17283 pw.println(); 17284 count++; 17285 } 17286 if (count == 0) { 17287 pw.println(prefix + "No configured app linkages."); 17288 pw.println(); 17289 } 17290 } 17291 } 17292 } 17293 } 17294 17295 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17296 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17297 if (packageName == null && permissionNames == null) { 17298 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17299 if (iperm == 0) { 17300 if (dumpState.onTitlePrinted()) 17301 pw.println(); 17302 pw.println("AppOp Permissions:"); 17303 } 17304 pw.print(" AppOp Permission "); 17305 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17306 pw.println(":"); 17307 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17308 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17309 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17310 } 17311 } 17312 } 17313 } 17314 17315 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17316 boolean printedSomething = false; 17317 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17318 if (packageName != null && !packageName.equals(p.info.packageName)) { 17319 continue; 17320 } 17321 if (!printedSomething) { 17322 if (dumpState.onTitlePrinted()) 17323 pw.println(); 17324 pw.println("Registered ContentProviders:"); 17325 printedSomething = true; 17326 } 17327 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17328 pw.print(" "); pw.println(p.toString()); 17329 } 17330 printedSomething = false; 17331 for (Map.Entry<String, PackageParser.Provider> entry : 17332 mProvidersByAuthority.entrySet()) { 17333 PackageParser.Provider p = entry.getValue(); 17334 if (packageName != null && !packageName.equals(p.info.packageName)) { 17335 continue; 17336 } 17337 if (!printedSomething) { 17338 if (dumpState.onTitlePrinted()) 17339 pw.println(); 17340 pw.println("ContentProvider Authorities:"); 17341 printedSomething = true; 17342 } 17343 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17344 pw.print(" "); pw.println(p.toString()); 17345 if (p.info != null && p.info.applicationInfo != null) { 17346 final String appInfo = p.info.applicationInfo.toString(); 17347 pw.print(" applicationInfo="); pw.println(appInfo); 17348 } 17349 } 17350 } 17351 17352 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17353 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17354 } 17355 17356 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17357 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17358 } 17359 17360 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17361 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17362 } 17363 17364 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17365 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17366 } 17367 17368 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17369 // XXX should handle packageName != null by dumping only install data that 17370 // the given package is involved with. 17371 if (dumpState.onTitlePrinted()) pw.println(); 17372 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17373 } 17374 17375 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 17376 if (dumpState.onTitlePrinted()) pw.println(); 17377 mSettings.dumpReadMessagesLPr(pw, dumpState); 17378 17379 pw.println(); 17380 pw.println("Package warning messages:"); 17381 BufferedReader in = null; 17382 String line = null; 17383 try { 17384 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17385 while ((line = in.readLine()) != null) { 17386 if (line.contains("ignored: updated version")) continue; 17387 pw.println(line); 17388 } 17389 } catch (IOException ignored) { 17390 } finally { 17391 IoUtils.closeQuietly(in); 17392 } 17393 } 17394 17395 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 17396 BufferedReader in = null; 17397 String line = null; 17398 try { 17399 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 17400 while ((line = in.readLine()) != null) { 17401 if (line.contains("ignored: updated version")) continue; 17402 pw.print("msg,"); 17403 pw.println(line); 17404 } 17405 } catch (IOException ignored) { 17406 } finally { 17407 IoUtils.closeQuietly(in); 17408 } 17409 } 17410 } 17411 } 17412 17413 private String dumpDomainString(String packageName) { 17414 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 17415 .getList(); 17416 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 17417 17418 ArraySet<String> result = new ArraySet<>(); 17419 if (iviList.size() > 0) { 17420 for (IntentFilterVerificationInfo ivi : iviList) { 17421 for (String host : ivi.getDomains()) { 17422 result.add(host); 17423 } 17424 } 17425 } 17426 if (filters != null && filters.size() > 0) { 17427 for (IntentFilter filter : filters) { 17428 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 17429 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 17430 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 17431 result.addAll(filter.getHostsList()); 17432 } 17433 } 17434 } 17435 17436 StringBuilder sb = new StringBuilder(result.size() * 16); 17437 for (String domain : result) { 17438 if (sb.length() > 0) sb.append(" "); 17439 sb.append(domain); 17440 } 17441 return sb.toString(); 17442 } 17443 17444 // ------- apps on sdcard specific code ------- 17445 static final boolean DEBUG_SD_INSTALL = false; 17446 17447 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 17448 17449 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 17450 17451 private boolean mMediaMounted = false; 17452 17453 static String getEncryptKey() { 17454 try { 17455 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 17456 SD_ENCRYPTION_KEYSTORE_NAME); 17457 if (sdEncKey == null) { 17458 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 17459 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 17460 if (sdEncKey == null) { 17461 Slog.e(TAG, "Failed to create encryption keys"); 17462 return null; 17463 } 17464 } 17465 return sdEncKey; 17466 } catch (NoSuchAlgorithmException nsae) { 17467 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 17468 return null; 17469 } catch (IOException ioe) { 17470 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 17471 return null; 17472 } 17473 } 17474 17475 /* 17476 * Update media status on PackageManager. 17477 */ 17478 @Override 17479 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 17480 int callingUid = Binder.getCallingUid(); 17481 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 17482 throw new SecurityException("Media status can only be updated by the system"); 17483 } 17484 // reader; this apparently protects mMediaMounted, but should probably 17485 // be a different lock in that case. 17486 synchronized (mPackages) { 17487 Log.i(TAG, "Updating external media status from " 17488 + (mMediaMounted ? "mounted" : "unmounted") + " to " 17489 + (mediaStatus ? "mounted" : "unmounted")); 17490 if (DEBUG_SD_INSTALL) 17491 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 17492 + ", mMediaMounted=" + mMediaMounted); 17493 if (mediaStatus == mMediaMounted) { 17494 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 17495 : 0, -1); 17496 mHandler.sendMessage(msg); 17497 return; 17498 } 17499 mMediaMounted = mediaStatus; 17500 } 17501 // Queue up an async operation since the package installation may take a 17502 // little while. 17503 mHandler.post(new Runnable() { 17504 public void run() { 17505 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 17506 } 17507 }); 17508 } 17509 17510 /** 17511 * Called by MountService when the initial ASECs to scan are available. 17512 * Should block until all the ASEC containers are finished being scanned. 17513 */ 17514 public void scanAvailableAsecs() { 17515 updateExternalMediaStatusInner(true, false, false); 17516 } 17517 17518 /* 17519 * Collect information of applications on external media, map them against 17520 * existing containers and update information based on current mount status. 17521 * Please note that we always have to report status if reportStatus has been 17522 * set to true especially when unloading packages. 17523 */ 17524 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 17525 boolean externalStorage) { 17526 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 17527 int[] uidArr = EmptyArray.INT; 17528 17529 final String[] list = PackageHelper.getSecureContainerList(); 17530 if (ArrayUtils.isEmpty(list)) { 17531 Log.i(TAG, "No secure containers found"); 17532 } else { 17533 // Process list of secure containers and categorize them 17534 // as active or stale based on their package internal state. 17535 17536 // reader 17537 synchronized (mPackages) { 17538 for (String cid : list) { 17539 // Leave stages untouched for now; installer service owns them 17540 if (PackageInstallerService.isStageName(cid)) continue; 17541 17542 if (DEBUG_SD_INSTALL) 17543 Log.i(TAG, "Processing container " + cid); 17544 String pkgName = getAsecPackageName(cid); 17545 if (pkgName == null) { 17546 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 17547 continue; 17548 } 17549 if (DEBUG_SD_INSTALL) 17550 Log.i(TAG, "Looking for pkg : " + pkgName); 17551 17552 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17553 if (ps == null) { 17554 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 17555 continue; 17556 } 17557 17558 /* 17559 * Skip packages that are not external if we're unmounting 17560 * external storage. 17561 */ 17562 if (externalStorage && !isMounted && !isExternal(ps)) { 17563 continue; 17564 } 17565 17566 final AsecInstallArgs args = new AsecInstallArgs(cid, 17567 getAppDexInstructionSets(ps), ps.isForwardLocked()); 17568 // The package status is changed only if the code path 17569 // matches between settings and the container id. 17570 if (ps.codePathString != null 17571 && ps.codePathString.startsWith(args.getCodePath())) { 17572 if (DEBUG_SD_INSTALL) { 17573 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 17574 + " at code path: " + ps.codePathString); 17575 } 17576 17577 // We do have a valid package installed on sdcard 17578 processCids.put(args, ps.codePathString); 17579 final int uid = ps.appId; 17580 if (uid != -1) { 17581 uidArr = ArrayUtils.appendInt(uidArr, uid); 17582 } 17583 } else { 17584 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 17585 + ps.codePathString); 17586 } 17587 } 17588 } 17589 17590 Arrays.sort(uidArr); 17591 } 17592 17593 // Process packages with valid entries. 17594 if (isMounted) { 17595 if (DEBUG_SD_INSTALL) 17596 Log.i(TAG, "Loading packages"); 17597 loadMediaPackages(processCids, uidArr, externalStorage); 17598 startCleaningPackages(); 17599 mInstallerService.onSecureContainersAvailable(); 17600 } else { 17601 if (DEBUG_SD_INSTALL) 17602 Log.i(TAG, "Unloading packages"); 17603 unloadMediaPackages(processCids, uidArr, reportStatus); 17604 } 17605 } 17606 17607 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17608 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 17609 final int size = infos.size(); 17610 final String[] packageNames = new String[size]; 17611 final int[] packageUids = new int[size]; 17612 for (int i = 0; i < size; i++) { 17613 final ApplicationInfo info = infos.get(i); 17614 packageNames[i] = info.packageName; 17615 packageUids[i] = info.uid; 17616 } 17617 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 17618 finishedReceiver); 17619 } 17620 17621 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17622 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17623 sendResourcesChangedBroadcast(mediaStatus, replacing, 17624 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 17625 } 17626 17627 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 17628 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 17629 int size = pkgList.length; 17630 if (size > 0) { 17631 // Send broadcasts here 17632 Bundle extras = new Bundle(); 17633 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 17634 if (uidArr != null) { 17635 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 17636 } 17637 if (replacing) { 17638 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 17639 } 17640 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 17641 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 17642 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 17643 } 17644 } 17645 17646 /* 17647 * Look at potentially valid container ids from processCids If package 17648 * information doesn't match the one on record or package scanning fails, 17649 * the cid is added to list of removeCids. We currently don't delete stale 17650 * containers. 17651 */ 17652 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 17653 boolean externalStorage) { 17654 ArrayList<String> pkgList = new ArrayList<String>(); 17655 Set<AsecInstallArgs> keys = processCids.keySet(); 17656 17657 for (AsecInstallArgs args : keys) { 17658 String codePath = processCids.get(args); 17659 if (DEBUG_SD_INSTALL) 17660 Log.i(TAG, "Loading container : " + args.cid); 17661 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 17662 try { 17663 // Make sure there are no container errors first. 17664 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 17665 Slog.e(TAG, "Failed to mount cid : " + args.cid 17666 + " when installing from sdcard"); 17667 continue; 17668 } 17669 // Check code path here. 17670 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 17671 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 17672 + " does not match one in settings " + codePath); 17673 continue; 17674 } 17675 // Parse package 17676 int parseFlags = mDefParseFlags; 17677 if (args.isExternalAsec()) { 17678 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 17679 } 17680 if (args.isFwdLocked()) { 17681 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 17682 } 17683 17684 synchronized (mInstallLock) { 17685 PackageParser.Package pkg = null; 17686 try { 17687 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null); 17688 } catch (PackageManagerException e) { 17689 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 17690 } 17691 // Scan the package 17692 if (pkg != null) { 17693 /* 17694 * TODO why is the lock being held? doPostInstall is 17695 * called in other places without the lock. This needs 17696 * to be straightened out. 17697 */ 17698 // writer 17699 synchronized (mPackages) { 17700 retCode = PackageManager.INSTALL_SUCCEEDED; 17701 pkgList.add(pkg.packageName); 17702 // Post process args 17703 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 17704 pkg.applicationInfo.uid); 17705 } 17706 } else { 17707 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 17708 } 17709 } 17710 17711 } finally { 17712 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 17713 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 17714 } 17715 } 17716 } 17717 // writer 17718 synchronized (mPackages) { 17719 // If the platform SDK has changed since the last time we booted, 17720 // we need to re-grant app permission to catch any new ones that 17721 // appear. This is really a hack, and means that apps can in some 17722 // cases get permissions that the user didn't initially explicitly 17723 // allow... it would be nice to have some better way to handle 17724 // this situation. 17725 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 17726 : mSettings.getInternalVersion(); 17727 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 17728 : StorageManager.UUID_PRIVATE_INTERNAL; 17729 17730 int updateFlags = UPDATE_PERMISSIONS_ALL; 17731 if (ver.sdkVersion != mSdkVersion) { 17732 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17733 + mSdkVersion + "; regranting permissions for external"); 17734 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17735 } 17736 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17737 17738 // Yay, everything is now upgraded 17739 ver.forceCurrent(); 17740 17741 // can downgrade to reader 17742 // Persist settings 17743 mSettings.writeLPr(); 17744 } 17745 // Send a broadcast to let everyone know we are done processing 17746 if (pkgList.size() > 0) { 17747 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 17748 } 17749 } 17750 17751 /* 17752 * Utility method to unload a list of specified containers 17753 */ 17754 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 17755 // Just unmount all valid containers. 17756 for (AsecInstallArgs arg : cidArgs) { 17757 synchronized (mInstallLock) { 17758 arg.doPostDeleteLI(false); 17759 } 17760 } 17761 } 17762 17763 /* 17764 * Unload packages mounted on external media. This involves deleting package 17765 * data from internal structures, sending broadcasts about disabled packages, 17766 * gc'ing to free up references, unmounting all secure containers 17767 * corresponding to packages on external media, and posting a 17768 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 17769 * that we always have to post this message if status has been requested no 17770 * matter what. 17771 */ 17772 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 17773 final boolean reportStatus) { 17774 if (DEBUG_SD_INSTALL) 17775 Log.i(TAG, "unloading media packages"); 17776 ArrayList<String> pkgList = new ArrayList<String>(); 17777 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 17778 final Set<AsecInstallArgs> keys = processCids.keySet(); 17779 for (AsecInstallArgs args : keys) { 17780 String pkgName = args.getPackageName(); 17781 if (DEBUG_SD_INSTALL) 17782 Log.i(TAG, "Trying to unload pkg : " + pkgName); 17783 // Delete package internally 17784 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17785 synchronized (mInstallLock) { 17786 boolean res = deletePackageLI(pkgName, null, false, null, 17787 PackageManager.DELETE_KEEP_DATA, outInfo, false, null); 17788 if (res) { 17789 pkgList.add(pkgName); 17790 } else { 17791 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 17792 failedList.add(args); 17793 } 17794 } 17795 } 17796 17797 // reader 17798 synchronized (mPackages) { 17799 // We didn't update the settings after removing each package; 17800 // write them now for all packages. 17801 mSettings.writeLPr(); 17802 } 17803 17804 // We have to absolutely send UPDATED_MEDIA_STATUS only 17805 // after confirming that all the receivers processed the ordered 17806 // broadcast when packages get disabled, force a gc to clean things up. 17807 // and unload all the containers. 17808 if (pkgList.size() > 0) { 17809 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 17810 new IIntentReceiver.Stub() { 17811 public void performReceive(Intent intent, int resultCode, String data, 17812 Bundle extras, boolean ordered, boolean sticky, 17813 int sendingUser) throws RemoteException { 17814 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 17815 reportStatus ? 1 : 0, 1, keys); 17816 mHandler.sendMessage(msg); 17817 } 17818 }); 17819 } else { 17820 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 17821 keys); 17822 mHandler.sendMessage(msg); 17823 } 17824 } 17825 17826 private void loadPrivatePackages(final VolumeInfo vol) { 17827 mHandler.post(new Runnable() { 17828 @Override 17829 public void run() { 17830 loadPrivatePackagesInner(vol); 17831 } 17832 }); 17833 } 17834 17835 private void loadPrivatePackagesInner(VolumeInfo vol) { 17836 final String volumeUuid = vol.fsUuid; 17837 if (TextUtils.isEmpty(volumeUuid)) { 17838 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 17839 return; 17840 } 17841 17842 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 17843 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 17844 17845 final VersionInfo ver; 17846 final List<PackageSetting> packages; 17847 synchronized (mPackages) { 17848 ver = mSettings.findOrCreateVersion(volumeUuid); 17849 packages = mSettings.getVolumePackagesLPr(volumeUuid); 17850 } 17851 17852 // TODO: introduce a new concept similar to "frozen" to prevent these 17853 // apps from being launched until after data has been fully reconciled 17854 for (PackageSetting ps : packages) { 17855 synchronized (mInstallLock) { 17856 final PackageParser.Package pkg; 17857 try { 17858 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 17859 loaded.add(pkg.applicationInfo); 17860 17861 } catch (PackageManagerException e) { 17862 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 17863 } 17864 17865 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 17866 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 17867 } 17868 } 17869 } 17870 17871 // Reconcile app data for all started/unlocked users 17872 final StorageManager sm = mContext.getSystemService(StorageManager.class); 17873 final UserManager um = mContext.getSystemService(UserManager.class); 17874 for (UserInfo user : um.getUsers()) { 17875 final int flags; 17876 if (um.isUserUnlocked(user.id)) { 17877 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17878 } else if (um.isUserRunning(user.id)) { 17879 flags = StorageManager.FLAG_STORAGE_DE; 17880 } else { 17881 continue; 17882 } 17883 17884 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 17885 reconcileAppsData(volumeUuid, user.id, flags); 17886 } 17887 17888 synchronized (mPackages) { 17889 int updateFlags = UPDATE_PERMISSIONS_ALL; 17890 if (ver.sdkVersion != mSdkVersion) { 17891 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 17892 + mSdkVersion + "; regranting permissions for " + volumeUuid); 17893 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 17894 } 17895 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 17896 17897 // Yay, everything is now upgraded 17898 ver.forceCurrent(); 17899 17900 mSettings.writeLPr(); 17901 } 17902 17903 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 17904 sendResourcesChangedBroadcast(true, false, loaded, null); 17905 } 17906 17907 private void unloadPrivatePackages(final VolumeInfo vol) { 17908 mHandler.post(new Runnable() { 17909 @Override 17910 public void run() { 17911 unloadPrivatePackagesInner(vol); 17912 } 17913 }); 17914 } 17915 17916 private void unloadPrivatePackagesInner(VolumeInfo vol) { 17917 final String volumeUuid = vol.fsUuid; 17918 if (TextUtils.isEmpty(volumeUuid)) { 17919 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 17920 return; 17921 } 17922 17923 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 17924 synchronized (mInstallLock) { 17925 synchronized (mPackages) { 17926 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 17927 for (PackageSetting ps : packages) { 17928 if (ps.pkg == null) continue; 17929 17930 final ApplicationInfo info = ps.pkg.applicationInfo; 17931 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 17932 if (deletePackageLI(ps.name, null, false, null, 17933 PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) { 17934 unloaded.add(info); 17935 } else { 17936 Slog.w(TAG, "Failed to unload " + ps.codePath); 17937 } 17938 } 17939 17940 mSettings.writeLPr(); 17941 } 17942 } 17943 17944 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 17945 sendResourcesChangedBroadcast(false, false, unloaded, null); 17946 } 17947 17948 /** 17949 * Examine all users present on given mounted volume, and destroy data 17950 * belonging to users that are no longer valid, or whose user ID has been 17951 * recycled. 17952 */ 17953 private void reconcileUsers(String volumeUuid) { 17954 // TODO: also reconcile DE directories 17955 final File[] files = FileUtils 17956 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 17957 for (File file : files) { 17958 if (!file.isDirectory()) continue; 17959 17960 final int userId; 17961 final UserInfo info; 17962 try { 17963 userId = Integer.parseInt(file.getName()); 17964 info = sUserManager.getUserInfo(userId); 17965 } catch (NumberFormatException e) { 17966 Slog.w(TAG, "Invalid user directory " + file); 17967 continue; 17968 } 17969 17970 boolean destroyUser = false; 17971 if (info == null) { 17972 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17973 + " because no matching user was found"); 17974 destroyUser = true; 17975 } else { 17976 try { 17977 UserManagerService.enforceSerialNumber(file, info.serialNumber); 17978 } catch (IOException e) { 17979 logCriticalInfo(Log.WARN, "Destroying user directory " + file 17980 + " because we failed to enforce serial number: " + e); 17981 destroyUser = true; 17982 } 17983 } 17984 17985 if (destroyUser) { 17986 synchronized (mInstallLock) { 17987 try { 17988 mInstaller.removeUserDataDirs(volumeUuid, userId); 17989 } catch (InstallerException e) { 17990 Slog.w(TAG, "Failed to clean up user dirs", e); 17991 } 17992 } 17993 } 17994 } 17995 } 17996 17997 private void assertPackageKnown(String volumeUuid, String packageName) 17998 throws PackageManagerException { 17999 synchronized (mPackages) { 18000 final PackageSetting ps = mSettings.mPackages.get(packageName); 18001 if (ps == null) { 18002 throw new PackageManagerException("Package " + packageName + " is unknown"); 18003 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18004 throw new PackageManagerException( 18005 "Package " + packageName + " found on unknown volume " + volumeUuid 18006 + "; expected volume " + ps.volumeUuid); 18007 } 18008 } 18009 } 18010 18011 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18012 throws PackageManagerException { 18013 synchronized (mPackages) { 18014 final PackageSetting ps = mSettings.mPackages.get(packageName); 18015 if (ps == null) { 18016 throw new PackageManagerException("Package " + packageName + " is unknown"); 18017 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18018 throw new PackageManagerException( 18019 "Package " + packageName + " found on unknown volume " + volumeUuid 18020 + "; expected volume " + ps.volumeUuid); 18021 } else if (!ps.getInstalled(userId)) { 18022 throw new PackageManagerException( 18023 "Package " + packageName + " not installed for user " + userId); 18024 } 18025 } 18026 } 18027 18028 /** 18029 * Examine all apps present on given mounted volume, and destroy apps that 18030 * aren't expected, either due to uninstallation or reinstallation on 18031 * another volume. 18032 */ 18033 private void reconcileApps(String volumeUuid) { 18034 final File[] files = FileUtils 18035 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18036 for (File file : files) { 18037 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18038 && !PackageInstallerService.isStageName(file.getName()); 18039 if (!isPackage) { 18040 // Ignore entries which are not packages 18041 continue; 18042 } 18043 18044 try { 18045 final PackageLite pkg = PackageParser.parsePackageLite(file, 18046 PackageParser.PARSE_MUST_BE_APK); 18047 assertPackageKnown(volumeUuid, pkg.packageName); 18048 18049 } catch (PackageParserException | PackageManagerException e) { 18050 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18051 synchronized (mInstallLock) { 18052 removeCodePathLI(file); 18053 } 18054 } 18055 } 18056 } 18057 18058 /** 18059 * Reconcile all app data for the given user. 18060 * <p> 18061 * Verifies that directories exist and that ownership and labeling is 18062 * correct for all installed apps on all mounted volumes. 18063 */ 18064 void reconcileAppsData(int userId, int flags) { 18065 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18066 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18067 final String volumeUuid = vol.getFsUuid(); 18068 reconcileAppsData(volumeUuid, userId, flags); 18069 } 18070 } 18071 18072 /** 18073 * Reconcile all app data on given mounted volume. 18074 * <p> 18075 * Destroys app data that isn't expected, either due to uninstallation or 18076 * reinstallation on another volume. 18077 * <p> 18078 * Verifies that directories exist and that ownership and labeling is 18079 * correct for all installed apps. 18080 */ 18081 private void reconcileAppsData(String volumeUuid, int userId, int flags) { 18082 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18083 + Integer.toHexString(flags)); 18084 18085 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18086 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18087 18088 boolean restoreconNeeded = false; 18089 18090 // First look for stale data that doesn't belong, and check if things 18091 // have changed since we did our last restorecon 18092 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18093 if (!isUserKeyUnlocked(userId)) { 18094 throw new RuntimeException( 18095 "Yikes, someone asked us to reconcile CE storage while " + userId 18096 + " was still locked; this would have caused massive data loss!"); 18097 } 18098 18099 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18100 18101 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18102 for (File file : files) { 18103 final String packageName = file.getName(); 18104 try { 18105 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18106 } catch (PackageManagerException e) { 18107 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18108 synchronized (mInstallLock) { 18109 destroyAppDataLI(volumeUuid, packageName, userId, 18110 StorageManager.FLAG_STORAGE_CE); 18111 } 18112 } 18113 } 18114 } 18115 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18116 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18117 18118 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18119 for (File file : files) { 18120 final String packageName = file.getName(); 18121 try { 18122 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18123 } catch (PackageManagerException e) { 18124 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18125 synchronized (mInstallLock) { 18126 destroyAppDataLI(volumeUuid, packageName, userId, 18127 StorageManager.FLAG_STORAGE_DE); 18128 } 18129 } 18130 } 18131 } 18132 18133 // Ensure that data directories are ready to roll for all packages 18134 // installed for this volume and user 18135 final List<PackageSetting> packages; 18136 synchronized (mPackages) { 18137 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18138 } 18139 int preparedCount = 0; 18140 for (PackageSetting ps : packages) { 18141 final String packageName = ps.name; 18142 if (ps.pkg == null) { 18143 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18144 // TODO: might be due to legacy ASEC apps; we should circle back 18145 // and reconcile again once they're scanned 18146 continue; 18147 } 18148 18149 if (ps.getInstalled(userId)) { 18150 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18151 18152 if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) { 18153 // We may have just shuffled around app data directories, so 18154 // prepare them one more time 18155 prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded); 18156 } 18157 18158 preparedCount++; 18159 } 18160 } 18161 18162 if (restoreconNeeded) { 18163 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18164 SELinuxMMAC.setRestoreconDone(ceDir); 18165 } 18166 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18167 SELinuxMMAC.setRestoreconDone(deDir); 18168 } 18169 } 18170 18171 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18172 + " packages; restoreconNeeded was " + restoreconNeeded); 18173 } 18174 18175 /** 18176 * Prepare app data for the given app just after it was installed or 18177 * upgraded. This method carefully only touches users that it's installed 18178 * for, and it forces a restorecon to handle any seinfo changes. 18179 * <p> 18180 * Verifies that directories exist and that ownership and labeling is 18181 * correct for all installed apps. If there is an ownership mismatch, it 18182 * will try recovering system apps by wiping data; third-party app data is 18183 * left intact. 18184 * <p> 18185 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18186 */ 18187 private void prepareAppDataAfterInstall(PackageParser.Package pkg) { 18188 prepareAppDataAfterInstallInternal(pkg); 18189 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18190 for (int i = 0; i < childCount; i++) { 18191 PackageParser.Package childPackage = pkg.childPackages.get(i); 18192 prepareAppDataAfterInstallInternal(childPackage); 18193 } 18194 } 18195 18196 private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) { 18197 final PackageSetting ps; 18198 synchronized (mPackages) { 18199 ps = mSettings.mPackages.get(pkg.packageName); 18200 mSettings.writeKernelMappingLPr(ps); 18201 } 18202 18203 final UserManager um = mContext.getSystemService(UserManager.class); 18204 for (UserInfo user : um.getUsers()) { 18205 final int flags; 18206 if (um.isUserUnlocked(user.id)) { 18207 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18208 } else if (um.isUserRunning(user.id)) { 18209 flags = StorageManager.FLAG_STORAGE_DE; 18210 } else { 18211 continue; 18212 } 18213 18214 if (ps.getInstalled(user.id)) { 18215 // Whenever an app changes, force a restorecon of its data 18216 // TODO: when user data is locked, mark that we're still dirty 18217 prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true); 18218 } 18219 } 18220 } 18221 18222 /** 18223 * Prepare app data for the given app. 18224 * <p> 18225 * Verifies that directories exist and that ownership and labeling is 18226 * correct for all installed apps. If there is an ownership mismatch, this 18227 * will try recovering system apps by wiping data; third-party app data is 18228 * left intact. 18229 */ 18230 private void prepareAppData(String volumeUuid, int userId, int flags, 18231 PackageParser.Package pkg, boolean restoreconNeeded) { 18232 if (DEBUG_APP_DATA) { 18233 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18234 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18235 } 18236 18237 final String packageName = pkg.packageName; 18238 final ApplicationInfo app = pkg.applicationInfo; 18239 final int appId = UserHandle.getAppId(app.uid); 18240 18241 Preconditions.checkNotNull(app.seinfo); 18242 18243 synchronized (mInstallLock) { 18244 try { 18245 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18246 appId, app.seinfo, app.targetSdkVersion); 18247 } catch (InstallerException e) { 18248 if (app.isSystemApp()) { 18249 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18250 + ", but trying to recover: " + e); 18251 destroyAppDataLI(volumeUuid, packageName, userId, flags); 18252 try { 18253 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18254 appId, app.seinfo, app.targetSdkVersion); 18255 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18256 } catch (InstallerException e2) { 18257 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18258 } 18259 } else { 18260 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18261 } 18262 } 18263 18264 if (restoreconNeeded) { 18265 restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo); 18266 } 18267 18268 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18269 // Create a native library symlink only if we have native libraries 18270 // and if the native libraries are 32 bit libraries. We do not provide 18271 // this symlink for 64 bit libraries. 18272 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18273 final String nativeLibPath = app.nativeLibraryDir; 18274 try { 18275 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18276 nativeLibPath, userId); 18277 } catch (InstallerException e) { 18278 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18279 } 18280 } 18281 } 18282 } 18283 } 18284 18285 /** 18286 * For system apps on non-FBE devices, this method migrates any existing 18287 * CE/DE data to match the {@code forceDeviceEncrypted} flag requested by 18288 * the app. 18289 */ 18290 private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) { 18291 if (pkg.isSystemApp() && !StorageManager.isFileBasedEncryptionEnabled() 18292 && PackageManager.APPLY_FORCE_DEVICE_ENCRYPTED) { 18293 final int storageTarget = pkg.applicationInfo.isForceDeviceEncrypted() 18294 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 18295 synchronized (mInstallLock) { 18296 try { 18297 mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget); 18298 } catch (InstallerException e) { 18299 logCriticalInfo(Log.WARN, 18300 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 18301 } 18302 } 18303 return true; 18304 } else { 18305 return false; 18306 } 18307 } 18308 18309 private void unfreezePackage(String packageName) { 18310 synchronized (mPackages) { 18311 final PackageSetting ps = mSettings.mPackages.get(packageName); 18312 if (ps != null) { 18313 ps.frozen = false; 18314 } 18315 } 18316 } 18317 18318 @Override 18319 public int movePackage(final String packageName, final String volumeUuid) { 18320 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18321 18322 final int moveId = mNextMoveId.getAndIncrement(); 18323 mHandler.post(new Runnable() { 18324 @Override 18325 public void run() { 18326 try { 18327 movePackageInternal(packageName, volumeUuid, moveId); 18328 } catch (PackageManagerException e) { 18329 Slog.w(TAG, "Failed to move " + packageName, e); 18330 mMoveCallbacks.notifyStatusChanged(moveId, 18331 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18332 } 18333 } 18334 }); 18335 return moveId; 18336 } 18337 18338 private void movePackageInternal(final String packageName, final String volumeUuid, 18339 final int moveId) throws PackageManagerException { 18340 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 18341 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18342 final PackageManager pm = mContext.getPackageManager(); 18343 18344 final boolean currentAsec; 18345 final String currentVolumeUuid; 18346 final File codeFile; 18347 final String installerPackageName; 18348 final String packageAbiOverride; 18349 final int appId; 18350 final String seinfo; 18351 final String label; 18352 final int targetSdkVersion; 18353 18354 // reader 18355 synchronized (mPackages) { 18356 final PackageParser.Package pkg = mPackages.get(packageName); 18357 final PackageSetting ps = mSettings.mPackages.get(packageName); 18358 if (pkg == null || ps == null) { 18359 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 18360 } 18361 18362 if (pkg.applicationInfo.isSystemApp()) { 18363 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 18364 "Cannot move system application"); 18365 } 18366 18367 if (pkg.applicationInfo.isExternalAsec()) { 18368 currentAsec = true; 18369 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 18370 } else if (pkg.applicationInfo.isForwardLocked()) { 18371 currentAsec = true; 18372 currentVolumeUuid = "forward_locked"; 18373 } else { 18374 currentAsec = false; 18375 currentVolumeUuid = ps.volumeUuid; 18376 18377 final File probe = new File(pkg.codePath); 18378 final File probeOat = new File(probe, "oat"); 18379 if (!probe.isDirectory() || !probeOat.isDirectory()) { 18380 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18381 "Move only supported for modern cluster style installs"); 18382 } 18383 } 18384 18385 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 18386 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18387 "Package already moved to " + volumeUuid); 18388 } 18389 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 18390 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 18391 "Device admin cannot be moved"); 18392 } 18393 18394 if (ps.frozen) { 18395 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 18396 "Failed to move already frozen package"); 18397 } 18398 ps.frozen = true; 18399 18400 codeFile = new File(pkg.codePath); 18401 installerPackageName = ps.installerPackageName; 18402 packageAbiOverride = ps.cpuAbiOverrideString; 18403 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18404 seinfo = pkg.applicationInfo.seinfo; 18405 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 18406 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 18407 } 18408 18409 // Now that we're guarded by frozen state, kill app during move 18410 final long token = Binder.clearCallingIdentity(); 18411 try { 18412 killApplication(packageName, appId, "move pkg"); 18413 } finally { 18414 Binder.restoreCallingIdentity(token); 18415 } 18416 18417 final Bundle extras = new Bundle(); 18418 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 18419 extras.putString(Intent.EXTRA_TITLE, label); 18420 mMoveCallbacks.notifyCreated(moveId, extras); 18421 18422 int installFlags; 18423 final boolean moveCompleteApp; 18424 final File measurePath; 18425 18426 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 18427 installFlags = INSTALL_INTERNAL; 18428 moveCompleteApp = !currentAsec; 18429 measurePath = Environment.getDataAppDirectory(volumeUuid); 18430 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 18431 installFlags = INSTALL_EXTERNAL; 18432 moveCompleteApp = false; 18433 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 18434 } else { 18435 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 18436 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 18437 || !volume.isMountedWritable()) { 18438 unfreezePackage(packageName); 18439 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18440 "Move location not mounted private volume"); 18441 } 18442 18443 Preconditions.checkState(!currentAsec); 18444 18445 installFlags = INSTALL_INTERNAL; 18446 moveCompleteApp = true; 18447 measurePath = Environment.getDataAppDirectory(volumeUuid); 18448 } 18449 18450 final PackageStats stats = new PackageStats(null, -1); 18451 synchronized (mInstaller) { 18452 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 18453 unfreezePackage(packageName); 18454 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18455 "Failed to measure package size"); 18456 } 18457 } 18458 18459 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 18460 + stats.dataSize); 18461 18462 final long startFreeBytes = measurePath.getFreeSpace(); 18463 final long sizeBytes; 18464 if (moveCompleteApp) { 18465 sizeBytes = stats.codeSize + stats.dataSize; 18466 } else { 18467 sizeBytes = stats.codeSize; 18468 } 18469 18470 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 18471 unfreezePackage(packageName); 18472 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 18473 "Not enough free space to move"); 18474 } 18475 18476 mMoveCallbacks.notifyStatusChanged(moveId, 10); 18477 18478 final CountDownLatch installedLatch = new CountDownLatch(1); 18479 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 18480 @Override 18481 public void onUserActionRequired(Intent intent) throws RemoteException { 18482 throw new IllegalStateException(); 18483 } 18484 18485 @Override 18486 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 18487 Bundle extras) throws RemoteException { 18488 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 18489 + PackageManager.installStatusToString(returnCode, msg)); 18490 18491 installedLatch.countDown(); 18492 18493 // Regardless of success or failure of the move operation, 18494 // always unfreeze the package 18495 unfreezePackage(packageName); 18496 18497 final int status = PackageManager.installStatusToPublicStatus(returnCode); 18498 switch (status) { 18499 case PackageInstaller.STATUS_SUCCESS: 18500 mMoveCallbacks.notifyStatusChanged(moveId, 18501 PackageManager.MOVE_SUCCEEDED); 18502 break; 18503 case PackageInstaller.STATUS_FAILURE_STORAGE: 18504 mMoveCallbacks.notifyStatusChanged(moveId, 18505 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 18506 break; 18507 default: 18508 mMoveCallbacks.notifyStatusChanged(moveId, 18509 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 18510 break; 18511 } 18512 } 18513 }; 18514 18515 final MoveInfo move; 18516 if (moveCompleteApp) { 18517 // Kick off a thread to report progress estimates 18518 new Thread() { 18519 @Override 18520 public void run() { 18521 while (true) { 18522 try { 18523 if (installedLatch.await(1, TimeUnit.SECONDS)) { 18524 break; 18525 } 18526 } catch (InterruptedException ignored) { 18527 } 18528 18529 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 18530 final int progress = 10 + (int) MathUtils.constrain( 18531 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 18532 mMoveCallbacks.notifyStatusChanged(moveId, progress); 18533 } 18534 } 18535 }.start(); 18536 18537 final String dataAppName = codeFile.getName(); 18538 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 18539 dataAppName, appId, seinfo, targetSdkVersion); 18540 } else { 18541 move = null; 18542 } 18543 18544 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 18545 18546 final Message msg = mHandler.obtainMessage(INIT_COPY); 18547 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 18548 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 18549 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 18550 packageAbiOverride, null); 18551 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 18552 msg.obj = params; 18553 18554 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 18555 System.identityHashCode(msg.obj)); 18556 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 18557 System.identityHashCode(msg.obj)); 18558 18559 mHandler.sendMessage(msg); 18560 } 18561 18562 @Override 18563 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 18564 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 18565 18566 final int realMoveId = mNextMoveId.getAndIncrement(); 18567 final Bundle extras = new Bundle(); 18568 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 18569 mMoveCallbacks.notifyCreated(realMoveId, extras); 18570 18571 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 18572 @Override 18573 public void onCreated(int moveId, Bundle extras) { 18574 // Ignored 18575 } 18576 18577 @Override 18578 public void onStatusChanged(int moveId, int status, long estMillis) { 18579 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 18580 } 18581 }; 18582 18583 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18584 storage.setPrimaryStorageUuid(volumeUuid, callback); 18585 return realMoveId; 18586 } 18587 18588 @Override 18589 public int getMoveStatus(int moveId) { 18590 mContext.enforceCallingOrSelfPermission( 18591 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18592 return mMoveCallbacks.mLastStatus.get(moveId); 18593 } 18594 18595 @Override 18596 public void registerMoveCallback(IPackageMoveObserver callback) { 18597 mContext.enforceCallingOrSelfPermission( 18598 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18599 mMoveCallbacks.register(callback); 18600 } 18601 18602 @Override 18603 public void unregisterMoveCallback(IPackageMoveObserver callback) { 18604 mContext.enforceCallingOrSelfPermission( 18605 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 18606 mMoveCallbacks.unregister(callback); 18607 } 18608 18609 @Override 18610 public boolean setInstallLocation(int loc) { 18611 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 18612 null); 18613 if (getInstallLocation() == loc) { 18614 return true; 18615 } 18616 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 18617 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 18618 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 18619 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 18620 return true; 18621 } 18622 return false; 18623 } 18624 18625 @Override 18626 public int getInstallLocation() { 18627 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 18628 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 18629 PackageHelper.APP_INSTALL_AUTO); 18630 } 18631 18632 /** Called by UserManagerService */ 18633 void cleanUpUser(UserManagerService userManager, int userHandle) { 18634 synchronized (mPackages) { 18635 mDirtyUsers.remove(userHandle); 18636 mUserNeedsBadging.delete(userHandle); 18637 mSettings.removeUserLPw(userHandle); 18638 mPendingBroadcasts.remove(userHandle); 18639 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 18640 } 18641 synchronized (mInstallLock) { 18642 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18643 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18644 final String volumeUuid = vol.getFsUuid(); 18645 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 18646 try { 18647 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 18648 } catch (InstallerException e) { 18649 Slog.w(TAG, "Failed to remove user data", e); 18650 } 18651 } 18652 synchronized (mPackages) { 18653 removeUnusedPackagesLILPw(userManager, userHandle); 18654 } 18655 } 18656 } 18657 18658 /** 18659 * We're removing userHandle and would like to remove any downloaded packages 18660 * that are no longer in use by any other user. 18661 * @param userHandle the user being removed 18662 */ 18663 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 18664 final boolean DEBUG_CLEAN_APKS = false; 18665 int [] users = userManager.getUserIds(); 18666 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 18667 while (psit.hasNext()) { 18668 PackageSetting ps = psit.next(); 18669 if (ps.pkg == null) { 18670 continue; 18671 } 18672 final String packageName = ps.pkg.packageName; 18673 // Skip over if system app 18674 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 18675 continue; 18676 } 18677 if (DEBUG_CLEAN_APKS) { 18678 Slog.i(TAG, "Checking package " + packageName); 18679 } 18680 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 18681 if (keep) { 18682 if (DEBUG_CLEAN_APKS) { 18683 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 18684 } 18685 } else { 18686 for (int i = 0; i < users.length; i++) { 18687 if (users[i] != userHandle && ps.getInstalled(users[i])) { 18688 keep = true; 18689 if (DEBUG_CLEAN_APKS) { 18690 Slog.i(TAG, " Keeping package " + packageName + " for user " 18691 + users[i]); 18692 } 18693 break; 18694 } 18695 } 18696 } 18697 if (!keep) { 18698 if (DEBUG_CLEAN_APKS) { 18699 Slog.i(TAG, " Removing package " + packageName); 18700 } 18701 mHandler.post(new Runnable() { 18702 public void run() { 18703 deletePackageX(packageName, userHandle, 0); 18704 } //end run 18705 }); 18706 } 18707 } 18708 } 18709 18710 /** Called by UserManagerService */ 18711 void createNewUser(int userHandle) { 18712 synchronized (mInstallLock) { 18713 try { 18714 mInstaller.createUserConfig(userHandle); 18715 } catch (InstallerException e) { 18716 Slog.w(TAG, "Failed to create user config", e); 18717 } 18718 mSettings.createNewUserLI(this, mInstaller, userHandle); 18719 } 18720 synchronized (mPackages) { 18721 applyFactoryDefaultBrowserLPw(userHandle); 18722 primeDomainVerificationsLPw(userHandle); 18723 } 18724 } 18725 18726 void newUserCreated(final int userHandle) { 18727 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 18728 // If permission review for legacy apps is required, we represent 18729 // dagerous permissions for such apps as always granted runtime 18730 // permissions to keep per user flag state whether review is needed. 18731 // Hence, if a new user is added we have to propagate dangerous 18732 // permission grants for these legacy apps. 18733 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 18734 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 18735 | UPDATE_PERMISSIONS_REPLACE_ALL); 18736 } 18737 } 18738 18739 @Override 18740 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 18741 mContext.enforceCallingOrSelfPermission( 18742 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 18743 "Only package verification agents can read the verifier device identity"); 18744 18745 synchronized (mPackages) { 18746 return mSettings.getVerifierDeviceIdentityLPw(); 18747 } 18748 } 18749 18750 @Override 18751 public void setPermissionEnforced(String permission, boolean enforced) { 18752 // TODO: Now that we no longer change GID for storage, this should to away. 18753 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 18754 "setPermissionEnforced"); 18755 if (READ_EXTERNAL_STORAGE.equals(permission)) { 18756 synchronized (mPackages) { 18757 if (mSettings.mReadExternalStorageEnforced == null 18758 || mSettings.mReadExternalStorageEnforced != enforced) { 18759 mSettings.mReadExternalStorageEnforced = enforced; 18760 mSettings.writeLPr(); 18761 } 18762 } 18763 // kill any non-foreground processes so we restart them and 18764 // grant/revoke the GID. 18765 final IActivityManager am = ActivityManagerNative.getDefault(); 18766 if (am != null) { 18767 final long token = Binder.clearCallingIdentity(); 18768 try { 18769 am.killProcessesBelowForeground("setPermissionEnforcement"); 18770 } catch (RemoteException e) { 18771 } finally { 18772 Binder.restoreCallingIdentity(token); 18773 } 18774 } 18775 } else { 18776 throw new IllegalArgumentException("No selective enforcement for " + permission); 18777 } 18778 } 18779 18780 @Override 18781 @Deprecated 18782 public boolean isPermissionEnforced(String permission) { 18783 return true; 18784 } 18785 18786 @Override 18787 public boolean isStorageLow() { 18788 final long token = Binder.clearCallingIdentity(); 18789 try { 18790 final DeviceStorageMonitorInternal 18791 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 18792 if (dsm != null) { 18793 return dsm.isMemoryLow(); 18794 } else { 18795 return false; 18796 } 18797 } finally { 18798 Binder.restoreCallingIdentity(token); 18799 } 18800 } 18801 18802 @Override 18803 public IPackageInstaller getPackageInstaller() { 18804 return mInstallerService; 18805 } 18806 18807 private boolean userNeedsBadging(int userId) { 18808 int index = mUserNeedsBadging.indexOfKey(userId); 18809 if (index < 0) { 18810 final UserInfo userInfo; 18811 final long token = Binder.clearCallingIdentity(); 18812 try { 18813 userInfo = sUserManager.getUserInfo(userId); 18814 } finally { 18815 Binder.restoreCallingIdentity(token); 18816 } 18817 final boolean b; 18818 if (userInfo != null && userInfo.isManagedProfile()) { 18819 b = true; 18820 } else { 18821 b = false; 18822 } 18823 mUserNeedsBadging.put(userId, b); 18824 return b; 18825 } 18826 return mUserNeedsBadging.valueAt(index); 18827 } 18828 18829 @Override 18830 public KeySet getKeySetByAlias(String packageName, String alias) { 18831 if (packageName == null || alias == null) { 18832 return null; 18833 } 18834 synchronized(mPackages) { 18835 final PackageParser.Package pkg = mPackages.get(packageName); 18836 if (pkg == null) { 18837 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18838 throw new IllegalArgumentException("Unknown package: " + packageName); 18839 } 18840 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18841 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 18842 } 18843 } 18844 18845 @Override 18846 public KeySet getSigningKeySet(String packageName) { 18847 if (packageName == null) { 18848 return null; 18849 } 18850 synchronized(mPackages) { 18851 final PackageParser.Package pkg = mPackages.get(packageName); 18852 if (pkg == null) { 18853 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18854 throw new IllegalArgumentException("Unknown package: " + packageName); 18855 } 18856 if (pkg.applicationInfo.uid != Binder.getCallingUid() 18857 && Process.SYSTEM_UID != Binder.getCallingUid()) { 18858 throw new SecurityException("May not access signing KeySet of other apps."); 18859 } 18860 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18861 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 18862 } 18863 } 18864 18865 @Override 18866 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 18867 if (packageName == null || ks == null) { 18868 return false; 18869 } 18870 synchronized(mPackages) { 18871 final PackageParser.Package pkg = mPackages.get(packageName); 18872 if (pkg == null) { 18873 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18874 throw new IllegalArgumentException("Unknown package: " + packageName); 18875 } 18876 IBinder ksh = ks.getToken(); 18877 if (ksh instanceof KeySetHandle) { 18878 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18879 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 18880 } 18881 return false; 18882 } 18883 } 18884 18885 @Override 18886 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 18887 if (packageName == null || ks == null) { 18888 return false; 18889 } 18890 synchronized(mPackages) { 18891 final PackageParser.Package pkg = mPackages.get(packageName); 18892 if (pkg == null) { 18893 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 18894 throw new IllegalArgumentException("Unknown package: " + packageName); 18895 } 18896 IBinder ksh = ks.getToken(); 18897 if (ksh instanceof KeySetHandle) { 18898 KeySetManagerService ksms = mSettings.mKeySetManagerService; 18899 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 18900 } 18901 return false; 18902 } 18903 } 18904 18905 private void deletePackageIfUnusedLPr(final String packageName) { 18906 PackageSetting ps = mSettings.mPackages.get(packageName); 18907 if (ps == null) { 18908 return; 18909 } 18910 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 18911 // TODO Implement atomic delete if package is unused 18912 // It is currently possible that the package will be deleted even if it is installed 18913 // after this method returns. 18914 mHandler.post(new Runnable() { 18915 public void run() { 18916 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 18917 } 18918 }); 18919 } 18920 } 18921 18922 /** 18923 * Check and throw if the given before/after packages would be considered a 18924 * downgrade. 18925 */ 18926 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 18927 throws PackageManagerException { 18928 if (after.versionCode < before.mVersionCode) { 18929 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18930 "Update version code " + after.versionCode + " is older than current " 18931 + before.mVersionCode); 18932 } else if (after.versionCode == before.mVersionCode) { 18933 if (after.baseRevisionCode < before.baseRevisionCode) { 18934 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18935 "Update base revision code " + after.baseRevisionCode 18936 + " is older than current " + before.baseRevisionCode); 18937 } 18938 18939 if (!ArrayUtils.isEmpty(after.splitNames)) { 18940 for (int i = 0; i < after.splitNames.length; i++) { 18941 final String splitName = after.splitNames[i]; 18942 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 18943 if (j != -1) { 18944 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 18945 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 18946 "Update split " + splitName + " revision code " 18947 + after.splitRevisionCodes[i] + " is older than current " 18948 + before.splitRevisionCodes[j]); 18949 } 18950 } 18951 } 18952 } 18953 } 18954 } 18955 18956 private static class MoveCallbacks extends Handler { 18957 private static final int MSG_CREATED = 1; 18958 private static final int MSG_STATUS_CHANGED = 2; 18959 18960 private final RemoteCallbackList<IPackageMoveObserver> 18961 mCallbacks = new RemoteCallbackList<>(); 18962 18963 private final SparseIntArray mLastStatus = new SparseIntArray(); 18964 18965 public MoveCallbacks(Looper looper) { 18966 super(looper); 18967 } 18968 18969 public void register(IPackageMoveObserver callback) { 18970 mCallbacks.register(callback); 18971 } 18972 18973 public void unregister(IPackageMoveObserver callback) { 18974 mCallbacks.unregister(callback); 18975 } 18976 18977 @Override 18978 public void handleMessage(Message msg) { 18979 final SomeArgs args = (SomeArgs) msg.obj; 18980 final int n = mCallbacks.beginBroadcast(); 18981 for (int i = 0; i < n; i++) { 18982 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 18983 try { 18984 invokeCallback(callback, msg.what, args); 18985 } catch (RemoteException ignored) { 18986 } 18987 } 18988 mCallbacks.finishBroadcast(); 18989 args.recycle(); 18990 } 18991 18992 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 18993 throws RemoteException { 18994 switch (what) { 18995 case MSG_CREATED: { 18996 callback.onCreated(args.argi1, (Bundle) args.arg2); 18997 break; 18998 } 18999 case MSG_STATUS_CHANGED: { 19000 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19001 break; 19002 } 19003 } 19004 } 19005 19006 private void notifyCreated(int moveId, Bundle extras) { 19007 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19008 19009 final SomeArgs args = SomeArgs.obtain(); 19010 args.argi1 = moveId; 19011 args.arg2 = extras; 19012 obtainMessage(MSG_CREATED, args).sendToTarget(); 19013 } 19014 19015 private void notifyStatusChanged(int moveId, int status) { 19016 notifyStatusChanged(moveId, status, -1); 19017 } 19018 19019 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19020 Slog.v(TAG, "Move " + moveId + " status " + status); 19021 19022 final SomeArgs args = SomeArgs.obtain(); 19023 args.argi1 = moveId; 19024 args.argi2 = status; 19025 args.arg3 = estMillis; 19026 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19027 19028 synchronized (mLastStatus) { 19029 mLastStatus.put(moveId, status); 19030 } 19031 } 19032 } 19033 19034 private final static class OnPermissionChangeListeners extends Handler { 19035 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19036 19037 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19038 new RemoteCallbackList<>(); 19039 19040 public OnPermissionChangeListeners(Looper looper) { 19041 super(looper); 19042 } 19043 19044 @Override 19045 public void handleMessage(Message msg) { 19046 switch (msg.what) { 19047 case MSG_ON_PERMISSIONS_CHANGED: { 19048 final int uid = msg.arg1; 19049 handleOnPermissionsChanged(uid); 19050 } break; 19051 } 19052 } 19053 19054 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19055 mPermissionListeners.register(listener); 19056 19057 } 19058 19059 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19060 mPermissionListeners.unregister(listener); 19061 } 19062 19063 public void onPermissionsChanged(int uid) { 19064 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19065 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19066 } 19067 } 19068 19069 private void handleOnPermissionsChanged(int uid) { 19070 final int count = mPermissionListeners.beginBroadcast(); 19071 try { 19072 for (int i = 0; i < count; i++) { 19073 IOnPermissionsChangeListener callback = mPermissionListeners 19074 .getBroadcastItem(i); 19075 try { 19076 callback.onPermissionsChanged(uid); 19077 } catch (RemoteException e) { 19078 Log.e(TAG, "Permission listener is dead", e); 19079 } 19080 } 19081 } finally { 19082 mPermissionListeners.finishBroadcast(); 19083 } 19084 } 19085 } 19086 19087 private class PackageManagerInternalImpl extends PackageManagerInternal { 19088 @Override 19089 public void setLocationPackagesProvider(PackagesProvider provider) { 19090 synchronized (mPackages) { 19091 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19092 } 19093 } 19094 19095 @Override 19096 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19097 synchronized (mPackages) { 19098 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19099 } 19100 } 19101 19102 @Override 19103 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19104 synchronized (mPackages) { 19105 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19106 } 19107 } 19108 19109 @Override 19110 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19111 synchronized (mPackages) { 19112 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19113 } 19114 } 19115 19116 @Override 19117 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19118 synchronized (mPackages) { 19119 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19120 } 19121 } 19122 19123 @Override 19124 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19125 synchronized (mPackages) { 19126 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19127 } 19128 } 19129 19130 @Override 19131 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19132 synchronized (mPackages) { 19133 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19134 packageName, userId); 19135 } 19136 } 19137 19138 @Override 19139 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19140 synchronized (mPackages) { 19141 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19142 packageName, userId); 19143 } 19144 } 19145 19146 @Override 19147 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19148 synchronized (mPackages) { 19149 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19150 packageName, userId); 19151 } 19152 } 19153 19154 @Override 19155 public void setKeepUninstalledPackages(final List<String> packageList) { 19156 Preconditions.checkNotNull(packageList); 19157 List<String> removedFromList = null; 19158 synchronized (mPackages) { 19159 if (mKeepUninstalledPackages != null) { 19160 final int packagesCount = mKeepUninstalledPackages.size(); 19161 for (int i = 0; i < packagesCount; i++) { 19162 String oldPackage = mKeepUninstalledPackages.get(i); 19163 if (packageList != null && packageList.contains(oldPackage)) { 19164 continue; 19165 } 19166 if (removedFromList == null) { 19167 removedFromList = new ArrayList<>(); 19168 } 19169 removedFromList.add(oldPackage); 19170 } 19171 } 19172 mKeepUninstalledPackages = new ArrayList<>(packageList); 19173 if (removedFromList != null) { 19174 final int removedCount = removedFromList.size(); 19175 for (int i = 0; i < removedCount; i++) { 19176 deletePackageIfUnusedLPr(removedFromList.get(i)); 19177 } 19178 } 19179 } 19180 } 19181 19182 @Override 19183 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19184 synchronized (mPackages) { 19185 // If we do not support permission review, done. 19186 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19187 return false; 19188 } 19189 19190 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 19191 if (packageSetting == null) { 19192 return false; 19193 } 19194 19195 // Permission review applies only to apps not supporting the new permission model. 19196 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 19197 return false; 19198 } 19199 19200 // Legacy apps have the permission and get user consent on launch. 19201 PermissionsState permissionsState = packageSetting.getPermissionsState(); 19202 return permissionsState.isPermissionReviewRequired(userId); 19203 } 19204 } 19205 19206 @Override 19207 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 19208 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 19209 } 19210 } 19211 19212 @Override 19213 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 19214 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 19215 synchronized (mPackages) { 19216 final long identity = Binder.clearCallingIdentity(); 19217 try { 19218 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 19219 packageNames, userId); 19220 } finally { 19221 Binder.restoreCallingIdentity(identity); 19222 } 19223 } 19224 } 19225 19226 private static void enforceSystemOrPhoneCaller(String tag) { 19227 int callingUid = Binder.getCallingUid(); 19228 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 19229 throw new SecurityException( 19230 "Cannot call " + tag + " from UID " + callingUid); 19231 } 19232 } 19233 19234 boolean isHistoricalPackageUsageAvailable() { 19235 return mPackageUsage.isHistoricalPackageUsageAvailable(); 19236 } 19237 19238 /** 19239 * Return a <b>copy</b> of the collection of packages known to the package manager. 19240 * @return A copy of the values of mPackages. 19241 */ 19242 Collection<PackageParser.Package> getPackages() { 19243 synchronized (mPackages) { 19244 return new ArrayList<>(mPackages.values()); 19245 } 19246 } 19247} 19248