PackageManagerService.java revision e991022423c2e5b4386553af7ef3b54da7c54be1
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.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppInfo; 132import android.content.pm.EphemeralRequest; 133import android.content.pm.EphemeralResolveInfo; 134import android.content.pm.AuxiliaryResolveInfo; 135import android.content.pm.FallbackCategoryProvider; 136import android.content.pm.FeatureInfo; 137import android.content.pm.IOnPermissionsChangeListener; 138import android.content.pm.IPackageDataObserver; 139import android.content.pm.IPackageDeleteObserver; 140import android.content.pm.IPackageDeleteObserver2; 141import android.content.pm.IPackageInstallObserver2; 142import android.content.pm.IPackageInstaller; 143import android.content.pm.IPackageManager; 144import android.content.pm.IPackageMoveObserver; 145import android.content.pm.IPackageStatsObserver; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageManagerInternal; 208import android.os.storage.StorageEventListener; 209import android.os.storage.StorageManager; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.DisplayMetrics; 224import android.util.EventLog; 225import android.util.ExceptionUtils; 226import android.util.Log; 227import android.util.LogPrinter; 228import android.util.MathUtils; 229import android.util.PackageUtils; 230import android.util.Pair; 231import android.util.PrintStreamPrinter; 232import android.util.Slog; 233import android.util.SparseArray; 234import android.util.SparseBooleanArray; 235import android.util.SparseIntArray; 236import android.util.Xml; 237import android.util.jar.StrictJarFile; 238import android.view.Display; 239 240import com.android.internal.R; 241import com.android.internal.annotations.GuardedBy; 242import com.android.internal.app.IMediaContainerService; 243import com.android.internal.app.ResolverActivity; 244import com.android.internal.content.NativeLibraryHelper; 245import com.android.internal.content.PackageHelper; 246import com.android.internal.logging.MetricsLogger; 247import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 248import com.android.internal.os.IParcelFileDescriptorFactory; 249import com.android.internal.os.RoSystemProperties; 250import com.android.internal.os.SomeArgs; 251import com.android.internal.os.Zygote; 252import com.android.internal.telephony.CarrierAppUtils; 253import com.android.internal.util.ArrayUtils; 254import com.android.internal.util.FastPrintWriter; 255import com.android.internal.util.FastXmlSerializer; 256import com.android.internal.util.IndentingPrintWriter; 257import com.android.internal.util.Preconditions; 258import com.android.internal.util.XmlUtils; 259import com.android.server.AttributeCache; 260import com.android.server.BackgroundDexOptJobService; 261import com.android.server.DeviceIdleController; 262import com.android.server.EventLogTags; 263import com.android.server.FgThread; 264import com.android.server.IntentResolver; 265import com.android.server.LocalServices; 266import com.android.server.ServiceThread; 267import com.android.server.SystemConfig; 268import com.android.server.Watchdog; 269import com.android.server.net.NetworkPolicyManagerInternal; 270import com.android.server.pm.Installer.InstallerException; 271import com.android.server.pm.PermissionsState.PermissionState; 272import com.android.server.pm.Settings.DatabaseVersion; 273import com.android.server.pm.Settings.VersionInfo; 274import com.android.server.pm.dex.DexManager; 275import com.android.server.storage.DeviceStorageMonitorInternal; 276 277import dalvik.system.CloseGuard; 278import dalvik.system.DexFile; 279import dalvik.system.VMRuntime; 280 281import libcore.io.IoUtils; 282import libcore.util.EmptyArray; 283 284import org.xmlpull.v1.XmlPullParser; 285import org.xmlpull.v1.XmlPullParserException; 286import org.xmlpull.v1.XmlSerializer; 287 288import java.io.BufferedOutputStream; 289import java.io.BufferedReader; 290import java.io.ByteArrayInputStream; 291import java.io.ByteArrayOutputStream; 292import java.io.File; 293import java.io.FileDescriptor; 294import java.io.FileInputStream; 295import java.io.FileNotFoundException; 296import java.io.FileOutputStream; 297import java.io.FileReader; 298import java.io.FilenameFilter; 299import java.io.IOException; 300import java.io.PrintWriter; 301import java.nio.charset.StandardCharsets; 302import java.security.DigestInputStream; 303import java.security.MessageDigest; 304import java.security.NoSuchAlgorithmException; 305import java.security.PublicKey; 306import java.security.SecureRandom; 307import java.security.cert.Certificate; 308import java.security.cert.CertificateEncodingException; 309import java.security.cert.CertificateException; 310import java.text.SimpleDateFormat; 311import java.util.ArrayList; 312import java.util.Arrays; 313import java.util.Collection; 314import java.util.Collections; 315import java.util.Comparator; 316import java.util.Date; 317import java.util.HashSet; 318import java.util.HashMap; 319import java.util.Iterator; 320import java.util.List; 321import java.util.Map; 322import java.util.Objects; 323import java.util.Set; 324import java.util.concurrent.CountDownLatch; 325import java.util.concurrent.TimeUnit; 326import java.util.concurrent.atomic.AtomicBoolean; 327import java.util.concurrent.atomic.AtomicInteger; 328 329/** 330 * Keep track of all those APKs everywhere. 331 * <p> 332 * Internally there are two important locks: 333 * <ul> 334 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 335 * and other related state. It is a fine-grained lock that should only be held 336 * momentarily, as it's one of the most contended locks in the system. 337 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 338 * operations typically involve heavy lifting of application data on disk. Since 339 * {@code installd} is single-threaded, and it's operations can often be slow, 340 * this lock should never be acquired while already holding {@link #mPackages}. 341 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 342 * holding {@link #mInstallLock}. 343 * </ul> 344 * Many internal methods rely on the caller to hold the appropriate locks, and 345 * this contract is expressed through method name suffixes: 346 * <ul> 347 * <li>fooLI(): the caller must hold {@link #mInstallLock} 348 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 349 * being modified must be frozen 350 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 351 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 352 * </ul> 353 * <p> 354 * Because this class is very central to the platform's security; please run all 355 * CTS and unit tests whenever making modifications: 356 * 357 * <pre> 358 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 359 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 360 * </pre> 361 */ 362public class PackageManagerService extends IPackageManager.Stub { 363 static final String TAG = "PackageManager"; 364 static final boolean DEBUG_SETTINGS = false; 365 static final boolean DEBUG_PREFERRED = false; 366 static final boolean DEBUG_UPGRADE = false; 367 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 368 private static final boolean DEBUG_BACKUP = false; 369 private static final boolean DEBUG_INSTALL = false; 370 private static final boolean DEBUG_REMOVE = false; 371 private static final boolean DEBUG_BROADCASTS = false; 372 private static final boolean DEBUG_SHOW_INFO = false; 373 private static final boolean DEBUG_PACKAGE_INFO = false; 374 private static final boolean DEBUG_INTENT_MATCHING = false; 375 private static final boolean DEBUG_PACKAGE_SCANNING = false; 376 private static final boolean DEBUG_VERIFY = false; 377 private static final boolean DEBUG_FILTERS = false; 378 379 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 380 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 381 // user, but by default initialize to this. 382 public static final boolean DEBUG_DEXOPT = false; 383 384 private static final boolean DEBUG_ABI_SELECTION = false; 385 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 386 private static final boolean DEBUG_TRIAGED_MISSING = false; 387 private static final boolean DEBUG_APP_DATA = false; 388 389 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 390 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 391 392 private static final boolean DISABLE_EPHEMERAL_APPS = false; 393 private static final boolean HIDE_EPHEMERAL_APIS = false; 394 395 private static final boolean ENABLE_QUOTA = 396 SystemProperties.getBoolean("persist.fw.quota", false); 397 398 private static final int RADIO_UID = Process.PHONE_UID; 399 private static final int LOG_UID = Process.LOG_UID; 400 private static final int NFC_UID = Process.NFC_UID; 401 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 402 private static final int SHELL_UID = Process.SHELL_UID; 403 404 // Cap the size of permission trees that 3rd party apps can define 405 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 406 407 // Suffix used during package installation when copying/moving 408 // package apks to install directory. 409 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 410 411 static final int SCAN_NO_DEX = 1<<1; 412 static final int SCAN_FORCE_DEX = 1<<2; 413 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 414 static final int SCAN_NEW_INSTALL = 1<<4; 415 static final int SCAN_UPDATE_TIME = 1<<5; 416 static final int SCAN_BOOTING = 1<<6; 417 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 418 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 419 static final int SCAN_REPLACING = 1<<9; 420 static final int SCAN_REQUIRE_KNOWN = 1<<10; 421 static final int SCAN_MOVE = 1<<11; 422 static final int SCAN_INITIAL = 1<<12; 423 static final int SCAN_CHECK_ONLY = 1<<13; 424 static final int SCAN_DONT_KILL_APP = 1<<14; 425 static final int SCAN_IGNORE_FROZEN = 1<<15; 426 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 427 static final int SCAN_AS_INSTANT_APP = 1<<17; 428 static final int SCAN_AS_FULL_APP = 1<<18; 429 /** Should not be with the scan flags */ 430 static final int FLAGS_REMOVE_CHATTY = 1<<31; 431 432 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 433 434 private static final int[] EMPTY_INT_ARRAY = new int[0]; 435 436 /** 437 * Timeout (in milliseconds) after which the watchdog should declare that 438 * our handler thread is wedged. The usual default for such things is one 439 * minute but we sometimes do very lengthy I/O operations on this thread, 440 * such as installing multi-gigabyte applications, so ours needs to be longer. 441 */ 442 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 443 444 /** 445 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 446 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 447 * settings entry if available, otherwise we use the hardcoded default. If it's been 448 * more than this long since the last fstrim, we force one during the boot sequence. 449 * 450 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 451 * one gets run at the next available charging+idle time. This final mandatory 452 * no-fstrim check kicks in only of the other scheduling criteria is never met. 453 */ 454 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 455 456 /** 457 * Whether verification is enabled by default. 458 */ 459 private static final boolean DEFAULT_VERIFY_ENABLE = true; 460 461 /** 462 * The default maximum time to wait for the verification agent to return in 463 * milliseconds. 464 */ 465 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 466 467 /** 468 * The default response for package verification timeout. 469 * 470 * This can be either PackageManager.VERIFICATION_ALLOW or 471 * PackageManager.VERIFICATION_REJECT. 472 */ 473 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 474 475 static final String PLATFORM_PACKAGE_NAME = "android"; 476 477 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 478 479 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 480 DEFAULT_CONTAINER_PACKAGE, 481 "com.android.defcontainer.DefaultContainerService"); 482 483 private static final String KILL_APP_REASON_GIDS_CHANGED = 484 "permission grant or revoke changed gids"; 485 486 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 487 "permissions revoked"; 488 489 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 490 491 private static final String PACKAGE_SCHEME = "package"; 492 493 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 494 /** 495 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 496 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 497 * VENDOR_OVERLAY_DIR. 498 */ 499 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 500 /** 501 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 502 * is in VENDOR_OVERLAY_THEME_PROPERTY. 503 */ 504 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 505 = "persist.vendor.overlay.theme"; 506 507 /** Permission grant: not grant the permission. */ 508 private static final int GRANT_DENIED = 1; 509 510 /** Permission grant: grant the permission as an install permission. */ 511 private static final int GRANT_INSTALL = 2; 512 513 /** Permission grant: grant the permission as a runtime one. */ 514 private static final int GRANT_RUNTIME = 3; 515 516 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 517 private static final int GRANT_UPGRADE = 4; 518 519 /** Canonical intent used to identify what counts as a "web browser" app */ 520 private static final Intent sBrowserIntent; 521 static { 522 sBrowserIntent = new Intent(); 523 sBrowserIntent.setAction(Intent.ACTION_VIEW); 524 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 525 sBrowserIntent.setData(Uri.parse("http:")); 526 } 527 528 /** 529 * The set of all protected actions [i.e. those actions for which a high priority 530 * intent filter is disallowed]. 531 */ 532 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 533 static { 534 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 535 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 536 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 537 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 538 } 539 540 // Compilation reasons. 541 public static final int REASON_FIRST_BOOT = 0; 542 public static final int REASON_BOOT = 1; 543 public static final int REASON_INSTALL = 2; 544 public static final int REASON_BACKGROUND_DEXOPT = 3; 545 public static final int REASON_AB_OTA = 4; 546 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 547 public static final int REASON_SHARED_APK = 6; 548 public static final int REASON_FORCED_DEXOPT = 7; 549 public static final int REASON_CORE_APP = 8; 550 551 public static final int REASON_LAST = REASON_CORE_APP; 552 553 /** All dangerous permission names in the same order as the events in MetricsEvent */ 554 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 555 Manifest.permission.READ_CALENDAR, 556 Manifest.permission.WRITE_CALENDAR, 557 Manifest.permission.CAMERA, 558 Manifest.permission.READ_CONTACTS, 559 Manifest.permission.WRITE_CONTACTS, 560 Manifest.permission.GET_ACCOUNTS, 561 Manifest.permission.ACCESS_FINE_LOCATION, 562 Manifest.permission.ACCESS_COARSE_LOCATION, 563 Manifest.permission.RECORD_AUDIO, 564 Manifest.permission.READ_PHONE_STATE, 565 Manifest.permission.CALL_PHONE, 566 Manifest.permission.READ_CALL_LOG, 567 Manifest.permission.WRITE_CALL_LOG, 568 Manifest.permission.ADD_VOICEMAIL, 569 Manifest.permission.USE_SIP, 570 Manifest.permission.PROCESS_OUTGOING_CALLS, 571 Manifest.permission.READ_CELL_BROADCASTS, 572 Manifest.permission.BODY_SENSORS, 573 Manifest.permission.SEND_SMS, 574 Manifest.permission.RECEIVE_SMS, 575 Manifest.permission.READ_SMS, 576 Manifest.permission.RECEIVE_WAP_PUSH, 577 Manifest.permission.RECEIVE_MMS, 578 Manifest.permission.READ_EXTERNAL_STORAGE, 579 Manifest.permission.WRITE_EXTERNAL_STORAGE, 580 Manifest.permission.READ_PHONE_NUMBER); 581 582 583 /** 584 * Version number for the package parser cache. Increment this whenever the format or 585 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 586 */ 587 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 588 589 /** 590 * Whether the package parser cache is enabled. 591 */ 592 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 593 594 final ServiceThread mHandlerThread; 595 596 final PackageHandler mHandler; 597 598 private final ProcessLoggingHandler mProcessLoggingHandler; 599 600 /** 601 * Messages for {@link #mHandler} that need to wait for system ready before 602 * being dispatched. 603 */ 604 private ArrayList<Message> mPostSystemReadyMessages; 605 606 final int mSdkVersion = Build.VERSION.SDK_INT; 607 608 final Context mContext; 609 final boolean mFactoryTest; 610 final boolean mOnlyCore; 611 final DisplayMetrics mMetrics; 612 final int mDefParseFlags; 613 final String[] mSeparateProcesses; 614 final boolean mIsUpgrade; 615 final boolean mIsPreNUpgrade; 616 final boolean mIsPreNMR1Upgrade; 617 618 @GuardedBy("mPackages") 619 private boolean mDexOptDialogShown; 620 621 /** The location for ASEC container files on internal storage. */ 622 final String mAsecInternalPath; 623 624 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 625 // LOCK HELD. Can be called with mInstallLock held. 626 @GuardedBy("mInstallLock") 627 final Installer mInstaller; 628 629 /** Directory where installed third-party apps stored */ 630 final File mAppInstallDir; 631 632 /** 633 * Directory to which applications installed internally have their 634 * 32 bit native libraries copied. 635 */ 636 private File mAppLib32InstallDir; 637 638 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 639 // apps. 640 final File mDrmAppPrivateInstallDir; 641 642 // ---------------------------------------------------------------- 643 644 // Lock for state used when installing and doing other long running 645 // operations. Methods that must be called with this lock held have 646 // the suffix "LI". 647 final Object mInstallLock = new Object(); 648 649 // ---------------------------------------------------------------- 650 651 // Keys are String (package name), values are Package. This also serves 652 // as the lock for the global state. Methods that must be called with 653 // this lock held have the prefix "LP". 654 @GuardedBy("mPackages") 655 final ArrayMap<String, PackageParser.Package> mPackages = 656 new ArrayMap<String, PackageParser.Package>(); 657 658 final ArrayMap<String, Set<String>> mKnownCodebase = 659 new ArrayMap<String, Set<String>>(); 660 661 // Tracks available target package names -> overlay package paths. 662 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 663 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 664 665 /** 666 * Tracks new system packages [received in an OTA] that we expect to 667 * find updated user-installed versions. Keys are package name, values 668 * are package location. 669 */ 670 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 671 /** 672 * Tracks high priority intent filters for protected actions. During boot, certain 673 * filter actions are protected and should never be allowed to have a high priority 674 * intent filter for them. However, there is one, and only one exception -- the 675 * setup wizard. It must be able to define a high priority intent filter for these 676 * actions to ensure there are no escapes from the wizard. We need to delay processing 677 * of these during boot as we need to look at all of the system packages in order 678 * to know which component is the setup wizard. 679 */ 680 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 681 /** 682 * Whether or not processing protected filters should be deferred. 683 */ 684 private boolean mDeferProtectedFilters = true; 685 686 /** 687 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 688 */ 689 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 690 /** 691 * Whether or not system app permissions should be promoted from install to runtime. 692 */ 693 boolean mPromoteSystemApps; 694 695 @GuardedBy("mPackages") 696 final Settings mSettings; 697 698 /** 699 * Set of package names that are currently "frozen", which means active 700 * surgery is being done on the code/data for that package. The platform 701 * will refuse to launch frozen packages to avoid race conditions. 702 * 703 * @see PackageFreezer 704 */ 705 @GuardedBy("mPackages") 706 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 707 708 final ProtectedPackages mProtectedPackages; 709 710 boolean mFirstBoot; 711 712 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 713 714 // System configuration read by SystemConfig. 715 final int[] mGlobalGids; 716 final SparseArray<ArraySet<String>> mSystemPermissions; 717 @GuardedBy("mAvailableFeatures") 718 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 719 720 // If mac_permissions.xml was found for seinfo labeling. 721 boolean mFoundPolicyFile; 722 723 private final InstantAppRegistry mInstantAppRegistry; 724 725 @GuardedBy("mPackages") 726 int mChangedPackagesSequenceNumber; 727 /** 728 * List of changed [installed, removed or updated] packages. 729 * mapping from user id -> sequence number -> package name 730 */ 731 @GuardedBy("mPackages") 732 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 733 /** 734 * The sequence number of the last change to a package. 735 * mapping from user id -> package name -> sequence number 736 */ 737 @GuardedBy("mPackages") 738 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 739 740 public static final class SharedLibraryEntry { 741 public final String path; 742 public final String apk; 743 public final SharedLibraryInfo info; 744 745 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 746 String declaringPackageName, int declaringPackageVersionCode) { 747 path = _path; 748 apk = _apk; 749 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 750 declaringPackageName, declaringPackageVersionCode), null); 751 } 752 } 753 754 // Currently known shared libraries. 755 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 756 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 757 new ArrayMap<>(); 758 759 // All available activities, for your resolving pleasure. 760 final ActivityIntentResolver mActivities = 761 new ActivityIntentResolver(); 762 763 // All available receivers, for your resolving pleasure. 764 final ActivityIntentResolver mReceivers = 765 new ActivityIntentResolver(); 766 767 // All available services, for your resolving pleasure. 768 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 769 770 // All available providers, for your resolving pleasure. 771 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 772 773 // Mapping from provider base names (first directory in content URI codePath) 774 // to the provider information. 775 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 776 new ArrayMap<String, PackageParser.Provider>(); 777 778 // Mapping from instrumentation class names to info about them. 779 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 780 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 781 782 // Mapping from permission names to info about them. 783 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 784 new ArrayMap<String, PackageParser.PermissionGroup>(); 785 786 // Packages whose data we have transfered into another package, thus 787 // should no longer exist. 788 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 789 790 // Broadcast actions that are only available to the system. 791 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 792 793 /** List of packages waiting for verification. */ 794 final SparseArray<PackageVerificationState> mPendingVerification 795 = new SparseArray<PackageVerificationState>(); 796 797 /** Set of packages associated with each app op permission. */ 798 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 799 800 final PackageInstallerService mInstallerService; 801 802 private final PackageDexOptimizer mPackageDexOptimizer; 803 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 804 // is used by other apps). 805 private final DexManager mDexManager; 806 807 private AtomicInteger mNextMoveId = new AtomicInteger(); 808 private final MoveCallbacks mMoveCallbacks; 809 810 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 811 812 // Cache of users who need badging. 813 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 814 815 /** Token for keys in mPendingVerification. */ 816 private int mPendingVerificationToken = 0; 817 818 volatile boolean mSystemReady; 819 volatile boolean mSafeMode; 820 volatile boolean mHasSystemUidErrors; 821 822 ApplicationInfo mAndroidApplication; 823 final ActivityInfo mResolveActivity = new ActivityInfo(); 824 final ResolveInfo mResolveInfo = new ResolveInfo(); 825 ComponentName mResolveComponentName; 826 PackageParser.Package mPlatformPackage; 827 ComponentName mCustomResolverComponentName; 828 829 boolean mResolverReplaced = false; 830 831 private final @Nullable ComponentName mIntentFilterVerifierComponent; 832 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 833 834 private int mIntentFilterVerificationToken = 0; 835 836 /** The service connection to the ephemeral resolver */ 837 final EphemeralResolverConnection mInstantAppResolverConnection; 838 839 /** Component used to install ephemeral applications */ 840 ComponentName mInstantAppInstallerComponent; 841 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 842 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 843 844 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 845 = new SparseArray<IntentFilterVerificationState>(); 846 847 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 848 849 // List of packages names to keep cached, even if they are uninstalled for all users 850 private List<String> mKeepUninstalledPackages; 851 852 private UserManagerInternal mUserManagerInternal; 853 854 private DeviceIdleController.LocalService mDeviceIdleController; 855 856 private File mCacheDir; 857 858 private ArraySet<String> mPrivappPermissionsViolations; 859 860 private static class IFVerificationParams { 861 PackageParser.Package pkg; 862 boolean replacing; 863 int userId; 864 int verifierUid; 865 866 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 867 int _userId, int _verifierUid) { 868 pkg = _pkg; 869 replacing = _replacing; 870 userId = _userId; 871 replacing = _replacing; 872 verifierUid = _verifierUid; 873 } 874 } 875 876 private interface IntentFilterVerifier<T extends IntentFilter> { 877 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 878 T filter, String packageName); 879 void startVerifications(int userId); 880 void receiveVerificationResponse(int verificationId); 881 } 882 883 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 884 private Context mContext; 885 private ComponentName mIntentFilterVerifierComponent; 886 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 887 888 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 889 mContext = context; 890 mIntentFilterVerifierComponent = verifierComponent; 891 } 892 893 private String getDefaultScheme() { 894 return IntentFilter.SCHEME_HTTPS; 895 } 896 897 @Override 898 public void startVerifications(int userId) { 899 // Launch verifications requests 900 int count = mCurrentIntentFilterVerifications.size(); 901 for (int n=0; n<count; n++) { 902 int verificationId = mCurrentIntentFilterVerifications.get(n); 903 final IntentFilterVerificationState ivs = 904 mIntentFilterVerificationStates.get(verificationId); 905 906 String packageName = ivs.getPackageName(); 907 908 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 909 final int filterCount = filters.size(); 910 ArraySet<String> domainsSet = new ArraySet<>(); 911 for (int m=0; m<filterCount; m++) { 912 PackageParser.ActivityIntentInfo filter = filters.get(m); 913 domainsSet.addAll(filter.getHostsList()); 914 } 915 synchronized (mPackages) { 916 if (mSettings.createIntentFilterVerificationIfNeededLPw( 917 packageName, domainsSet) != null) { 918 scheduleWriteSettingsLocked(); 919 } 920 } 921 sendVerificationRequest(userId, verificationId, ivs); 922 } 923 mCurrentIntentFilterVerifications.clear(); 924 } 925 926 private void sendVerificationRequest(int userId, int verificationId, 927 IntentFilterVerificationState ivs) { 928 929 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 930 verificationIntent.putExtra( 931 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 932 verificationId); 933 verificationIntent.putExtra( 934 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 935 getDefaultScheme()); 936 verificationIntent.putExtra( 937 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 938 ivs.getHostsString()); 939 verificationIntent.putExtra( 940 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 941 ivs.getPackageName()); 942 verificationIntent.setComponent(mIntentFilterVerifierComponent); 943 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 944 945 UserHandle user = new UserHandle(userId); 946 mContext.sendBroadcastAsUser(verificationIntent, user); 947 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 948 "Sending IntentFilter verification broadcast"); 949 } 950 951 public void receiveVerificationResponse(int verificationId) { 952 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 953 954 final boolean verified = ivs.isVerified(); 955 956 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 957 final int count = filters.size(); 958 if (DEBUG_DOMAIN_VERIFICATION) { 959 Slog.i(TAG, "Received verification response " + verificationId 960 + " for " + count + " filters, verified=" + verified); 961 } 962 for (int n=0; n<count; n++) { 963 PackageParser.ActivityIntentInfo filter = filters.get(n); 964 filter.setVerified(verified); 965 966 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 967 + " verified with result:" + verified + " and hosts:" 968 + ivs.getHostsString()); 969 } 970 971 mIntentFilterVerificationStates.remove(verificationId); 972 973 final String packageName = ivs.getPackageName(); 974 IntentFilterVerificationInfo ivi = null; 975 976 synchronized (mPackages) { 977 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 978 } 979 if (ivi == null) { 980 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 981 + verificationId + " packageName:" + packageName); 982 return; 983 } 984 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 985 "Updating IntentFilterVerificationInfo for package " + packageName 986 +" verificationId:" + verificationId); 987 988 synchronized (mPackages) { 989 if (verified) { 990 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 991 } else { 992 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 993 } 994 scheduleWriteSettingsLocked(); 995 996 final int userId = ivs.getUserId(); 997 if (userId != UserHandle.USER_ALL) { 998 final int userStatus = 999 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1000 1001 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1002 boolean needUpdate = false; 1003 1004 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1005 // already been set by the User thru the Disambiguation dialog 1006 switch (userStatus) { 1007 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1008 if (verified) { 1009 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1010 } else { 1011 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1012 } 1013 needUpdate = true; 1014 break; 1015 1016 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1017 if (verified) { 1018 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1019 needUpdate = true; 1020 } 1021 break; 1022 1023 default: 1024 // Nothing to do 1025 } 1026 1027 if (needUpdate) { 1028 mSettings.updateIntentFilterVerificationStatusLPw( 1029 packageName, updatedStatus, userId); 1030 scheduleWritePackageRestrictionsLocked(userId); 1031 } 1032 } 1033 } 1034 } 1035 1036 @Override 1037 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1038 ActivityIntentInfo filter, String packageName) { 1039 if (!hasValidDomains(filter)) { 1040 return false; 1041 } 1042 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1043 if (ivs == null) { 1044 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1045 packageName); 1046 } 1047 if (DEBUG_DOMAIN_VERIFICATION) { 1048 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1049 } 1050 ivs.addFilter(filter); 1051 return true; 1052 } 1053 1054 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1055 int userId, int verificationId, String packageName) { 1056 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1057 verifierUid, userId, packageName); 1058 ivs.setPendingState(); 1059 synchronized (mPackages) { 1060 mIntentFilterVerificationStates.append(verificationId, ivs); 1061 mCurrentIntentFilterVerifications.add(verificationId); 1062 } 1063 return ivs; 1064 } 1065 } 1066 1067 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1068 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1069 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1070 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1071 } 1072 1073 // Set of pending broadcasts for aggregating enable/disable of components. 1074 static class PendingPackageBroadcasts { 1075 // for each user id, a map of <package name -> components within that package> 1076 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1077 1078 public PendingPackageBroadcasts() { 1079 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1080 } 1081 1082 public ArrayList<String> get(int userId, String packageName) { 1083 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1084 return packages.get(packageName); 1085 } 1086 1087 public void put(int userId, String packageName, ArrayList<String> components) { 1088 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1089 packages.put(packageName, components); 1090 } 1091 1092 public void remove(int userId, String packageName) { 1093 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1094 if (packages != null) { 1095 packages.remove(packageName); 1096 } 1097 } 1098 1099 public void remove(int userId) { 1100 mUidMap.remove(userId); 1101 } 1102 1103 public int userIdCount() { 1104 return mUidMap.size(); 1105 } 1106 1107 public int userIdAt(int n) { 1108 return mUidMap.keyAt(n); 1109 } 1110 1111 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1112 return mUidMap.get(userId); 1113 } 1114 1115 public int size() { 1116 // total number of pending broadcast entries across all userIds 1117 int num = 0; 1118 for (int i = 0; i< mUidMap.size(); i++) { 1119 num += mUidMap.valueAt(i).size(); 1120 } 1121 return num; 1122 } 1123 1124 public void clear() { 1125 mUidMap.clear(); 1126 } 1127 1128 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1129 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1130 if (map == null) { 1131 map = new ArrayMap<String, ArrayList<String>>(); 1132 mUidMap.put(userId, map); 1133 } 1134 return map; 1135 } 1136 } 1137 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1138 1139 // Service Connection to remote media container service to copy 1140 // package uri's from external media onto secure containers 1141 // or internal storage. 1142 private IMediaContainerService mContainerService = null; 1143 1144 static final int SEND_PENDING_BROADCAST = 1; 1145 static final int MCS_BOUND = 3; 1146 static final int END_COPY = 4; 1147 static final int INIT_COPY = 5; 1148 static final int MCS_UNBIND = 6; 1149 static final int START_CLEANING_PACKAGE = 7; 1150 static final int FIND_INSTALL_LOC = 8; 1151 static final int POST_INSTALL = 9; 1152 static final int MCS_RECONNECT = 10; 1153 static final int MCS_GIVE_UP = 11; 1154 static final int UPDATED_MEDIA_STATUS = 12; 1155 static final int WRITE_SETTINGS = 13; 1156 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1157 static final int PACKAGE_VERIFIED = 15; 1158 static final int CHECK_PENDING_VERIFICATION = 16; 1159 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1160 static final int INTENT_FILTER_VERIFIED = 18; 1161 static final int WRITE_PACKAGE_LIST = 19; 1162 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1163 1164 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1165 1166 // Delay time in millisecs 1167 static final int BROADCAST_DELAY = 10 * 1000; 1168 1169 static UserManagerService sUserManager; 1170 1171 // Stores a list of users whose package restrictions file needs to be updated 1172 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1173 1174 final private DefaultContainerConnection mDefContainerConn = 1175 new DefaultContainerConnection(); 1176 class DefaultContainerConnection implements ServiceConnection { 1177 public void onServiceConnected(ComponentName name, IBinder service) { 1178 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1179 final IMediaContainerService imcs = IMediaContainerService.Stub 1180 .asInterface(Binder.allowBlocking(service)); 1181 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1182 } 1183 1184 public void onServiceDisconnected(ComponentName name) { 1185 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1186 } 1187 } 1188 1189 // Recordkeeping of restore-after-install operations that are currently in flight 1190 // between the Package Manager and the Backup Manager 1191 static class PostInstallData { 1192 public InstallArgs args; 1193 public PackageInstalledInfo res; 1194 1195 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1196 args = _a; 1197 res = _r; 1198 } 1199 } 1200 1201 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1202 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1203 1204 // XML tags for backup/restore of various bits of state 1205 private static final String TAG_PREFERRED_BACKUP = "pa"; 1206 private static final String TAG_DEFAULT_APPS = "da"; 1207 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1208 1209 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1210 private static final String TAG_ALL_GRANTS = "rt-grants"; 1211 private static final String TAG_GRANT = "grant"; 1212 private static final String ATTR_PACKAGE_NAME = "pkg"; 1213 1214 private static final String TAG_PERMISSION = "perm"; 1215 private static final String ATTR_PERMISSION_NAME = "name"; 1216 private static final String ATTR_IS_GRANTED = "g"; 1217 private static final String ATTR_USER_SET = "set"; 1218 private static final String ATTR_USER_FIXED = "fixed"; 1219 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1220 1221 // System/policy permission grants are not backed up 1222 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1223 FLAG_PERMISSION_POLICY_FIXED 1224 | FLAG_PERMISSION_SYSTEM_FIXED 1225 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1226 1227 // And we back up these user-adjusted states 1228 private static final int USER_RUNTIME_GRANT_MASK = 1229 FLAG_PERMISSION_USER_SET 1230 | FLAG_PERMISSION_USER_FIXED 1231 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1232 1233 final @Nullable String mRequiredVerifierPackage; 1234 final @NonNull String mRequiredInstallerPackage; 1235 final @NonNull String mRequiredUninstallerPackage; 1236 final @Nullable String mSetupWizardPackage; 1237 final @Nullable String mStorageManagerPackage; 1238 final @NonNull String mServicesSystemSharedLibraryPackageName; 1239 final @NonNull String mSharedSystemSharedLibraryPackageName; 1240 1241 final boolean mPermissionReviewRequired; 1242 1243 private final PackageUsage mPackageUsage = new PackageUsage(); 1244 private final CompilerStats mCompilerStats = new CompilerStats(); 1245 1246 class PackageHandler extends Handler { 1247 private boolean mBound = false; 1248 final ArrayList<HandlerParams> mPendingInstalls = 1249 new ArrayList<HandlerParams>(); 1250 1251 private boolean connectToService() { 1252 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1253 " DefaultContainerService"); 1254 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1256 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1257 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1258 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1259 mBound = true; 1260 return true; 1261 } 1262 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1263 return false; 1264 } 1265 1266 private void disconnectService() { 1267 mContainerService = null; 1268 mBound = false; 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1270 mContext.unbindService(mDefContainerConn); 1271 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1272 } 1273 1274 PackageHandler(Looper looper) { 1275 super(looper); 1276 } 1277 1278 public void handleMessage(Message msg) { 1279 try { 1280 doHandleMessage(msg); 1281 } finally { 1282 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1283 } 1284 } 1285 1286 void doHandleMessage(Message msg) { 1287 switch (msg.what) { 1288 case INIT_COPY: { 1289 HandlerParams params = (HandlerParams) msg.obj; 1290 int idx = mPendingInstalls.size(); 1291 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1292 // If a bind was already initiated we dont really 1293 // need to do anything. The pending install 1294 // will be processed later on. 1295 if (!mBound) { 1296 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1297 System.identityHashCode(mHandler)); 1298 // If this is the only one pending we might 1299 // have to bind to the service again. 1300 if (!connectToService()) { 1301 Slog.e(TAG, "Failed to bind to media container service"); 1302 params.serviceError(); 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1304 System.identityHashCode(mHandler)); 1305 if (params.traceMethod != null) { 1306 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1307 params.traceCookie); 1308 } 1309 return; 1310 } else { 1311 // Once we bind to the service, the first 1312 // pending request will be processed. 1313 mPendingInstalls.add(idx, params); 1314 } 1315 } else { 1316 mPendingInstalls.add(idx, params); 1317 // Already bound to the service. Just make 1318 // sure we trigger off processing the first request. 1319 if (idx == 0) { 1320 mHandler.sendEmptyMessage(MCS_BOUND); 1321 } 1322 } 1323 break; 1324 } 1325 case MCS_BOUND: { 1326 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1327 if (msg.obj != null) { 1328 mContainerService = (IMediaContainerService) msg.obj; 1329 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1330 System.identityHashCode(mHandler)); 1331 } 1332 if (mContainerService == null) { 1333 if (!mBound) { 1334 // Something seriously wrong since we are not bound and we are not 1335 // waiting for connection. Bail out. 1336 Slog.e(TAG, "Cannot bind to media container service"); 1337 for (HandlerParams params : mPendingInstalls) { 1338 // Indicate service bind error 1339 params.serviceError(); 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1341 System.identityHashCode(params)); 1342 if (params.traceMethod != null) { 1343 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1344 params.traceMethod, params.traceCookie); 1345 } 1346 return; 1347 } 1348 mPendingInstalls.clear(); 1349 } else { 1350 Slog.w(TAG, "Waiting to connect to media container service"); 1351 } 1352 } else if (mPendingInstalls.size() > 0) { 1353 HandlerParams params = mPendingInstalls.get(0); 1354 if (params != null) { 1355 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1356 System.identityHashCode(params)); 1357 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1358 if (params.startCopy()) { 1359 // We are done... look for more work or to 1360 // go idle. 1361 if (DEBUG_SD_INSTALL) Log.i(TAG, 1362 "Checking for more work or unbind..."); 1363 // Delete pending install 1364 if (mPendingInstalls.size() > 0) { 1365 mPendingInstalls.remove(0); 1366 } 1367 if (mPendingInstalls.size() == 0) { 1368 if (mBound) { 1369 if (DEBUG_SD_INSTALL) Log.i(TAG, 1370 "Posting delayed MCS_UNBIND"); 1371 removeMessages(MCS_UNBIND); 1372 Message ubmsg = obtainMessage(MCS_UNBIND); 1373 // Unbind after a little delay, to avoid 1374 // continual thrashing. 1375 sendMessageDelayed(ubmsg, 10000); 1376 } 1377 } else { 1378 // There are more pending requests in queue. 1379 // Just post MCS_BOUND message to trigger processing 1380 // of next pending install. 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, 1382 "Posting MCS_BOUND for next work"); 1383 mHandler.sendEmptyMessage(MCS_BOUND); 1384 } 1385 } 1386 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1387 } 1388 } else { 1389 // Should never happen ideally. 1390 Slog.w(TAG, "Empty queue"); 1391 } 1392 break; 1393 } 1394 case MCS_RECONNECT: { 1395 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1396 if (mPendingInstalls.size() > 0) { 1397 if (mBound) { 1398 disconnectService(); 1399 } 1400 if (!connectToService()) { 1401 Slog.e(TAG, "Failed to bind to media container service"); 1402 for (HandlerParams params : mPendingInstalls) { 1403 // Indicate service bind error 1404 params.serviceError(); 1405 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1406 System.identityHashCode(params)); 1407 } 1408 mPendingInstalls.clear(); 1409 } 1410 } 1411 break; 1412 } 1413 case MCS_UNBIND: { 1414 // If there is no actual work left, then time to unbind. 1415 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1416 1417 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1418 if (mBound) { 1419 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1420 1421 disconnectService(); 1422 } 1423 } else if (mPendingInstalls.size() > 0) { 1424 // There are more pending requests in queue. 1425 // Just post MCS_BOUND message to trigger processing 1426 // of next pending install. 1427 mHandler.sendEmptyMessage(MCS_BOUND); 1428 } 1429 1430 break; 1431 } 1432 case MCS_GIVE_UP: { 1433 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1434 HandlerParams params = mPendingInstalls.remove(0); 1435 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1436 System.identityHashCode(params)); 1437 break; 1438 } 1439 case SEND_PENDING_BROADCAST: { 1440 String packages[]; 1441 ArrayList<String> components[]; 1442 int size = 0; 1443 int uids[]; 1444 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1445 synchronized (mPackages) { 1446 if (mPendingBroadcasts == null) { 1447 return; 1448 } 1449 size = mPendingBroadcasts.size(); 1450 if (size <= 0) { 1451 // Nothing to be done. Just return 1452 return; 1453 } 1454 packages = new String[size]; 1455 components = new ArrayList[size]; 1456 uids = new int[size]; 1457 int i = 0; // filling out the above arrays 1458 1459 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1460 int packageUserId = mPendingBroadcasts.userIdAt(n); 1461 Iterator<Map.Entry<String, ArrayList<String>>> it 1462 = mPendingBroadcasts.packagesForUserId(packageUserId) 1463 .entrySet().iterator(); 1464 while (it.hasNext() && i < size) { 1465 Map.Entry<String, ArrayList<String>> ent = it.next(); 1466 packages[i] = ent.getKey(); 1467 components[i] = ent.getValue(); 1468 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1469 uids[i] = (ps != null) 1470 ? UserHandle.getUid(packageUserId, ps.appId) 1471 : -1; 1472 i++; 1473 } 1474 } 1475 size = i; 1476 mPendingBroadcasts.clear(); 1477 } 1478 // Send broadcasts 1479 for (int i = 0; i < size; i++) { 1480 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1481 } 1482 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1483 break; 1484 } 1485 case START_CLEANING_PACKAGE: { 1486 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1487 final String packageName = (String)msg.obj; 1488 final int userId = msg.arg1; 1489 final boolean andCode = msg.arg2 != 0; 1490 synchronized (mPackages) { 1491 if (userId == UserHandle.USER_ALL) { 1492 int[] users = sUserManager.getUserIds(); 1493 for (int user : users) { 1494 mSettings.addPackageToCleanLPw( 1495 new PackageCleanItem(user, packageName, andCode)); 1496 } 1497 } else { 1498 mSettings.addPackageToCleanLPw( 1499 new PackageCleanItem(userId, packageName, andCode)); 1500 } 1501 } 1502 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1503 startCleaningPackages(); 1504 } break; 1505 case POST_INSTALL: { 1506 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1507 1508 PostInstallData data = mRunningInstalls.get(msg.arg1); 1509 final boolean didRestore = (msg.arg2 != 0); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, didRestore, args.installerPackageName, 1525 args.observer); 1526 1527 // Handle the child packages 1528 final int childCount = (parentRes.addedChildPackages != null) 1529 ? parentRes.addedChildPackages.size() : 0; 1530 for (int i = 0; i < childCount; i++) { 1531 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1532 handlePackagePostInstall(childRes, grantPermissions, killApp, 1533 grantedPermissions, false, args.installerPackageName, 1534 args.observer); 1535 } 1536 1537 // Log tracing if needed 1538 if (args.traceMethod != null) { 1539 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1540 args.traceCookie); 1541 } 1542 } else { 1543 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1544 } 1545 1546 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1547 } break; 1548 case UPDATED_MEDIA_STATUS: { 1549 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1550 boolean reportStatus = msg.arg1 == 1; 1551 boolean doGc = msg.arg2 == 1; 1552 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1553 if (doGc) { 1554 // Force a gc to clear up stale containers. 1555 Runtime.getRuntime().gc(); 1556 } 1557 if (msg.obj != null) { 1558 @SuppressWarnings("unchecked") 1559 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1561 // Unload containers 1562 unloadAllContainers(args); 1563 } 1564 if (reportStatus) { 1565 try { 1566 if (DEBUG_SD_INSTALL) Log.i(TAG, 1567 "Invoking StorageManagerService call back"); 1568 PackageHelper.getStorageManager().finishMediaUpdate(); 1569 } catch (RemoteException e) { 1570 Log.e(TAG, "StorageManagerService not running?"); 1571 } 1572 } 1573 } break; 1574 case WRITE_SETTINGS: { 1575 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1576 synchronized (mPackages) { 1577 removeMessages(WRITE_SETTINGS); 1578 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1579 mSettings.writeLPr(); 1580 mDirtyUsers.clear(); 1581 } 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1583 } break; 1584 case WRITE_PACKAGE_RESTRICTIONS: { 1585 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1586 synchronized (mPackages) { 1587 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1588 for (int userId : mDirtyUsers) { 1589 mSettings.writePackageRestrictionsLPr(userId); 1590 } 1591 mDirtyUsers.clear(); 1592 } 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1594 } break; 1595 case WRITE_PACKAGE_LIST: { 1596 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1597 synchronized (mPackages) { 1598 removeMessages(WRITE_PACKAGE_LIST); 1599 mSettings.writePackageListLPr(msg.arg1); 1600 } 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1602 } break; 1603 case CHECK_PENDING_VERIFICATION: { 1604 final int verificationId = msg.arg1; 1605 final PackageVerificationState state = mPendingVerification.get(verificationId); 1606 1607 if ((state != null) && !state.timeoutExtended()) { 1608 final InstallArgs args = state.getInstallArgs(); 1609 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1610 1611 Slog.i(TAG, "Verification timed out for " + originUri); 1612 mPendingVerification.remove(verificationId); 1613 1614 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1615 1616 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1617 Slog.i(TAG, "Continuing with installation of " + originUri); 1618 state.setVerifierResponse(Binder.getCallingUid(), 1619 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1620 broadcastPackageVerified(verificationId, originUri, 1621 PackageManager.VERIFICATION_ALLOW, 1622 state.getInstallArgs().getUser()); 1623 try { 1624 ret = args.copyApk(mContainerService, true); 1625 } catch (RemoteException e) { 1626 Slog.e(TAG, "Could not contact the ContainerService"); 1627 } 1628 } else { 1629 broadcastPackageVerified(verificationId, originUri, 1630 PackageManager.VERIFICATION_REJECT, 1631 state.getInstallArgs().getUser()); 1632 } 1633 1634 Trace.asyncTraceEnd( 1635 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1636 1637 processPendingInstall(args, ret); 1638 mHandler.sendEmptyMessage(MCS_UNBIND); 1639 } 1640 break; 1641 } 1642 case PACKAGE_VERIFIED: { 1643 final int verificationId = msg.arg1; 1644 1645 final PackageVerificationState state = mPendingVerification.get(verificationId); 1646 if (state == null) { 1647 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1648 break; 1649 } 1650 1651 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1652 1653 state.setVerifierResponse(response.callerUid, response.code); 1654 1655 if (state.isVerificationComplete()) { 1656 mPendingVerification.remove(verificationId); 1657 1658 final InstallArgs args = state.getInstallArgs(); 1659 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1660 1661 int ret; 1662 if (state.isInstallAllowed()) { 1663 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1664 broadcastPackageVerified(verificationId, originUri, 1665 response.code, state.getInstallArgs().getUser()); 1666 try { 1667 ret = args.copyApk(mContainerService, true); 1668 } catch (RemoteException e) { 1669 Slog.e(TAG, "Could not contact the ContainerService"); 1670 } 1671 } else { 1672 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1673 } 1674 1675 Trace.asyncTraceEnd( 1676 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1677 1678 processPendingInstall(args, ret); 1679 mHandler.sendEmptyMessage(MCS_UNBIND); 1680 } 1681 1682 break; 1683 } 1684 case START_INTENT_FILTER_VERIFICATIONS: { 1685 IFVerificationParams params = (IFVerificationParams) msg.obj; 1686 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1687 params.replacing, params.pkg); 1688 break; 1689 } 1690 case INTENT_FILTER_VERIFIED: { 1691 final int verificationId = msg.arg1; 1692 1693 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1694 verificationId); 1695 if (state == null) { 1696 Slog.w(TAG, "Invalid IntentFilter verification token " 1697 + verificationId + " received"); 1698 break; 1699 } 1700 1701 final int userId = state.getUserId(); 1702 1703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1704 "Processing IntentFilter verification with token:" 1705 + verificationId + " and userId:" + userId); 1706 1707 final IntentFilterVerificationResponse response = 1708 (IntentFilterVerificationResponse) msg.obj; 1709 1710 state.setVerifierResponse(response.callerUid, response.code); 1711 1712 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1713 "IntentFilter verification with token:" + verificationId 1714 + " and userId:" + userId 1715 + " is settings verifier response with response code:" 1716 + response.code); 1717 1718 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1719 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1720 + response.getFailedDomainsString()); 1721 } 1722 1723 if (state.isVerificationComplete()) { 1724 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1725 } else { 1726 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1727 "IntentFilter verification with token:" + verificationId 1728 + " was not said to be complete"); 1729 } 1730 1731 break; 1732 } 1733 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1734 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1735 mInstantAppResolverConnection, 1736 (EphemeralRequest) msg.obj, 1737 mInstantAppInstallerActivity, 1738 mHandler); 1739 } 1740 } 1741 } 1742 } 1743 1744 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1745 boolean killApp, String[] grantedPermissions, 1746 boolean launchedForRestore, String installerPackage, 1747 IPackageInstallObserver2 installObserver) { 1748 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1749 // Send the removed broadcasts 1750 if (res.removedInfo != null) { 1751 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1752 } 1753 1754 // Now that we successfully installed the package, grant runtime 1755 // permissions if requested before broadcasting the install. Also 1756 // for legacy apps in permission review mode we clear the permission 1757 // review flag which is used to emulate runtime permissions for 1758 // legacy apps. 1759 if (grantPermissions) { 1760 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1761 } 1762 1763 final boolean update = res.removedInfo != null 1764 && res.removedInfo.removedPackage != null; 1765 1766 // If this is the first time we have child packages for a disabled privileged 1767 // app that had no children, we grant requested runtime permissions to the new 1768 // children if the parent on the system image had them already granted. 1769 if (res.pkg.parentPackage != null) { 1770 synchronized (mPackages) { 1771 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1772 } 1773 } 1774 1775 synchronized (mPackages) { 1776 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1777 } 1778 1779 final String packageName = res.pkg.applicationInfo.packageName; 1780 1781 // Determine the set of users who are adding this package for 1782 // the first time vs. those who are seeing an update. 1783 int[] firstUsers = EMPTY_INT_ARRAY; 1784 int[] updateUsers = EMPTY_INT_ARRAY; 1785 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1786 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1787 for (int newUser : res.newUsers) { 1788 if (ps.getInstantApp(newUser)) { 1789 continue; 1790 } 1791 if (allNewUsers) { 1792 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1793 continue; 1794 } 1795 boolean isNew = true; 1796 for (int origUser : res.origUsers) { 1797 if (origUser == newUser) { 1798 isNew = false; 1799 break; 1800 } 1801 } 1802 if (isNew) { 1803 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1804 } else { 1805 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1806 } 1807 } 1808 1809 // Send installed broadcasts if the package is not a static shared lib. 1810 if (res.pkg.staticSharedLibName == null) { 1811 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1812 1813 // Send added for users that see the package for the first time 1814 // sendPackageAddedForNewUsers also deals with system apps 1815 int appId = UserHandle.getAppId(res.uid); 1816 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1817 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1818 1819 // Send added for users that don't see the package for the first time 1820 Bundle extras = new Bundle(1); 1821 extras.putInt(Intent.EXTRA_UID, res.uid); 1822 if (update) { 1823 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1824 } 1825 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1826 extras, 0 /*flags*/, null /*targetPackage*/, 1827 null /*finishedReceiver*/, updateUsers); 1828 1829 // Send replaced for users that don't see the package for the first time 1830 if (update) { 1831 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1832 packageName, extras, 0 /*flags*/, 1833 null /*targetPackage*/, null /*finishedReceiver*/, 1834 updateUsers); 1835 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1836 null /*package*/, null /*extras*/, 0 /*flags*/, 1837 packageName /*targetPackage*/, 1838 null /*finishedReceiver*/, updateUsers); 1839 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1840 // First-install and we did a restore, so we're responsible for the 1841 // first-launch broadcast. 1842 if (DEBUG_BACKUP) { 1843 Slog.i(TAG, "Post-restore of " + packageName 1844 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1845 } 1846 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1847 } 1848 1849 // Send broadcast package appeared if forward locked/external for all users 1850 // treat asec-hosted packages like removable media on upgrade 1851 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1852 if (DEBUG_INSTALL) { 1853 Slog.i(TAG, "upgrading pkg " + res.pkg 1854 + " is ASEC-hosted -> AVAILABLE"); 1855 } 1856 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1857 ArrayList<String> pkgList = new ArrayList<>(1); 1858 pkgList.add(packageName); 1859 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1860 } 1861 } 1862 1863 // Work that needs to happen on first install within each user 1864 if (firstUsers != null && firstUsers.length > 0) { 1865 synchronized (mPackages) { 1866 for (int userId : firstUsers) { 1867 // If this app is a browser and it's newly-installed for some 1868 // users, clear any default-browser state in those users. The 1869 // app's nature doesn't depend on the user, so we can just check 1870 // its browser nature in any user and generalize. 1871 if (packageIsBrowser(packageName, userId)) { 1872 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1873 } 1874 1875 // We may also need to apply pending (restored) runtime 1876 // permission grants within these users. 1877 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1878 } 1879 } 1880 } 1881 1882 // Log current value of "unknown sources" setting 1883 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1884 getUnknownSourcesSettings()); 1885 1886 // Force a gc to clear up things 1887 Runtime.getRuntime().gc(); 1888 1889 // Remove the replaced package's older resources safely now 1890 // We delete after a gc for applications on sdcard. 1891 if (res.removedInfo != null && res.removedInfo.args != null) { 1892 synchronized (mInstallLock) { 1893 res.removedInfo.args.doPostDeleteLI(true); 1894 } 1895 } 1896 1897 // Notify DexManager that the package was installed for new users. 1898 // The updated users should already be indexed and the package code paths 1899 // should not change. 1900 // Don't notify the manager for ephemeral apps as they are not expected to 1901 // survive long enough to benefit of background optimizations. 1902 for (int userId : firstUsers) { 1903 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1904 mDexManager.notifyPackageInstalled(info, userId); 1905 } 1906 } 1907 1908 // If someone is watching installs - notify them 1909 if (installObserver != null) { 1910 try { 1911 Bundle extras = extrasForInstallResult(res); 1912 installObserver.onPackageInstalled(res.name, res.returnCode, 1913 res.returnMsg, extras); 1914 } catch (RemoteException e) { 1915 Slog.i(TAG, "Observer no longer exists."); 1916 } 1917 } 1918 } 1919 1920 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1921 PackageParser.Package pkg) { 1922 if (pkg.parentPackage == null) { 1923 return; 1924 } 1925 if (pkg.requestedPermissions == null) { 1926 return; 1927 } 1928 final PackageSetting disabledSysParentPs = mSettings 1929 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1930 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1931 || !disabledSysParentPs.isPrivileged() 1932 || (disabledSysParentPs.childPackageNames != null 1933 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1934 return; 1935 } 1936 final int[] allUserIds = sUserManager.getUserIds(); 1937 final int permCount = pkg.requestedPermissions.size(); 1938 for (int i = 0; i < permCount; i++) { 1939 String permission = pkg.requestedPermissions.get(i); 1940 BasePermission bp = mSettings.mPermissions.get(permission); 1941 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1942 continue; 1943 } 1944 for (int userId : allUserIds) { 1945 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1946 permission, userId)) { 1947 grantRuntimePermission(pkg.packageName, permission, userId); 1948 } 1949 } 1950 } 1951 } 1952 1953 private StorageEventListener mStorageListener = new StorageEventListener() { 1954 @Override 1955 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1956 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1957 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1958 final String volumeUuid = vol.getFsUuid(); 1959 1960 // Clean up any users or apps that were removed or recreated 1961 // while this volume was missing 1962 sUserManager.reconcileUsers(volumeUuid); 1963 reconcileApps(volumeUuid); 1964 1965 // Clean up any install sessions that expired or were 1966 // cancelled while this volume was missing 1967 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1968 1969 loadPrivatePackages(vol); 1970 1971 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1972 unloadPrivatePackages(vol); 1973 } 1974 } 1975 1976 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1977 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1978 updateExternalMediaStatus(true, false); 1979 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1980 updateExternalMediaStatus(false, false); 1981 } 1982 } 1983 } 1984 1985 @Override 1986 public void onVolumeForgotten(String fsUuid) { 1987 if (TextUtils.isEmpty(fsUuid)) { 1988 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1989 return; 1990 } 1991 1992 // Remove any apps installed on the forgotten volume 1993 synchronized (mPackages) { 1994 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1995 for (PackageSetting ps : packages) { 1996 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1997 deletePackageVersioned(new VersionedPackage(ps.name, 1998 PackageManager.VERSION_CODE_HIGHEST), 1999 new LegacyPackageDeleteObserver(null).getBinder(), 2000 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2001 // Try very hard to release any references to this package 2002 // so we don't risk the system server being killed due to 2003 // open FDs 2004 AttributeCache.instance().removePackage(ps.name); 2005 } 2006 2007 mSettings.onVolumeForgotten(fsUuid); 2008 mSettings.writeLPr(); 2009 } 2010 } 2011 }; 2012 2013 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2014 String[] grantedPermissions) { 2015 for (int userId : userIds) { 2016 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2017 } 2018 } 2019 2020 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2021 String[] grantedPermissions) { 2022 SettingBase sb = (SettingBase) pkg.mExtras; 2023 if (sb == null) { 2024 return; 2025 } 2026 2027 PermissionsState permissionsState = sb.getPermissionsState(); 2028 2029 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2030 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2031 2032 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2033 >= Build.VERSION_CODES.M; 2034 2035 for (String permission : pkg.requestedPermissions) { 2036 final BasePermission bp; 2037 synchronized (mPackages) { 2038 bp = mSettings.mPermissions.get(permission); 2039 } 2040 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2041 && (grantedPermissions == null 2042 || ArrayUtils.contains(grantedPermissions, permission))) { 2043 final int flags = permissionsState.getPermissionFlags(permission, userId); 2044 if (supportsRuntimePermissions) { 2045 // Installer cannot change immutable permissions. 2046 if ((flags & immutableFlags) == 0) { 2047 grantRuntimePermission(pkg.packageName, permission, userId); 2048 } 2049 } else if (mPermissionReviewRequired) { 2050 // In permission review mode we clear the review flag when we 2051 // are asked to install the app with all permissions granted. 2052 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2053 updatePermissionFlags(permission, pkg.packageName, 2054 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2055 } 2056 } 2057 } 2058 } 2059 } 2060 2061 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2062 Bundle extras = null; 2063 switch (res.returnCode) { 2064 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2065 extras = new Bundle(); 2066 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2067 res.origPermission); 2068 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2069 res.origPackage); 2070 break; 2071 } 2072 case PackageManager.INSTALL_SUCCEEDED: { 2073 extras = new Bundle(); 2074 extras.putBoolean(Intent.EXTRA_REPLACING, 2075 res.removedInfo != null && res.removedInfo.removedPackage != null); 2076 break; 2077 } 2078 } 2079 return extras; 2080 } 2081 2082 void scheduleWriteSettingsLocked() { 2083 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2084 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2085 } 2086 } 2087 2088 void scheduleWritePackageListLocked(int userId) { 2089 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2090 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2091 msg.arg1 = userId; 2092 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2093 } 2094 } 2095 2096 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2097 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2098 scheduleWritePackageRestrictionsLocked(userId); 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(int userId) { 2102 final int[] userIds = (userId == UserHandle.USER_ALL) 2103 ? sUserManager.getUserIds() : new int[]{userId}; 2104 for (int nextUserId : userIds) { 2105 if (!sUserManager.exists(nextUserId)) return; 2106 mDirtyUsers.add(nextUserId); 2107 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2108 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2109 } 2110 } 2111 } 2112 2113 public static PackageManagerService main(Context context, Installer installer, 2114 boolean factoryTest, boolean onlyCore) { 2115 // Self-check for initial settings. 2116 PackageManagerServiceCompilerMapping.checkProperties(); 2117 2118 PackageManagerService m = new PackageManagerService(context, installer, 2119 factoryTest, onlyCore); 2120 m.enableSystemUserPackages(); 2121 ServiceManager.addService("package", m); 2122 return m; 2123 } 2124 2125 private void enableSystemUserPackages() { 2126 if (!UserManager.isSplitSystemUser()) { 2127 return; 2128 } 2129 // For system user, enable apps based on the following conditions: 2130 // - app is whitelisted or belong to one of these groups: 2131 // -- system app which has no launcher icons 2132 // -- system app which has INTERACT_ACROSS_USERS permission 2133 // -- system IME app 2134 // - app is not in the blacklist 2135 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2136 Set<String> enableApps = new ArraySet<>(); 2137 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2138 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2139 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2140 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2141 enableApps.addAll(wlApps); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2143 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2144 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2145 enableApps.removeAll(blApps); 2146 Log.i(TAG, "Applications installed for system user: " + enableApps); 2147 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2148 UserHandle.SYSTEM); 2149 final int allAppsSize = allAps.size(); 2150 synchronized (mPackages) { 2151 for (int i = 0; i < allAppsSize; i++) { 2152 String pName = allAps.get(i); 2153 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2154 // Should not happen, but we shouldn't be failing if it does 2155 if (pkgSetting == null) { 2156 continue; 2157 } 2158 boolean install = enableApps.contains(pName); 2159 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2160 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2161 + " for system user"); 2162 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2163 } 2164 } 2165 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2166 } 2167 } 2168 2169 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2170 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2171 Context.DISPLAY_SERVICE); 2172 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2173 } 2174 2175 /** 2176 * Requests that files preopted on a secondary system partition be copied to the data partition 2177 * if possible. Note that the actual copying of the files is accomplished by init for security 2178 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2179 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2180 */ 2181 private static void requestCopyPreoptedFiles() { 2182 final int WAIT_TIME_MS = 100; 2183 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2184 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2185 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2186 // We will wait for up to 100 seconds. 2187 final long timeStart = SystemClock.uptimeMillis(); 2188 final long timeEnd = timeStart + 100 * 1000; 2189 long timeNow = timeStart; 2190 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2191 try { 2192 Thread.sleep(WAIT_TIME_MS); 2193 } catch (InterruptedException e) { 2194 // Do nothing 2195 } 2196 timeNow = SystemClock.uptimeMillis(); 2197 if (timeNow > timeEnd) { 2198 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2199 Slog.wtf(TAG, "cppreopt did not finish!"); 2200 break; 2201 } 2202 } 2203 2204 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2205 } 2206 } 2207 2208 public PackageManagerService(Context context, Installer installer, 2209 boolean factoryTest, boolean onlyCore) { 2210 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2211 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2212 SystemClock.uptimeMillis()); 2213 2214 if (mSdkVersion <= 0) { 2215 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2216 } 2217 2218 mContext = context; 2219 2220 mPermissionReviewRequired = context.getResources().getBoolean( 2221 R.bool.config_permissionReviewRequired); 2222 2223 mFactoryTest = factoryTest; 2224 mOnlyCore = onlyCore; 2225 mMetrics = new DisplayMetrics(); 2226 mSettings = new Settings(mPackages); 2227 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2228 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2229 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2230 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2231 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2232 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2233 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2234 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2235 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2236 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2237 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 2240 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2241 if (separateProcesses != null && separateProcesses.length() > 0) { 2242 if ("*".equals(separateProcesses)) { 2243 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2244 mSeparateProcesses = null; 2245 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2246 } else { 2247 mDefParseFlags = 0; 2248 mSeparateProcesses = separateProcesses.split(","); 2249 Slog.w(TAG, "Running with debug.separate_processes: " 2250 + separateProcesses); 2251 } 2252 } else { 2253 mDefParseFlags = 0; 2254 mSeparateProcesses = null; 2255 } 2256 2257 mInstaller = installer; 2258 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2259 "*dexopt*"); 2260 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2261 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2262 2263 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2264 FgThread.get().getLooper()); 2265 2266 getDefaultDisplayMetrics(context, mMetrics); 2267 2268 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2269 SystemConfig systemConfig = SystemConfig.getInstance(); 2270 mGlobalGids = systemConfig.getGlobalGids(); 2271 mSystemPermissions = systemConfig.getSystemPermissions(); 2272 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2274 2275 mProtectedPackages = new ProtectedPackages(mContext); 2276 2277 synchronized (mInstallLock) { 2278 // writer 2279 synchronized (mPackages) { 2280 mHandlerThread = new ServiceThread(TAG, 2281 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2282 mHandlerThread.start(); 2283 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2284 mProcessLoggingHandler = new ProcessLoggingHandler(); 2285 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2286 2287 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2288 mInstantAppRegistry = new InstantAppRegistry(this); 2289 2290 File dataDir = Environment.getDataDirectory(); 2291 mAppInstallDir = new File(dataDir, "app"); 2292 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2293 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2294 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2295 sUserManager = new UserManagerService(context, this, 2296 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2297 2298 // Propagate permission configuration in to package manager. 2299 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2300 = systemConfig.getPermissions(); 2301 for (int i=0; i<permConfig.size(); i++) { 2302 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2303 BasePermission bp = mSettings.mPermissions.get(perm.name); 2304 if (bp == null) { 2305 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2306 mSettings.mPermissions.put(perm.name, bp); 2307 } 2308 if (perm.gids != null) { 2309 bp.setGids(perm.gids, perm.perUser); 2310 } 2311 } 2312 2313 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2314 final int builtInLibCount = libConfig.size(); 2315 for (int i = 0; i < builtInLibCount; i++) { 2316 String name = libConfig.keyAt(i); 2317 String path = libConfig.valueAt(i); 2318 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2319 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2320 } 2321 2322 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2323 2324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2325 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2326 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2327 2328 // Clean up orphaned packages for which the code path doesn't exist 2329 // and they are an update to a system app - caused by bug/32321269 2330 final int packageSettingCount = mSettings.mPackages.size(); 2331 for (int i = packageSettingCount - 1; i >= 0; i--) { 2332 PackageSetting ps = mSettings.mPackages.valueAt(i); 2333 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2334 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2335 mSettings.mPackages.removeAt(i); 2336 mSettings.enableSystemPackageLPw(ps.name); 2337 } 2338 } 2339 2340 if (mFirstBoot) { 2341 requestCopyPreoptedFiles(); 2342 } 2343 2344 String customResolverActivity = Resources.getSystem().getString( 2345 R.string.config_customResolverActivity); 2346 if (TextUtils.isEmpty(customResolverActivity)) { 2347 customResolverActivity = null; 2348 } else { 2349 mCustomResolverComponentName = ComponentName.unflattenFromString( 2350 customResolverActivity); 2351 } 2352 2353 long startTime = SystemClock.uptimeMillis(); 2354 2355 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2356 startTime); 2357 2358 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2359 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2360 2361 if (bootClassPath == null) { 2362 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2363 } 2364 2365 if (systemServerClassPath == null) { 2366 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2367 } 2368 2369 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2370 final String[] dexCodeInstructionSets = 2371 getDexCodeInstructionSets( 2372 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2373 2374 /** 2375 * Ensure all external libraries have had dexopt run on them. 2376 */ 2377 if (mSharedLibraries.size() > 0) { 2378 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2379 // NOTE: For now, we're compiling these system "shared libraries" 2380 // (and framework jars) into all available architectures. It's possible 2381 // to compile them only when we come across an app that uses them (there's 2382 // already logic for that in scanPackageLI) but that adds some complexity. 2383 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2384 final int libCount = mSharedLibraries.size(); 2385 for (int i = 0; i < libCount; i++) { 2386 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2387 final int versionCount = versionedLib.size(); 2388 for (int j = 0; j < versionCount; j++) { 2389 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2390 final String libPath = libEntry.path != null 2391 ? libEntry.path : libEntry.apk; 2392 if (libPath == null) { 2393 continue; 2394 } 2395 try { 2396 // Shared libraries do not have profiles so we perform a full 2397 // AOT compilation (if needed). 2398 int dexoptNeeded = DexFile.getDexOptNeeded( 2399 libPath, dexCodeInstructionSet, 2400 getCompilerFilterForReason(REASON_SHARED_APK), 2401 false /* newProfile */); 2402 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2403 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2404 dexCodeInstructionSet, dexoptNeeded, null, 2405 DEXOPT_PUBLIC, 2406 getCompilerFilterForReason(REASON_SHARED_APK), 2407 StorageManager.UUID_PRIVATE_INTERNAL, 2408 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2409 } 2410 } catch (FileNotFoundException e) { 2411 Slog.w(TAG, "Library not found: " + libPath); 2412 } catch (IOException | InstallerException e) { 2413 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2414 + e.getMessage()); 2415 } 2416 } 2417 } 2418 } 2419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2420 } 2421 2422 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2423 2424 final VersionInfo ver = mSettings.getInternalVersion(); 2425 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2426 2427 // when upgrading from pre-M, promote system app permissions from install to runtime 2428 mPromoteSystemApps = 2429 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2430 2431 // When upgrading from pre-N, we need to handle package extraction like first boot, 2432 // as there is no profiling data available. 2433 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2434 2435 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2436 2437 // save off the names of pre-existing system packages prior to scanning; we don't 2438 // want to automatically grant runtime permissions for new system apps 2439 if (mPromoteSystemApps) { 2440 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2441 while (pkgSettingIter.hasNext()) { 2442 PackageSetting ps = pkgSettingIter.next(); 2443 if (isSystemApp(ps)) { 2444 mExistingSystemPackages.add(ps.name); 2445 } 2446 } 2447 } 2448 2449 mCacheDir = preparePackageParserCache(mIsUpgrade); 2450 2451 // Set flag to monitor and not change apk file paths when 2452 // scanning install directories. 2453 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2454 2455 if (mIsUpgrade || mFirstBoot) { 2456 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2457 } 2458 2459 // Collect vendor overlay packages. (Do this before scanning any apps.) 2460 // For security and version matching reason, only consider 2461 // overlay packages if they reside in the right directory. 2462 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2463 if (overlayThemeDir.isEmpty()) { 2464 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2465 } 2466 if (!overlayThemeDir.isEmpty()) { 2467 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2468 | PackageParser.PARSE_IS_SYSTEM 2469 | PackageParser.PARSE_IS_SYSTEM_DIR 2470 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2471 } 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 2477 // Find base frameworks (resource packages without code). 2478 scanDirTracedLI(frameworkDir, mDefParseFlags 2479 | PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR 2481 | PackageParser.PARSE_IS_PRIVILEGED, 2482 scanFlags | SCAN_NO_DEX, 0); 2483 2484 // Collected privileged system packages. 2485 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2486 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR 2489 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2490 2491 // Collect ordinary system packages. 2492 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2493 scanDirTracedLI(systemAppDir, mDefParseFlags 2494 | PackageParser.PARSE_IS_SYSTEM 2495 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2496 2497 // Collect all vendor packages. 2498 File vendorAppDir = new File("/vendor/app"); 2499 try { 2500 vendorAppDir = vendorAppDir.getCanonicalFile(); 2501 } catch (IOException e) { 2502 // failed to look up canonical path, continue with original one 2503 } 2504 scanDirTracedLI(vendorAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Collect all OEM packages. 2509 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2510 scanDirTracedLI(oemAppDir, mDefParseFlags 2511 | PackageParser.PARSE_IS_SYSTEM 2512 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2513 2514 // Prune any system packages that no longer exist. 2515 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2516 if (!mOnlyCore) { 2517 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2518 while (psit.hasNext()) { 2519 PackageSetting ps = psit.next(); 2520 2521 /* 2522 * If this is not a system app, it can't be a 2523 * disable system app. 2524 */ 2525 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2526 continue; 2527 } 2528 2529 /* 2530 * If the package is scanned, it's not erased. 2531 */ 2532 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2533 if (scannedPkg != null) { 2534 /* 2535 * If the system app is both scanned and in the 2536 * disabled packages list, then it must have been 2537 * added via OTA. Remove it from the currently 2538 * scanned package so the previously user-installed 2539 * application can be scanned. 2540 */ 2541 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2542 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2543 + ps.name + "; removing system app. Last known codePath=" 2544 + ps.codePathString + ", installStatus=" + ps.installStatus 2545 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2546 + scannedPkg.mVersionCode); 2547 removePackageLI(scannedPkg, true); 2548 mExpectingBetter.put(ps.name, ps.codePath); 2549 } 2550 2551 continue; 2552 } 2553 2554 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2555 psit.remove(); 2556 logCriticalInfo(Log.WARN, "System package " + ps.name 2557 + " no longer exists; it's data will be wiped"); 2558 // Actual deletion of code and data will be handled by later 2559 // reconciliation step 2560 } else { 2561 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2562 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2563 possiblyDeletedUpdatedSystemApps.add(ps.name); 2564 } 2565 } 2566 } 2567 } 2568 2569 //look for any incomplete package installations 2570 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2571 for (int i = 0; i < deletePkgsList.size(); i++) { 2572 // Actual deletion of code and data will be handled by later 2573 // reconciliation step 2574 final String packageName = deletePkgsList.get(i).name; 2575 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2576 synchronized (mPackages) { 2577 mSettings.removePackageLPw(packageName); 2578 } 2579 } 2580 2581 //delete tmp files 2582 deleteTempPackageFiles(); 2583 2584 // Remove any shared userIDs that have no associated packages 2585 mSettings.pruneSharedUsersLPw(); 2586 2587 if (!mOnlyCore) { 2588 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2589 SystemClock.uptimeMillis()); 2590 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2591 2592 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2593 | PackageParser.PARSE_FORWARD_LOCK, 2594 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2595 2596 /** 2597 * Remove disable package settings for any updated system 2598 * apps that were removed via an OTA. If they're not a 2599 * previously-updated app, remove them completely. 2600 * Otherwise, just revoke their system-level permissions. 2601 */ 2602 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2603 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2604 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2605 2606 String msg; 2607 if (deletedPkg == null) { 2608 msg = "Updated system package " + deletedAppName 2609 + " no longer exists; it's data will be wiped"; 2610 // Actual deletion of code and data will be handled by later 2611 // reconciliation step 2612 } else { 2613 msg = "Updated system app + " + deletedAppName 2614 + " no longer present; removing system privileges for " 2615 + deletedAppName; 2616 2617 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 2619 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2620 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2621 } 2622 logCriticalInfo(Log.WARN, msg); 2623 } 2624 2625 /** 2626 * Make sure all system apps that we expected to appear on 2627 * the userdata partition actually showed up. If they never 2628 * appeared, crawl back and revive the system version. 2629 */ 2630 for (int i = 0; i < mExpectingBetter.size(); i++) { 2631 final String packageName = mExpectingBetter.keyAt(i); 2632 if (!mPackages.containsKey(packageName)) { 2633 final File scanFile = mExpectingBetter.valueAt(i); 2634 2635 logCriticalInfo(Log.WARN, "Expected better " + packageName 2636 + " but never showed up; reverting to system"); 2637 2638 int reparseFlags = mDefParseFlags; 2639 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2640 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2641 | PackageParser.PARSE_IS_SYSTEM_DIR 2642 | PackageParser.PARSE_IS_PRIVILEGED; 2643 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2650 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2651 | PackageParser.PARSE_IS_SYSTEM_DIR; 2652 } else { 2653 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2654 continue; 2655 } 2656 2657 mSettings.enableSystemPackageLPw(packageName); 2658 2659 try { 2660 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2661 } catch (PackageManagerException e) { 2662 Slog.e(TAG, "Failed to parse original system package: " 2663 + e.getMessage()); 2664 } 2665 } 2666 } 2667 } 2668 mExpectingBetter.clear(); 2669 2670 // Resolve the storage manager. 2671 mStorageManagerPackage = getStorageManagerPackageName(); 2672 2673 // Resolve protected action filters. Only the setup wizard is allowed to 2674 // have a high priority filter for these actions. 2675 mSetupWizardPackage = getSetupWizardPackageName(); 2676 if (mProtectedFilters.size() > 0) { 2677 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2678 Slog.i(TAG, "No setup wizard;" 2679 + " All protected intents capped to priority 0"); 2680 } 2681 for (ActivityIntentInfo filter : mProtectedFilters) { 2682 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2683 if (DEBUG_FILTERS) { 2684 Slog.i(TAG, "Found setup wizard;" 2685 + " allow priority " + filter.getPriority() + ";" 2686 + " package: " + filter.activity.info.packageName 2687 + " activity: " + filter.activity.className 2688 + " priority: " + filter.getPriority()); 2689 } 2690 // skip setup wizard; allow it to keep the high priority filter 2691 continue; 2692 } 2693 Slog.w(TAG, "Protected action; cap priority to 0;" 2694 + " package: " + filter.activity.info.packageName 2695 + " activity: " + filter.activity.className 2696 + " origPrio: " + filter.getPriority()); 2697 filter.setPriority(0); 2698 } 2699 } 2700 mDeferProtectedFilters = false; 2701 mProtectedFilters.clear(); 2702 2703 // Now that we know all of the shared libraries, update all clients to have 2704 // the correct library paths. 2705 updateAllSharedLibrariesLPw(null); 2706 2707 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2708 // NOTE: We ignore potential failures here during a system scan (like 2709 // the rest of the commands above) because there's precious little we 2710 // can do about it. A settings error is reported, though. 2711 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2712 } 2713 2714 // Now that we know all the packages we are keeping, 2715 // read and update their last usage times. 2716 mPackageUsage.read(mPackages); 2717 mCompilerStats.read(); 2718 2719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2720 SystemClock.uptimeMillis()); 2721 Slog.i(TAG, "Time to scan packages: " 2722 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2723 + " seconds"); 2724 2725 // If the platform SDK has changed since the last time we booted, 2726 // we need to re-grant app permission to catch any new ones that 2727 // appear. This is really a hack, and means that apps can in some 2728 // cases get permissions that the user didn't initially explicitly 2729 // allow... it would be nice to have some better way to handle 2730 // this situation. 2731 int updateFlags = UPDATE_PERMISSIONS_ALL; 2732 if (ver.sdkVersion != mSdkVersion) { 2733 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2734 + mSdkVersion + "; regranting permissions for internal storage"); 2735 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2736 } 2737 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2738 ver.sdkVersion = mSdkVersion; 2739 2740 // If this is the first boot or an update from pre-M, and it is a normal 2741 // boot, then we need to initialize the default preferred apps across 2742 // all defined users. 2743 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2744 for (UserInfo user : sUserManager.getUsers(true)) { 2745 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2746 applyFactoryDefaultBrowserLPw(user.id); 2747 primeDomainVerificationsLPw(user.id); 2748 } 2749 } 2750 2751 // Prepare storage for system user really early during boot, 2752 // since core system apps like SettingsProvider and SystemUI 2753 // can't wait for user to start 2754 final int storageFlags; 2755 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2756 storageFlags = StorageManager.FLAG_STORAGE_DE; 2757 } else { 2758 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2759 } 2760 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2761 storageFlags, true /* migrateAppData */); 2762 2763 // If this is first boot after an OTA, and a normal boot, then 2764 // we need to clear code cache directories. 2765 // Note that we do *not* clear the application profiles. These remain valid 2766 // across OTAs and are used to drive profile verification (post OTA) and 2767 // profile compilation (without waiting to collect a fresh set of profiles). 2768 if (mIsUpgrade && !onlyCore) { 2769 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2770 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2771 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2772 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2773 // No apps are running this early, so no need to freeze 2774 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2775 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2776 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2777 } 2778 } 2779 ver.fingerprint = Build.FINGERPRINT; 2780 } 2781 2782 checkDefaultBrowser(); 2783 2784 // clear only after permissions and other defaults have been updated 2785 mExistingSystemPackages.clear(); 2786 mPromoteSystemApps = false; 2787 2788 // All the changes are done during package scanning. 2789 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2790 2791 // can downgrade to reader 2792 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2793 mSettings.writeLPr(); 2794 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2795 2796 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2797 // early on (before the package manager declares itself as early) because other 2798 // components in the system server might ask for package contexts for these apps. 2799 // 2800 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2801 // (i.e, that the data partition is unavailable). 2802 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2803 long start = System.nanoTime(); 2804 List<PackageParser.Package> coreApps = new ArrayList<>(); 2805 for (PackageParser.Package pkg : mPackages.values()) { 2806 if (pkg.coreApp) { 2807 coreApps.add(pkg); 2808 } 2809 } 2810 2811 int[] stats = performDexOptUpgrade(coreApps, false, 2812 getCompilerFilterForReason(REASON_CORE_APP)); 2813 2814 final int elapsedTimeSeconds = 2815 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2816 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2817 2818 if (DEBUG_DEXOPT) { 2819 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2820 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2821 } 2822 2823 2824 // TODO: Should we log these stats to tron too ? 2825 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2826 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2827 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2828 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2829 } 2830 2831 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2832 SystemClock.uptimeMillis()); 2833 2834 if (!mOnlyCore) { 2835 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2836 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2837 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2838 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2839 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2840 mIntentFilterVerifierComponent); 2841 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2842 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2843 SharedLibraryInfo.VERSION_UNDEFINED); 2844 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2845 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2846 SharedLibraryInfo.VERSION_UNDEFINED); 2847 } else { 2848 mRequiredVerifierPackage = null; 2849 mRequiredInstallerPackage = null; 2850 mRequiredUninstallerPackage = null; 2851 mIntentFilterVerifierComponent = null; 2852 mIntentFilterVerifier = null; 2853 mServicesSystemSharedLibraryPackageName = null; 2854 mSharedSystemSharedLibraryPackageName = null; 2855 } 2856 2857 mInstallerService = new PackageInstallerService(context, this); 2858 2859 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2860 if (ephemeralResolverComponent != null) { 2861 if (DEBUG_EPHEMERAL) { 2862 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2863 } 2864 mInstantAppResolverConnection = 2865 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2866 } else { 2867 mInstantAppResolverConnection = null; 2868 } 2869 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2870 if (mInstantAppInstallerComponent != null) { 2871 if (DEBUG_EPHEMERAL) { 2872 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2873 } 2874 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2875 } 2876 2877 // Read and update the usage of dex files. 2878 // Do this at the end of PM init so that all the packages have their 2879 // data directory reconciled. 2880 // At this point we know the code paths of the packages, so we can validate 2881 // the disk file and build the internal cache. 2882 // The usage file is expected to be small so loading and verifying it 2883 // should take a fairly small time compare to the other activities (e.g. package 2884 // scanning). 2885 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2886 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2887 for (int userId : currentUserIds) { 2888 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2889 } 2890 mDexManager.load(userPackages); 2891 } // synchronized (mPackages) 2892 } // synchronized (mInstallLock) 2893 2894 // Now after opening every single application zip, make sure they 2895 // are all flushed. Not really needed, but keeps things nice and 2896 // tidy. 2897 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2898 Runtime.getRuntime().gc(); 2899 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2900 2901 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2902 FallbackCategoryProvider.loadFallbacks(); 2903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2904 2905 // The initial scanning above does many calls into installd while 2906 // holding the mPackages lock, but we're mostly interested in yelling 2907 // once we have a booted system. 2908 mInstaller.setWarnIfHeld(mPackages); 2909 2910 // Expose private service for system components to use. 2911 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2912 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2913 } 2914 2915 private static File preparePackageParserCache(boolean isUpgrade) { 2916 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2917 return null; 2918 } 2919 2920 // Disable package parsing on eng builds to allow for faster incremental development. 2921 if ("eng".equals(Build.TYPE)) { 2922 return null; 2923 } 2924 2925 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2926 Slog.i(TAG, "Disabling package parser cache due to system property."); 2927 return null; 2928 } 2929 2930 // The base directory for the package parser cache lives under /data/system/. 2931 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2932 "package_cache"); 2933 if (cacheBaseDir == null) { 2934 return null; 2935 } 2936 2937 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2938 // This also serves to "GC" unused entries when the package cache version changes (which 2939 // can only happen during upgrades). 2940 if (isUpgrade) { 2941 FileUtils.deleteContents(cacheBaseDir); 2942 } 2943 2944 2945 // Return the versioned package cache directory. This is something like 2946 // "/data/system/package_cache/1" 2947 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2948 2949 // The following is a workaround to aid development on non-numbered userdebug 2950 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2951 // the system partition is newer. 2952 // 2953 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2954 // that starts with "eng." to signify that this is an engineering build and not 2955 // destined for release. 2956 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2957 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2958 2959 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2960 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2961 // in general and should not be used for production changes. In this specific case, 2962 // we know that they will work. 2963 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2964 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2965 FileUtils.deleteContents(cacheBaseDir); 2966 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2967 } 2968 } 2969 2970 return cacheDir; 2971 } 2972 2973 @Override 2974 public boolean isFirstBoot() { 2975 return mFirstBoot; 2976 } 2977 2978 @Override 2979 public boolean isOnlyCoreApps() { 2980 return mOnlyCore; 2981 } 2982 2983 @Override 2984 public boolean isUpgrade() { 2985 return mIsUpgrade; 2986 } 2987 2988 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2989 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2990 2991 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2992 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2993 UserHandle.USER_SYSTEM); 2994 if (matches.size() == 1) { 2995 return matches.get(0).getComponentInfo().packageName; 2996 } else if (matches.size() == 0) { 2997 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2998 return null; 2999 } 3000 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3001 } 3002 3003 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3004 synchronized (mPackages) { 3005 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3006 if (libraryEntry == null) { 3007 throw new IllegalStateException("Missing required shared library:" + name); 3008 } 3009 return libraryEntry.apk; 3010 } 3011 } 3012 3013 private @NonNull String getRequiredInstallerLPr() { 3014 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3015 intent.addCategory(Intent.CATEGORY_DEFAULT); 3016 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3017 3018 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3019 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3020 UserHandle.USER_SYSTEM); 3021 if (matches.size() == 1) { 3022 ResolveInfo resolveInfo = matches.get(0); 3023 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3024 throw new RuntimeException("The installer must be a privileged app"); 3025 } 3026 return matches.get(0).getComponentInfo().packageName; 3027 } else { 3028 throw new RuntimeException("There must be exactly one installer; found " + matches); 3029 } 3030 } 3031 3032 private @NonNull String getRequiredUninstallerLPr() { 3033 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3034 intent.addCategory(Intent.CATEGORY_DEFAULT); 3035 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3036 3037 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3038 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3039 UserHandle.USER_SYSTEM); 3040 if (resolveInfo == null || 3041 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3042 throw new RuntimeException("There must be exactly one uninstaller; found " 3043 + resolveInfo); 3044 } 3045 return resolveInfo.getComponentInfo().packageName; 3046 } 3047 3048 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3049 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3050 3051 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3052 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3053 UserHandle.USER_SYSTEM); 3054 ResolveInfo best = null; 3055 final int N = matches.size(); 3056 for (int i = 0; i < N; i++) { 3057 final ResolveInfo cur = matches.get(i); 3058 final String packageName = cur.getComponentInfo().packageName; 3059 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3060 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3061 continue; 3062 } 3063 3064 if (best == null || cur.priority > best.priority) { 3065 best = cur; 3066 } 3067 } 3068 3069 if (best != null) { 3070 return best.getComponentInfo().getComponentName(); 3071 } else { 3072 throw new RuntimeException("There must be at least one intent filter verifier"); 3073 } 3074 } 3075 3076 private @Nullable ComponentName getEphemeralResolverLPr() { 3077 final String[] packageArray = 3078 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3079 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3080 if (DEBUG_EPHEMERAL) { 3081 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3082 } 3083 return null; 3084 } 3085 3086 final int resolveFlags = 3087 MATCH_DIRECT_BOOT_AWARE 3088 | MATCH_DIRECT_BOOT_UNAWARE 3089 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3090 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3091 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3092 resolveFlags, UserHandle.USER_SYSTEM); 3093 3094 final int N = resolvers.size(); 3095 if (N == 0) { 3096 if (DEBUG_EPHEMERAL) { 3097 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3098 } 3099 return null; 3100 } 3101 3102 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3103 for (int i = 0; i < N; i++) { 3104 final ResolveInfo info = resolvers.get(i); 3105 3106 if (info.serviceInfo == null) { 3107 continue; 3108 } 3109 3110 final String packageName = info.serviceInfo.packageName; 3111 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3112 if (DEBUG_EPHEMERAL) { 3113 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3114 + " pkg: " + packageName + ", info:" + info); 3115 } 3116 continue; 3117 } 3118 3119 if (DEBUG_EPHEMERAL) { 3120 Slog.v(TAG, "Ephemeral resolver found;" 3121 + " pkg: " + packageName + ", info:" + info); 3122 } 3123 return new ComponentName(packageName, info.serviceInfo.name); 3124 } 3125 if (DEBUG_EPHEMERAL) { 3126 Slog.v(TAG, "Ephemeral resolver NOT found"); 3127 } 3128 return null; 3129 } 3130 3131 private @Nullable ComponentName getEphemeralInstallerLPr() { 3132 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3133 intent.addCategory(Intent.CATEGORY_DEFAULT); 3134 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3135 3136 final int resolveFlags = 3137 MATCH_DIRECT_BOOT_AWARE 3138 | MATCH_DIRECT_BOOT_UNAWARE 3139 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3140 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3141 resolveFlags, UserHandle.USER_SYSTEM); 3142 Iterator<ResolveInfo> iter = matches.iterator(); 3143 while (iter.hasNext()) { 3144 final ResolveInfo rInfo = iter.next(); 3145 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3146 if (ps != null) { 3147 final PermissionsState permissionsState = ps.getPermissionsState(); 3148 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3149 continue; 3150 } 3151 } 3152 iter.remove(); 3153 } 3154 if (matches.size() == 0) { 3155 return null; 3156 } else if (matches.size() == 1) { 3157 return matches.get(0).getComponentInfo().getComponentName(); 3158 } else { 3159 throw new RuntimeException( 3160 "There must be at most one ephemeral installer; found " + matches); 3161 } 3162 } 3163 3164 private void primeDomainVerificationsLPw(int userId) { 3165 if (DEBUG_DOMAIN_VERIFICATION) { 3166 Slog.d(TAG, "Priming domain verifications in user " + userId); 3167 } 3168 3169 SystemConfig systemConfig = SystemConfig.getInstance(); 3170 ArraySet<String> packages = systemConfig.getLinkedApps(); 3171 3172 for (String packageName : packages) { 3173 PackageParser.Package pkg = mPackages.get(packageName); 3174 if (pkg != null) { 3175 if (!pkg.isSystemApp()) { 3176 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3177 continue; 3178 } 3179 3180 ArraySet<String> domains = null; 3181 for (PackageParser.Activity a : pkg.activities) { 3182 for (ActivityIntentInfo filter : a.intents) { 3183 if (hasValidDomains(filter)) { 3184 if (domains == null) { 3185 domains = new ArraySet<String>(); 3186 } 3187 domains.addAll(filter.getHostsList()); 3188 } 3189 } 3190 } 3191 3192 if (domains != null && domains.size() > 0) { 3193 if (DEBUG_DOMAIN_VERIFICATION) { 3194 Slog.v(TAG, " + " + packageName); 3195 } 3196 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3197 // state w.r.t. the formal app-linkage "no verification attempted" state; 3198 // and then 'always' in the per-user state actually used for intent resolution. 3199 final IntentFilterVerificationInfo ivi; 3200 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3201 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3202 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3203 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3204 } else { 3205 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3206 + "' does not handle web links"); 3207 } 3208 } else { 3209 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3210 } 3211 } 3212 3213 scheduleWritePackageRestrictionsLocked(userId); 3214 scheduleWriteSettingsLocked(); 3215 } 3216 3217 private void applyFactoryDefaultBrowserLPw(int userId) { 3218 // The default browser app's package name is stored in a string resource, 3219 // with a product-specific overlay used for vendor customization. 3220 String browserPkg = mContext.getResources().getString( 3221 com.android.internal.R.string.default_browser); 3222 if (!TextUtils.isEmpty(browserPkg)) { 3223 // non-empty string => required to be a known package 3224 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3225 if (ps == null) { 3226 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3227 browserPkg = null; 3228 } else { 3229 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3230 } 3231 } 3232 3233 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3234 // default. If there's more than one, just leave everything alone. 3235 if (browserPkg == null) { 3236 calculateDefaultBrowserLPw(userId); 3237 } 3238 } 3239 3240 private void calculateDefaultBrowserLPw(int userId) { 3241 List<String> allBrowsers = resolveAllBrowserApps(userId); 3242 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3243 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3244 } 3245 3246 private List<String> resolveAllBrowserApps(int userId) { 3247 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3248 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3249 PackageManager.MATCH_ALL, userId); 3250 3251 final int count = list.size(); 3252 List<String> result = new ArrayList<String>(count); 3253 for (int i=0; i<count; i++) { 3254 ResolveInfo info = list.get(i); 3255 if (info.activityInfo == null 3256 || !info.handleAllWebDataURI 3257 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3258 || result.contains(info.activityInfo.packageName)) { 3259 continue; 3260 } 3261 result.add(info.activityInfo.packageName); 3262 } 3263 3264 return result; 3265 } 3266 3267 private boolean packageIsBrowser(String packageName, int userId) { 3268 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3269 PackageManager.MATCH_ALL, userId); 3270 final int N = list.size(); 3271 for (int i = 0; i < N; i++) { 3272 ResolveInfo info = list.get(i); 3273 if (packageName.equals(info.activityInfo.packageName)) { 3274 return true; 3275 } 3276 } 3277 return false; 3278 } 3279 3280 private void checkDefaultBrowser() { 3281 final int myUserId = UserHandle.myUserId(); 3282 final String packageName = getDefaultBrowserPackageName(myUserId); 3283 if (packageName != null) { 3284 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3285 if (info == null) { 3286 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3287 synchronized (mPackages) { 3288 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3289 } 3290 } 3291 } 3292 } 3293 3294 @Override 3295 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3296 throws RemoteException { 3297 try { 3298 return super.onTransact(code, data, reply, flags); 3299 } catch (RuntimeException e) { 3300 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3301 Slog.wtf(TAG, "Package Manager Crash", e); 3302 } 3303 throw e; 3304 } 3305 } 3306 3307 static int[] appendInts(int[] cur, int[] add) { 3308 if (add == null) return cur; 3309 if (cur == null) return add; 3310 final int N = add.length; 3311 for (int i=0; i<N; i++) { 3312 cur = appendInt(cur, add[i]); 3313 } 3314 return cur; 3315 } 3316 3317 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3318 if (!sUserManager.exists(userId)) return null; 3319 if (ps == null) { 3320 return null; 3321 } 3322 final PackageParser.Package p = ps.pkg; 3323 if (p == null) { 3324 return null; 3325 } 3326 // Filter out ephemeral app metadata: 3327 // * The system/shell/root can see metadata for any app 3328 // * An installed app can see metadata for 1) other installed apps 3329 // and 2) ephemeral apps that have explicitly interacted with it 3330 // * Ephemeral apps can only see their own metadata 3331 // * Holding a signature permission allows seeing instant apps 3332 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3333 if (callingAppId != Process.SYSTEM_UID 3334 && callingAppId != Process.SHELL_UID 3335 && callingAppId != Process.ROOT_UID 3336 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3337 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3338 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3339 if (instantAppPackageName != null) { 3340 // ephemeral apps can only get information on themselves 3341 if (!instantAppPackageName.equals(p.packageName)) { 3342 return null; 3343 } 3344 } else { 3345 if (ps.getInstantApp(userId)) { 3346 // only get access to the ephemeral app if we've been granted access 3347 if (!mInstantAppRegistry.isInstantAccessGranted( 3348 userId, callingAppId, ps.appId)) { 3349 return null; 3350 } 3351 } 3352 } 3353 } 3354 3355 final PermissionsState permissionsState = ps.getPermissionsState(); 3356 3357 // Compute GIDs only if requested 3358 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3359 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3360 // Compute granted permissions only if package has requested permissions 3361 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3362 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3363 final PackageUserState state = ps.readUserState(userId); 3364 3365 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3366 && ps.isSystem()) { 3367 flags |= MATCH_ANY_USER; 3368 } 3369 3370 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3371 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3372 3373 if (packageInfo == null) { 3374 return null; 3375 } 3376 3377 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3378 resolveExternalPackageNameLPr(p); 3379 3380 return packageInfo; 3381 } 3382 3383 @Override 3384 public void checkPackageStartable(String packageName, int userId) { 3385 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3386 3387 synchronized (mPackages) { 3388 final PackageSetting ps = mSettings.mPackages.get(packageName); 3389 if (ps == null) { 3390 throw new SecurityException("Package " + packageName + " was not found!"); 3391 } 3392 3393 if (!ps.getInstalled(userId)) { 3394 throw new SecurityException( 3395 "Package " + packageName + " was not installed for user " + userId + "!"); 3396 } 3397 3398 if (mSafeMode && !ps.isSystem()) { 3399 throw new SecurityException("Package " + packageName + " not a system app!"); 3400 } 3401 3402 if (mFrozenPackages.contains(packageName)) { 3403 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3404 } 3405 3406 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3407 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3408 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3409 } 3410 } 3411 } 3412 3413 @Override 3414 public boolean isPackageAvailable(String packageName, int userId) { 3415 if (!sUserManager.exists(userId)) return false; 3416 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3417 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3418 synchronized (mPackages) { 3419 PackageParser.Package p = mPackages.get(packageName); 3420 if (p != null) { 3421 final PackageSetting ps = (PackageSetting) p.mExtras; 3422 if (ps != null) { 3423 final PackageUserState state = ps.readUserState(userId); 3424 if (state != null) { 3425 return PackageParser.isAvailable(state); 3426 } 3427 } 3428 } 3429 } 3430 return false; 3431 } 3432 3433 @Override 3434 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3435 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3436 flags, userId); 3437 } 3438 3439 @Override 3440 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3441 int flags, int userId) { 3442 return getPackageInfoInternal(versionedPackage.getPackageName(), 3443 // TODO: We will change version code to long, so in the new API it is long 3444 (int) versionedPackage.getVersionCode(), flags, userId); 3445 } 3446 3447 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3448 int flags, int userId) { 3449 if (!sUserManager.exists(userId)) return null; 3450 flags = updateFlagsForPackage(flags, userId, packageName); 3451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3452 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3453 3454 // reader 3455 synchronized (mPackages) { 3456 // Normalize package name to handle renamed packages and static libs 3457 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3458 3459 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3460 if (matchFactoryOnly) { 3461 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3462 if (ps != null) { 3463 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3464 return null; 3465 } 3466 return generatePackageInfo(ps, flags, userId); 3467 } 3468 } 3469 3470 PackageParser.Package p = mPackages.get(packageName); 3471 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3472 return null; 3473 } 3474 if (DEBUG_PACKAGE_INFO) 3475 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3476 if (p != null) { 3477 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3478 Binder.getCallingUid(), userId)) { 3479 return null; 3480 } 3481 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3482 } 3483 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3484 final PackageSetting ps = mSettings.mPackages.get(packageName); 3485 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3486 return null; 3487 } 3488 return generatePackageInfo(ps, flags, userId); 3489 } 3490 } 3491 return null; 3492 } 3493 3494 3495 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3496 // System/shell/root get to see all static libs 3497 final int appId = UserHandle.getAppId(uid); 3498 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3499 || appId == Process.ROOT_UID) { 3500 return false; 3501 } 3502 3503 // No package means no static lib as it is always on internal storage 3504 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3505 return false; 3506 } 3507 3508 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3509 ps.pkg.staticSharedLibVersion); 3510 if (libEntry == null) { 3511 return false; 3512 } 3513 3514 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3515 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3516 if (uidPackageNames == null) { 3517 return true; 3518 } 3519 3520 for (String uidPackageName : uidPackageNames) { 3521 if (ps.name.equals(uidPackageName)) { 3522 return false; 3523 } 3524 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3525 if (uidPs != null) { 3526 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3527 libEntry.info.getName()); 3528 if (index < 0) { 3529 continue; 3530 } 3531 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3532 return false; 3533 } 3534 } 3535 } 3536 return true; 3537 } 3538 3539 @Override 3540 public String[] currentToCanonicalPackageNames(String[] names) { 3541 String[] out = new String[names.length]; 3542 // reader 3543 synchronized (mPackages) { 3544 for (int i=names.length-1; i>=0; i--) { 3545 PackageSetting ps = mSettings.mPackages.get(names[i]); 3546 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3547 } 3548 } 3549 return out; 3550 } 3551 3552 @Override 3553 public String[] canonicalToCurrentPackageNames(String[] names) { 3554 String[] out = new String[names.length]; 3555 // reader 3556 synchronized (mPackages) { 3557 for (int i=names.length-1; i>=0; i--) { 3558 String cur = mSettings.getRenamedPackageLPr(names[i]); 3559 out[i] = cur != null ? cur : names[i]; 3560 } 3561 } 3562 return out; 3563 } 3564 3565 @Override 3566 public int getPackageUid(String packageName, int flags, int userId) { 3567 if (!sUserManager.exists(userId)) return -1; 3568 flags = updateFlagsForPackage(flags, userId, packageName); 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3570 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3571 3572 // reader 3573 synchronized (mPackages) { 3574 final PackageParser.Package p = mPackages.get(packageName); 3575 if (p != null && p.isMatch(flags)) { 3576 return UserHandle.getUid(userId, p.applicationInfo.uid); 3577 } 3578 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3579 final PackageSetting ps = mSettings.mPackages.get(packageName); 3580 if (ps != null && ps.isMatch(flags)) { 3581 return UserHandle.getUid(userId, ps.appId); 3582 } 3583 } 3584 } 3585 3586 return -1; 3587 } 3588 3589 @Override 3590 public int[] getPackageGids(String packageName, int flags, int userId) { 3591 if (!sUserManager.exists(userId)) return null; 3592 flags = updateFlagsForPackage(flags, userId, packageName); 3593 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3594 false /* requireFullPermission */, false /* checkShell */, 3595 "getPackageGids"); 3596 3597 // reader 3598 synchronized (mPackages) { 3599 final PackageParser.Package p = mPackages.get(packageName); 3600 if (p != null && p.isMatch(flags)) { 3601 PackageSetting ps = (PackageSetting) p.mExtras; 3602 // TODO: Shouldn't this be checking for package installed state for userId and 3603 // return null? 3604 return ps.getPermissionsState().computeGids(userId); 3605 } 3606 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3607 final PackageSetting ps = mSettings.mPackages.get(packageName); 3608 if (ps != null && ps.isMatch(flags)) { 3609 return ps.getPermissionsState().computeGids(userId); 3610 } 3611 } 3612 } 3613 3614 return null; 3615 } 3616 3617 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3618 if (bp.perm != null) { 3619 return PackageParser.generatePermissionInfo(bp.perm, flags); 3620 } 3621 PermissionInfo pi = new PermissionInfo(); 3622 pi.name = bp.name; 3623 pi.packageName = bp.sourcePackage; 3624 pi.nonLocalizedLabel = bp.name; 3625 pi.protectionLevel = bp.protectionLevel; 3626 return pi; 3627 } 3628 3629 @Override 3630 public PermissionInfo getPermissionInfo(String name, int flags) { 3631 // reader 3632 synchronized (mPackages) { 3633 final BasePermission p = mSettings.mPermissions.get(name); 3634 if (p != null) { 3635 return generatePermissionInfo(p, flags); 3636 } 3637 return null; 3638 } 3639 } 3640 3641 @Override 3642 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3643 int flags) { 3644 // reader 3645 synchronized (mPackages) { 3646 if (group != null && !mPermissionGroups.containsKey(group)) { 3647 // This is thrown as NameNotFoundException 3648 return null; 3649 } 3650 3651 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3652 for (BasePermission p : mSettings.mPermissions.values()) { 3653 if (group == null) { 3654 if (p.perm == null || p.perm.info.group == null) { 3655 out.add(generatePermissionInfo(p, flags)); 3656 } 3657 } else { 3658 if (p.perm != null && group.equals(p.perm.info.group)) { 3659 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3660 } 3661 } 3662 } 3663 return new ParceledListSlice<>(out); 3664 } 3665 } 3666 3667 @Override 3668 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3669 // reader 3670 synchronized (mPackages) { 3671 return PackageParser.generatePermissionGroupInfo( 3672 mPermissionGroups.get(name), flags); 3673 } 3674 } 3675 3676 @Override 3677 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3678 // reader 3679 synchronized (mPackages) { 3680 final int N = mPermissionGroups.size(); 3681 ArrayList<PermissionGroupInfo> out 3682 = new ArrayList<PermissionGroupInfo>(N); 3683 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3684 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3685 } 3686 return new ParceledListSlice<>(out); 3687 } 3688 } 3689 3690 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3691 int uid, int userId) { 3692 if (!sUserManager.exists(userId)) return null; 3693 PackageSetting ps = mSettings.mPackages.get(packageName); 3694 if (ps != null) { 3695 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3696 return null; 3697 } 3698 if (ps.pkg == null) { 3699 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3700 if (pInfo != null) { 3701 return pInfo.applicationInfo; 3702 } 3703 return null; 3704 } 3705 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3706 ps.readUserState(userId), userId); 3707 if (ai != null) { 3708 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3709 } 3710 return ai; 3711 } 3712 return null; 3713 } 3714 3715 @Override 3716 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return null; 3718 flags = updateFlagsForApplication(flags, userId, packageName); 3719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3720 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3721 3722 // writer 3723 synchronized (mPackages) { 3724 // Normalize package name to handle renamed packages and static libs 3725 packageName = resolveInternalPackageNameLPr(packageName, 3726 PackageManager.VERSION_CODE_HIGHEST); 3727 3728 PackageParser.Package p = mPackages.get(packageName); 3729 if (DEBUG_PACKAGE_INFO) Log.v( 3730 TAG, "getApplicationInfo " + packageName 3731 + ": " + p); 3732 if (p != null) { 3733 PackageSetting ps = mSettings.mPackages.get(packageName); 3734 if (ps == null) return null; 3735 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3736 return null; 3737 } 3738 // Note: isEnabledLP() does not apply here - always return info 3739 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3740 p, flags, ps.readUserState(userId), userId); 3741 if (ai != null) { 3742 ai.packageName = resolveExternalPackageNameLPr(p); 3743 } 3744 return ai; 3745 } 3746 if ("android".equals(packageName)||"system".equals(packageName)) { 3747 return mAndroidApplication; 3748 } 3749 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3750 // Already generates the external package name 3751 return generateApplicationInfoFromSettingsLPw(packageName, 3752 Binder.getCallingUid(), flags, userId); 3753 } 3754 } 3755 return null; 3756 } 3757 3758 private String normalizePackageNameLPr(String packageName) { 3759 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3760 return normalizedPackageName != null ? normalizedPackageName : packageName; 3761 } 3762 3763 @Override 3764 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3765 final IPackageDataObserver observer) { 3766 mContext.enforceCallingOrSelfPermission( 3767 android.Manifest.permission.CLEAR_APP_CACHE, null); 3768 // Queue up an async operation since clearing cache may take a little while. 3769 mHandler.post(new Runnable() { 3770 public void run() { 3771 mHandler.removeCallbacks(this); 3772 boolean success = true; 3773 synchronized (mInstallLock) { 3774 try { 3775 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3776 } catch (InstallerException e) { 3777 Slog.w(TAG, "Couldn't clear application caches: " + e); 3778 success = false; 3779 } 3780 } 3781 if (observer != null) { 3782 try { 3783 observer.onRemoveCompleted(null, success); 3784 } catch (RemoteException e) { 3785 Slog.w(TAG, "RemoveException when invoking call back"); 3786 } 3787 } 3788 } 3789 }); 3790 } 3791 3792 @Override 3793 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3794 final IntentSender pi) { 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.CLEAR_APP_CACHE, null); 3797 // Queue up an async operation since clearing cache may take a little while. 3798 mHandler.post(new Runnable() { 3799 public void run() { 3800 mHandler.removeCallbacks(this); 3801 boolean success = true; 3802 synchronized (mInstallLock) { 3803 try { 3804 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3805 } catch (InstallerException e) { 3806 Slog.w(TAG, "Couldn't clear application caches: " + e); 3807 success = false; 3808 } 3809 } 3810 if(pi != null) { 3811 try { 3812 // Callback via pending intent 3813 int code = success ? 1 : 0; 3814 pi.sendIntent(null, code, null, 3815 null, null); 3816 } catch (SendIntentException e1) { 3817 Slog.i(TAG, "Failed to send pending intent"); 3818 } 3819 } 3820 } 3821 }); 3822 } 3823 3824 public void freeStorage(String volumeUuid, long freeStorageSize, int storageFlags) 3825 throws IOException { 3826 synchronized (mInstallLock) { 3827 try { 3828 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3829 } catch (InstallerException e) { 3830 throw new IOException("Failed to free enough space", e); 3831 } 3832 } 3833 } 3834 3835 /** 3836 * Update given flags based on encryption status of current user. 3837 */ 3838 private int updateFlags(int flags, int userId) { 3839 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3840 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3841 // Caller expressed an explicit opinion about what encryption 3842 // aware/unaware components they want to see, so fall through and 3843 // give them what they want 3844 } else { 3845 // Caller expressed no opinion, so match based on user state 3846 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3847 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3848 } else { 3849 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3850 } 3851 } 3852 return flags; 3853 } 3854 3855 private UserManagerInternal getUserManagerInternal() { 3856 if (mUserManagerInternal == null) { 3857 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3858 } 3859 return mUserManagerInternal; 3860 } 3861 3862 private DeviceIdleController.LocalService getDeviceIdleController() { 3863 if (mDeviceIdleController == null) { 3864 mDeviceIdleController = 3865 LocalServices.getService(DeviceIdleController.LocalService.class); 3866 } 3867 return mDeviceIdleController; 3868 } 3869 3870 /** 3871 * Update given flags when being used to request {@link PackageInfo}. 3872 */ 3873 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3874 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3875 boolean triaged = true; 3876 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3877 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3878 // Caller is asking for component details, so they'd better be 3879 // asking for specific encryption matching behavior, or be triaged 3880 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3881 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3882 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3883 triaged = false; 3884 } 3885 } 3886 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3887 | PackageManager.MATCH_SYSTEM_ONLY 3888 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3889 triaged = false; 3890 } 3891 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3892 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3893 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3894 + Debug.getCallers(5)); 3895 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3896 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3897 // If the caller wants all packages and has a restricted profile associated with it, 3898 // then match all users. This is to make sure that launchers that need to access work 3899 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3900 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3901 flags |= PackageManager.MATCH_ANY_USER; 3902 } 3903 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3904 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3905 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3906 } 3907 return updateFlags(flags, userId); 3908 } 3909 3910 /** 3911 * Update given flags when being used to request {@link ApplicationInfo}. 3912 */ 3913 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3914 return updateFlagsForPackage(flags, userId, cookie); 3915 } 3916 3917 /** 3918 * Update given flags when being used to request {@link ComponentInfo}. 3919 */ 3920 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3921 if (cookie instanceof Intent) { 3922 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3923 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3924 } 3925 } 3926 3927 boolean triaged = true; 3928 // Caller is asking for component details, so they'd better be 3929 // asking for specific encryption matching behavior, or be triaged 3930 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3931 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3932 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3933 triaged = false; 3934 } 3935 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3936 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3937 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3938 } 3939 3940 return updateFlags(flags, userId); 3941 } 3942 3943 /** 3944 * Update given intent when being used to request {@link ResolveInfo}. 3945 */ 3946 private Intent updateIntentForResolve(Intent intent) { 3947 if (intent.getSelector() != null) { 3948 intent = intent.getSelector(); 3949 } 3950 if (DEBUG_PREFERRED) { 3951 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3952 } 3953 return intent; 3954 } 3955 3956 /** 3957 * Update given flags when being used to request {@link ResolveInfo}. 3958 */ 3959 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3960 // Safe mode means we shouldn't match any third-party components 3961 if (mSafeMode) { 3962 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3963 } 3964 final int callingUid = Binder.getCallingUid(); 3965 if (getInstantAppPackageName(callingUid) != null) { 3966 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3967 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 3968 flags |= PackageManager.MATCH_INSTANT; 3969 } else { 3970 // Otherwise, prevent leaking ephemeral components 3971 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 3972 if (callingUid != Process.SYSTEM_UID 3973 && callingUid != Process.SHELL_UID 3974 && callingUid != 0) { 3975 // Unless called from the system process 3976 flags &= ~PackageManager.MATCH_INSTANT; 3977 } 3978 } 3979 return updateFlagsForComponent(flags, userId, cookie); 3980 } 3981 3982 @Override 3983 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3984 if (!sUserManager.exists(userId)) return null; 3985 flags = updateFlagsForComponent(flags, userId, component); 3986 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3987 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3988 synchronized (mPackages) { 3989 PackageParser.Activity a = mActivities.mActivities.get(component); 3990 3991 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3992 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3993 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3994 if (ps == null) return null; 3995 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3996 userId); 3997 } 3998 if (mResolveComponentName.equals(component)) { 3999 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4000 new PackageUserState(), userId); 4001 } 4002 } 4003 return null; 4004 } 4005 4006 @Override 4007 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4008 String resolvedType) { 4009 synchronized (mPackages) { 4010 if (component.equals(mResolveComponentName)) { 4011 // The resolver supports EVERYTHING! 4012 return true; 4013 } 4014 PackageParser.Activity a = mActivities.mActivities.get(component); 4015 if (a == null) { 4016 return false; 4017 } 4018 for (int i=0; i<a.intents.size(); i++) { 4019 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4020 intent.getData(), intent.getCategories(), TAG) >= 0) { 4021 return true; 4022 } 4023 } 4024 return false; 4025 } 4026 } 4027 4028 @Override 4029 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4030 if (!sUserManager.exists(userId)) return null; 4031 flags = updateFlagsForComponent(flags, userId, component); 4032 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4033 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4034 synchronized (mPackages) { 4035 PackageParser.Activity a = mReceivers.mActivities.get(component); 4036 if (DEBUG_PACKAGE_INFO) Log.v( 4037 TAG, "getReceiverInfo " + component + ": " + a); 4038 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4039 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4040 if (ps == null) return null; 4041 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4042 userId); 4043 } 4044 } 4045 return null; 4046 } 4047 4048 @Override 4049 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4050 if (!sUserManager.exists(userId)) return null; 4051 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4052 4053 flags = updateFlagsForPackage(flags, userId, null); 4054 4055 final boolean canSeeStaticLibraries = 4056 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4057 == PERMISSION_GRANTED 4058 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4059 == PERMISSION_GRANTED 4060 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4061 == PERMISSION_GRANTED 4062 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4063 == PERMISSION_GRANTED; 4064 4065 synchronized (mPackages) { 4066 List<SharedLibraryInfo> result = null; 4067 4068 final int libCount = mSharedLibraries.size(); 4069 for (int i = 0; i < libCount; i++) { 4070 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4071 if (versionedLib == null) { 4072 continue; 4073 } 4074 4075 final int versionCount = versionedLib.size(); 4076 for (int j = 0; j < versionCount; j++) { 4077 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4078 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4079 break; 4080 } 4081 final long identity = Binder.clearCallingIdentity(); 4082 try { 4083 // TODO: We will change version code to long, so in the new API it is long 4084 PackageInfo packageInfo = getPackageInfoVersioned( 4085 libInfo.getDeclaringPackage(), flags, userId); 4086 if (packageInfo == null) { 4087 continue; 4088 } 4089 } finally { 4090 Binder.restoreCallingIdentity(identity); 4091 } 4092 4093 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4094 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4095 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4096 4097 if (result == null) { 4098 result = new ArrayList<>(); 4099 } 4100 result.add(resLibInfo); 4101 } 4102 } 4103 4104 return result != null ? new ParceledListSlice<>(result) : null; 4105 } 4106 } 4107 4108 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4109 SharedLibraryInfo libInfo, int flags, int userId) { 4110 List<VersionedPackage> versionedPackages = null; 4111 final int packageCount = mSettings.mPackages.size(); 4112 for (int i = 0; i < packageCount; i++) { 4113 PackageSetting ps = mSettings.mPackages.valueAt(i); 4114 4115 if (ps == null) { 4116 continue; 4117 } 4118 4119 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4120 continue; 4121 } 4122 4123 final String libName = libInfo.getName(); 4124 if (libInfo.isStatic()) { 4125 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4126 if (libIdx < 0) { 4127 continue; 4128 } 4129 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4130 continue; 4131 } 4132 if (versionedPackages == null) { 4133 versionedPackages = new ArrayList<>(); 4134 } 4135 // If the dependent is a static shared lib, use the public package name 4136 String dependentPackageName = ps.name; 4137 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4138 dependentPackageName = ps.pkg.manifestPackageName; 4139 } 4140 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4141 } else if (ps.pkg != null) { 4142 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4143 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4144 if (versionedPackages == null) { 4145 versionedPackages = new ArrayList<>(); 4146 } 4147 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4148 } 4149 } 4150 } 4151 4152 return versionedPackages; 4153 } 4154 4155 @Override 4156 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4157 if (!sUserManager.exists(userId)) return null; 4158 flags = updateFlagsForComponent(flags, userId, component); 4159 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4160 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4161 synchronized (mPackages) { 4162 PackageParser.Service s = mServices.mServices.get(component); 4163 if (DEBUG_PACKAGE_INFO) Log.v( 4164 TAG, "getServiceInfo " + component + ": " + s); 4165 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4166 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4167 if (ps == null) return null; 4168 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4169 userId); 4170 } 4171 } 4172 return null; 4173 } 4174 4175 @Override 4176 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4177 if (!sUserManager.exists(userId)) return null; 4178 flags = updateFlagsForComponent(flags, userId, component); 4179 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4180 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4181 synchronized (mPackages) { 4182 PackageParser.Provider p = mProviders.mProviders.get(component); 4183 if (DEBUG_PACKAGE_INFO) Log.v( 4184 TAG, "getProviderInfo " + component + ": " + p); 4185 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4186 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4187 if (ps == null) return null; 4188 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4189 userId); 4190 } 4191 } 4192 return null; 4193 } 4194 4195 @Override 4196 public String[] getSystemSharedLibraryNames() { 4197 synchronized (mPackages) { 4198 Set<String> libs = null; 4199 final int libCount = mSharedLibraries.size(); 4200 for (int i = 0; i < libCount; i++) { 4201 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4202 if (versionedLib == null) { 4203 continue; 4204 } 4205 final int versionCount = versionedLib.size(); 4206 for (int j = 0; j < versionCount; j++) { 4207 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4208 if (!libEntry.info.isStatic()) { 4209 if (libs == null) { 4210 libs = new ArraySet<>(); 4211 } 4212 libs.add(libEntry.info.getName()); 4213 break; 4214 } 4215 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4216 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4217 UserHandle.getUserId(Binder.getCallingUid()))) { 4218 if (libs == null) { 4219 libs = new ArraySet<>(); 4220 } 4221 libs.add(libEntry.info.getName()); 4222 break; 4223 } 4224 } 4225 } 4226 4227 if (libs != null) { 4228 String[] libsArray = new String[libs.size()]; 4229 libs.toArray(libsArray); 4230 return libsArray; 4231 } 4232 4233 return null; 4234 } 4235 } 4236 4237 @Override 4238 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4239 synchronized (mPackages) { 4240 return mServicesSystemSharedLibraryPackageName; 4241 } 4242 } 4243 4244 @Override 4245 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4246 synchronized (mPackages) { 4247 return mSharedSystemSharedLibraryPackageName; 4248 } 4249 } 4250 4251 private void updateSequenceNumberLP(String packageName, int[] userList) { 4252 for (int i = userList.length - 1; i >= 0; --i) { 4253 final int userId = userList[i]; 4254 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4255 if (changedPackages == null) { 4256 changedPackages = new SparseArray<>(); 4257 mChangedPackages.put(userId, changedPackages); 4258 } 4259 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4260 if (sequenceNumbers == null) { 4261 sequenceNumbers = new HashMap<>(); 4262 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4263 } 4264 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4265 if (sequenceNumber != null) { 4266 changedPackages.remove(sequenceNumber); 4267 } 4268 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4269 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4270 } 4271 mChangedPackagesSequenceNumber++; 4272 } 4273 4274 @Override 4275 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4276 synchronized (mPackages) { 4277 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4278 return null; 4279 } 4280 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4281 if (changedPackages == null) { 4282 return null; 4283 } 4284 final List<String> packageNames = 4285 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4286 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4287 final String packageName = changedPackages.get(i); 4288 if (packageName != null) { 4289 packageNames.add(packageName); 4290 } 4291 } 4292 return packageNames.isEmpty() 4293 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4294 } 4295 } 4296 4297 @Override 4298 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4299 ArrayList<FeatureInfo> res; 4300 synchronized (mAvailableFeatures) { 4301 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4302 res.addAll(mAvailableFeatures.values()); 4303 } 4304 final FeatureInfo fi = new FeatureInfo(); 4305 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4306 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4307 res.add(fi); 4308 4309 return new ParceledListSlice<>(res); 4310 } 4311 4312 @Override 4313 public boolean hasSystemFeature(String name, int version) { 4314 synchronized (mAvailableFeatures) { 4315 final FeatureInfo feat = mAvailableFeatures.get(name); 4316 if (feat == null) { 4317 return false; 4318 } else { 4319 return feat.version >= version; 4320 } 4321 } 4322 } 4323 4324 @Override 4325 public int checkPermission(String permName, String pkgName, int userId) { 4326 if (!sUserManager.exists(userId)) { 4327 return PackageManager.PERMISSION_DENIED; 4328 } 4329 4330 synchronized (mPackages) { 4331 final PackageParser.Package p = mPackages.get(pkgName); 4332 if (p != null && p.mExtras != null) { 4333 final PackageSetting ps = (PackageSetting) p.mExtras; 4334 final PermissionsState permissionsState = ps.getPermissionsState(); 4335 if (permissionsState.hasPermission(permName, userId)) { 4336 return PackageManager.PERMISSION_GRANTED; 4337 } 4338 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4339 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4340 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4341 return PackageManager.PERMISSION_GRANTED; 4342 } 4343 } 4344 } 4345 4346 return PackageManager.PERMISSION_DENIED; 4347 } 4348 4349 @Override 4350 public int checkUidPermission(String permName, int uid) { 4351 final int userId = UserHandle.getUserId(uid); 4352 4353 if (!sUserManager.exists(userId)) { 4354 return PackageManager.PERMISSION_DENIED; 4355 } 4356 4357 synchronized (mPackages) { 4358 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4359 if (obj != null) { 4360 final SettingBase ps = (SettingBase) obj; 4361 final PermissionsState permissionsState = ps.getPermissionsState(); 4362 if (permissionsState.hasPermission(permName, userId)) { 4363 return PackageManager.PERMISSION_GRANTED; 4364 } 4365 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4366 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4367 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4368 return PackageManager.PERMISSION_GRANTED; 4369 } 4370 } else { 4371 ArraySet<String> perms = mSystemPermissions.get(uid); 4372 if (perms != null) { 4373 if (perms.contains(permName)) { 4374 return PackageManager.PERMISSION_GRANTED; 4375 } 4376 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4377 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4378 return PackageManager.PERMISSION_GRANTED; 4379 } 4380 } 4381 } 4382 } 4383 4384 return PackageManager.PERMISSION_DENIED; 4385 } 4386 4387 @Override 4388 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4389 if (UserHandle.getCallingUserId() != userId) { 4390 mContext.enforceCallingPermission( 4391 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4392 "isPermissionRevokedByPolicy for user " + userId); 4393 } 4394 4395 if (checkPermission(permission, packageName, userId) 4396 == PackageManager.PERMISSION_GRANTED) { 4397 return false; 4398 } 4399 4400 final long identity = Binder.clearCallingIdentity(); 4401 try { 4402 final int flags = getPermissionFlags(permission, packageName, userId); 4403 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4404 } finally { 4405 Binder.restoreCallingIdentity(identity); 4406 } 4407 } 4408 4409 @Override 4410 public String getPermissionControllerPackageName() { 4411 synchronized (mPackages) { 4412 return mRequiredInstallerPackage; 4413 } 4414 } 4415 4416 /** 4417 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4418 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4419 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4420 * @param message the message to log on security exception 4421 */ 4422 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4423 boolean checkShell, String message) { 4424 if (userId < 0) { 4425 throw new IllegalArgumentException("Invalid userId " + userId); 4426 } 4427 if (checkShell) { 4428 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4429 } 4430 if (userId == UserHandle.getUserId(callingUid)) return; 4431 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4432 if (requireFullPermission) { 4433 mContext.enforceCallingOrSelfPermission( 4434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4435 } else { 4436 try { 4437 mContext.enforceCallingOrSelfPermission( 4438 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4439 } catch (SecurityException se) { 4440 mContext.enforceCallingOrSelfPermission( 4441 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4442 } 4443 } 4444 } 4445 } 4446 4447 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4448 if (callingUid == Process.SHELL_UID) { 4449 if (userHandle >= 0 4450 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4451 throw new SecurityException("Shell does not have permission to access user " 4452 + userHandle); 4453 } else if (userHandle < 0) { 4454 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4455 + Debug.getCallers(3)); 4456 } 4457 } 4458 } 4459 4460 private BasePermission findPermissionTreeLP(String permName) { 4461 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4462 if (permName.startsWith(bp.name) && 4463 permName.length() > bp.name.length() && 4464 permName.charAt(bp.name.length()) == '.') { 4465 return bp; 4466 } 4467 } 4468 return null; 4469 } 4470 4471 private BasePermission checkPermissionTreeLP(String permName) { 4472 if (permName != null) { 4473 BasePermission bp = findPermissionTreeLP(permName); 4474 if (bp != null) { 4475 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4476 return bp; 4477 } 4478 throw new SecurityException("Calling uid " 4479 + Binder.getCallingUid() 4480 + " is not allowed to add to permission tree " 4481 + bp.name + " owned by uid " + bp.uid); 4482 } 4483 } 4484 throw new SecurityException("No permission tree found for " + permName); 4485 } 4486 4487 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4488 if (s1 == null) { 4489 return s2 == null; 4490 } 4491 if (s2 == null) { 4492 return false; 4493 } 4494 if (s1.getClass() != s2.getClass()) { 4495 return false; 4496 } 4497 return s1.equals(s2); 4498 } 4499 4500 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4501 if (pi1.icon != pi2.icon) return false; 4502 if (pi1.logo != pi2.logo) return false; 4503 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4504 if (!compareStrings(pi1.name, pi2.name)) return false; 4505 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4506 // We'll take care of setting this one. 4507 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4508 // These are not currently stored in settings. 4509 //if (!compareStrings(pi1.group, pi2.group)) return false; 4510 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4511 //if (pi1.labelRes != pi2.labelRes) return false; 4512 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4513 return true; 4514 } 4515 4516 int permissionInfoFootprint(PermissionInfo info) { 4517 int size = info.name.length(); 4518 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4519 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4520 return size; 4521 } 4522 4523 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4524 int size = 0; 4525 for (BasePermission perm : mSettings.mPermissions.values()) { 4526 if (perm.uid == tree.uid) { 4527 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4528 } 4529 } 4530 return size; 4531 } 4532 4533 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4534 // We calculate the max size of permissions defined by this uid and throw 4535 // if that plus the size of 'info' would exceed our stated maximum. 4536 if (tree.uid != Process.SYSTEM_UID) { 4537 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4538 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4539 throw new SecurityException("Permission tree size cap exceeded"); 4540 } 4541 } 4542 } 4543 4544 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4545 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4546 throw new SecurityException("Label must be specified in permission"); 4547 } 4548 BasePermission tree = checkPermissionTreeLP(info.name); 4549 BasePermission bp = mSettings.mPermissions.get(info.name); 4550 boolean added = bp == null; 4551 boolean changed = true; 4552 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4553 if (added) { 4554 enforcePermissionCapLocked(info, tree); 4555 bp = new BasePermission(info.name, tree.sourcePackage, 4556 BasePermission.TYPE_DYNAMIC); 4557 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4558 throw new SecurityException( 4559 "Not allowed to modify non-dynamic permission " 4560 + info.name); 4561 } else { 4562 if (bp.protectionLevel == fixedLevel 4563 && bp.perm.owner.equals(tree.perm.owner) 4564 && bp.uid == tree.uid 4565 && comparePermissionInfos(bp.perm.info, info)) { 4566 changed = false; 4567 } 4568 } 4569 bp.protectionLevel = fixedLevel; 4570 info = new PermissionInfo(info); 4571 info.protectionLevel = fixedLevel; 4572 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4573 bp.perm.info.packageName = tree.perm.info.packageName; 4574 bp.uid = tree.uid; 4575 if (added) { 4576 mSettings.mPermissions.put(info.name, bp); 4577 } 4578 if (changed) { 4579 if (!async) { 4580 mSettings.writeLPr(); 4581 } else { 4582 scheduleWriteSettingsLocked(); 4583 } 4584 } 4585 return added; 4586 } 4587 4588 @Override 4589 public boolean addPermission(PermissionInfo info) { 4590 synchronized (mPackages) { 4591 return addPermissionLocked(info, false); 4592 } 4593 } 4594 4595 @Override 4596 public boolean addPermissionAsync(PermissionInfo info) { 4597 synchronized (mPackages) { 4598 return addPermissionLocked(info, true); 4599 } 4600 } 4601 4602 @Override 4603 public void removePermission(String name) { 4604 synchronized (mPackages) { 4605 checkPermissionTreeLP(name); 4606 BasePermission bp = mSettings.mPermissions.get(name); 4607 if (bp != null) { 4608 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4609 throw new SecurityException( 4610 "Not allowed to modify non-dynamic permission " 4611 + name); 4612 } 4613 mSettings.mPermissions.remove(name); 4614 mSettings.writeLPr(); 4615 } 4616 } 4617 } 4618 4619 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4620 BasePermission bp) { 4621 int index = pkg.requestedPermissions.indexOf(bp.name); 4622 if (index == -1) { 4623 throw new SecurityException("Package " + pkg.packageName 4624 + " has not requested permission " + bp.name); 4625 } 4626 if (!bp.isRuntime() && !bp.isDevelopment()) { 4627 throw new SecurityException("Permission " + bp.name 4628 + " is not a changeable permission type"); 4629 } 4630 } 4631 4632 @Override 4633 public void grantRuntimePermission(String packageName, String name, final int userId) { 4634 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4635 } 4636 4637 private void grantRuntimePermission(String packageName, String name, final int userId, 4638 boolean overridePolicy) { 4639 if (!sUserManager.exists(userId)) { 4640 Log.e(TAG, "No such user:" + userId); 4641 return; 4642 } 4643 4644 mContext.enforceCallingOrSelfPermission( 4645 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4646 "grantRuntimePermission"); 4647 4648 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4649 true /* requireFullPermission */, true /* checkShell */, 4650 "grantRuntimePermission"); 4651 4652 final int uid; 4653 final SettingBase sb; 4654 4655 synchronized (mPackages) { 4656 final PackageParser.Package pkg = mPackages.get(packageName); 4657 if (pkg == null) { 4658 throw new IllegalArgumentException("Unknown package: " + packageName); 4659 } 4660 4661 final BasePermission bp = mSettings.mPermissions.get(name); 4662 if (bp == null) { 4663 throw new IllegalArgumentException("Unknown permission: " + name); 4664 } 4665 4666 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4667 4668 // If a permission review is required for legacy apps we represent 4669 // their permissions as always granted runtime ones since we need 4670 // to keep the review required permission flag per user while an 4671 // install permission's state is shared across all users. 4672 if (mPermissionReviewRequired 4673 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4674 && bp.isRuntime()) { 4675 return; 4676 } 4677 4678 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4679 sb = (SettingBase) pkg.mExtras; 4680 if (sb == null) { 4681 throw new IllegalArgumentException("Unknown package: " + packageName); 4682 } 4683 4684 final PermissionsState permissionsState = sb.getPermissionsState(); 4685 4686 final int flags = permissionsState.getPermissionFlags(name, userId); 4687 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4688 throw new SecurityException("Cannot grant system fixed permission " 4689 + name + " for package " + packageName); 4690 } 4691 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4692 throw new SecurityException("Cannot grant policy fixed permission " 4693 + name + " for package " + packageName); 4694 } 4695 4696 if (bp.isDevelopment()) { 4697 // Development permissions must be handled specially, since they are not 4698 // normal runtime permissions. For now they apply to all users. 4699 if (permissionsState.grantInstallPermission(bp) != 4700 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4701 scheduleWriteSettingsLocked(); 4702 } 4703 return; 4704 } 4705 4706 final PackageSetting ps = mSettings.mPackages.get(packageName); 4707 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4708 throw new SecurityException("Cannot grant non-ephemeral permission" 4709 + name + " for package " + packageName); 4710 } 4711 4712 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4713 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4714 return; 4715 } 4716 4717 final int result = permissionsState.grantRuntimePermission(bp, userId); 4718 switch (result) { 4719 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4720 return; 4721 } 4722 4723 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4724 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4725 mHandler.post(new Runnable() { 4726 @Override 4727 public void run() { 4728 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4729 } 4730 }); 4731 } 4732 break; 4733 } 4734 4735 if (bp.isRuntime()) { 4736 logPermissionGranted(mContext, name, packageName); 4737 } 4738 4739 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4740 4741 // Not critical if that is lost - app has to request again. 4742 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4743 } 4744 4745 // Only need to do this if user is initialized. Otherwise it's a new user 4746 // and there are no processes running as the user yet and there's no need 4747 // to make an expensive call to remount processes for the changed permissions. 4748 if (READ_EXTERNAL_STORAGE.equals(name) 4749 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4750 final long token = Binder.clearCallingIdentity(); 4751 try { 4752 if (sUserManager.isInitialized(userId)) { 4753 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4754 StorageManagerInternal.class); 4755 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4756 } 4757 } finally { 4758 Binder.restoreCallingIdentity(token); 4759 } 4760 } 4761 } 4762 4763 @Override 4764 public void revokeRuntimePermission(String packageName, String name, int userId) { 4765 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4766 } 4767 4768 private void revokeRuntimePermission(String packageName, String name, int userId, 4769 boolean overridePolicy) { 4770 if (!sUserManager.exists(userId)) { 4771 Log.e(TAG, "No such user:" + userId); 4772 return; 4773 } 4774 4775 mContext.enforceCallingOrSelfPermission( 4776 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4777 "revokeRuntimePermission"); 4778 4779 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4780 true /* requireFullPermission */, true /* checkShell */, 4781 "revokeRuntimePermission"); 4782 4783 final int appId; 4784 4785 synchronized (mPackages) { 4786 final PackageParser.Package pkg = mPackages.get(packageName); 4787 if (pkg == null) { 4788 throw new IllegalArgumentException("Unknown package: " + packageName); 4789 } 4790 4791 final BasePermission bp = mSettings.mPermissions.get(name); 4792 if (bp == null) { 4793 throw new IllegalArgumentException("Unknown permission: " + name); 4794 } 4795 4796 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4797 4798 // If a permission review is required for legacy apps we represent 4799 // their permissions as always granted runtime ones since we need 4800 // to keep the review required permission flag per user while an 4801 // install permission's state is shared across all users. 4802 if (mPermissionReviewRequired 4803 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4804 && bp.isRuntime()) { 4805 return; 4806 } 4807 4808 SettingBase sb = (SettingBase) pkg.mExtras; 4809 if (sb == null) { 4810 throw new IllegalArgumentException("Unknown package: " + packageName); 4811 } 4812 4813 final PermissionsState permissionsState = sb.getPermissionsState(); 4814 4815 final int flags = permissionsState.getPermissionFlags(name, userId); 4816 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4817 throw new SecurityException("Cannot revoke system fixed permission " 4818 + name + " for package " + packageName); 4819 } 4820 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4821 throw new SecurityException("Cannot revoke policy fixed permission " 4822 + name + " for package " + packageName); 4823 } 4824 4825 if (bp.isDevelopment()) { 4826 // Development permissions must be handled specially, since they are not 4827 // normal runtime permissions. For now they apply to all users. 4828 if (permissionsState.revokeInstallPermission(bp) != 4829 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4830 scheduleWriteSettingsLocked(); 4831 } 4832 return; 4833 } 4834 4835 if (permissionsState.revokeRuntimePermission(bp, userId) == 4836 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4837 return; 4838 } 4839 4840 if (bp.isRuntime()) { 4841 logPermissionRevoked(mContext, name, packageName); 4842 } 4843 4844 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4845 4846 // Critical, after this call app should never have the permission. 4847 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4848 4849 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4850 } 4851 4852 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4853 } 4854 4855 /** 4856 * Get the first event id for the permission. 4857 * 4858 * <p>There are four events for each permission: <ul> 4859 * <li>Request permission: first id + 0</li> 4860 * <li>Grant permission: first id + 1</li> 4861 * <li>Request for permission denied: first id + 2</li> 4862 * <li>Revoke permission: first id + 3</li> 4863 * </ul></p> 4864 * 4865 * @param name name of the permission 4866 * 4867 * @return The first event id for the permission 4868 */ 4869 private static int getBaseEventId(@NonNull String name) { 4870 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4871 4872 if (eventIdIndex == -1) { 4873 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4874 || "user".equals(Build.TYPE)) { 4875 Log.i(TAG, "Unknown permission " + name); 4876 4877 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4878 } else { 4879 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4880 // 4881 // Also update 4882 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4883 // - metrics_constants.proto 4884 throw new IllegalStateException("Unknown permission " + name); 4885 } 4886 } 4887 4888 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4889 } 4890 4891 /** 4892 * Log that a permission was revoked. 4893 * 4894 * @param context Context of the caller 4895 * @param name name of the permission 4896 * @param packageName package permission if for 4897 */ 4898 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4899 @NonNull String packageName) { 4900 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4901 } 4902 4903 /** 4904 * Log that a permission request was granted. 4905 * 4906 * @param context Context of the caller 4907 * @param name name of the permission 4908 * @param packageName package permission if for 4909 */ 4910 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4911 @NonNull String packageName) { 4912 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4913 } 4914 4915 @Override 4916 public void resetRuntimePermissions() { 4917 mContext.enforceCallingOrSelfPermission( 4918 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4919 "revokeRuntimePermission"); 4920 4921 int callingUid = Binder.getCallingUid(); 4922 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4923 mContext.enforceCallingOrSelfPermission( 4924 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4925 "resetRuntimePermissions"); 4926 } 4927 4928 synchronized (mPackages) { 4929 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4930 for (int userId : UserManagerService.getInstance().getUserIds()) { 4931 final int packageCount = mPackages.size(); 4932 for (int i = 0; i < packageCount; i++) { 4933 PackageParser.Package pkg = mPackages.valueAt(i); 4934 if (!(pkg.mExtras instanceof PackageSetting)) { 4935 continue; 4936 } 4937 PackageSetting ps = (PackageSetting) pkg.mExtras; 4938 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4939 } 4940 } 4941 } 4942 } 4943 4944 @Override 4945 public int getPermissionFlags(String name, String packageName, int userId) { 4946 if (!sUserManager.exists(userId)) { 4947 return 0; 4948 } 4949 4950 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4951 4952 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4953 true /* requireFullPermission */, false /* checkShell */, 4954 "getPermissionFlags"); 4955 4956 synchronized (mPackages) { 4957 final PackageParser.Package pkg = mPackages.get(packageName); 4958 if (pkg == null) { 4959 return 0; 4960 } 4961 4962 final BasePermission bp = mSettings.mPermissions.get(name); 4963 if (bp == null) { 4964 return 0; 4965 } 4966 4967 SettingBase sb = (SettingBase) pkg.mExtras; 4968 if (sb == null) { 4969 return 0; 4970 } 4971 4972 PermissionsState permissionsState = sb.getPermissionsState(); 4973 return permissionsState.getPermissionFlags(name, userId); 4974 } 4975 } 4976 4977 @Override 4978 public void updatePermissionFlags(String name, String packageName, int flagMask, 4979 int flagValues, int userId) { 4980 if (!sUserManager.exists(userId)) { 4981 return; 4982 } 4983 4984 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4985 4986 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4987 true /* requireFullPermission */, true /* checkShell */, 4988 "updatePermissionFlags"); 4989 4990 // Only the system can change these flags and nothing else. 4991 if (getCallingUid() != Process.SYSTEM_UID) { 4992 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4993 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4994 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4995 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4996 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4997 } 4998 4999 synchronized (mPackages) { 5000 final PackageParser.Package pkg = mPackages.get(packageName); 5001 if (pkg == null) { 5002 throw new IllegalArgumentException("Unknown package: " + packageName); 5003 } 5004 5005 final BasePermission bp = mSettings.mPermissions.get(name); 5006 if (bp == null) { 5007 throw new IllegalArgumentException("Unknown permission: " + name); 5008 } 5009 5010 SettingBase sb = (SettingBase) pkg.mExtras; 5011 if (sb == null) { 5012 throw new IllegalArgumentException("Unknown package: " + packageName); 5013 } 5014 5015 PermissionsState permissionsState = sb.getPermissionsState(); 5016 5017 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5018 5019 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5020 // Install and runtime permissions are stored in different places, 5021 // so figure out what permission changed and persist the change. 5022 if (permissionsState.getInstallPermissionState(name) != null) { 5023 scheduleWriteSettingsLocked(); 5024 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5025 || hadState) { 5026 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5027 } 5028 } 5029 } 5030 } 5031 5032 /** 5033 * Update the permission flags for all packages and runtime permissions of a user in order 5034 * to allow device or profile owner to remove POLICY_FIXED. 5035 */ 5036 @Override 5037 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5038 if (!sUserManager.exists(userId)) { 5039 return; 5040 } 5041 5042 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5043 5044 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5045 true /* requireFullPermission */, true /* checkShell */, 5046 "updatePermissionFlagsForAllApps"); 5047 5048 // Only the system can change system fixed flags. 5049 if (getCallingUid() != Process.SYSTEM_UID) { 5050 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5051 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5052 } 5053 5054 synchronized (mPackages) { 5055 boolean changed = false; 5056 final int packageCount = mPackages.size(); 5057 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5058 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5059 SettingBase sb = (SettingBase) pkg.mExtras; 5060 if (sb == null) { 5061 continue; 5062 } 5063 PermissionsState permissionsState = sb.getPermissionsState(); 5064 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5065 userId, flagMask, flagValues); 5066 } 5067 if (changed) { 5068 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5069 } 5070 } 5071 } 5072 5073 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5074 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5075 != PackageManager.PERMISSION_GRANTED 5076 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5077 != PackageManager.PERMISSION_GRANTED) { 5078 throw new SecurityException(message + " requires " 5079 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5080 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5081 } 5082 } 5083 5084 @Override 5085 public boolean shouldShowRequestPermissionRationale(String permissionName, 5086 String packageName, int userId) { 5087 if (UserHandle.getCallingUserId() != userId) { 5088 mContext.enforceCallingPermission( 5089 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5090 "canShowRequestPermissionRationale for user " + userId); 5091 } 5092 5093 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5094 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5095 return false; 5096 } 5097 5098 if (checkPermission(permissionName, packageName, userId) 5099 == PackageManager.PERMISSION_GRANTED) { 5100 return false; 5101 } 5102 5103 final int flags; 5104 5105 final long identity = Binder.clearCallingIdentity(); 5106 try { 5107 flags = getPermissionFlags(permissionName, 5108 packageName, userId); 5109 } finally { 5110 Binder.restoreCallingIdentity(identity); 5111 } 5112 5113 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5114 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5115 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5116 5117 if ((flags & fixedFlags) != 0) { 5118 return false; 5119 } 5120 5121 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5122 } 5123 5124 @Override 5125 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5126 mContext.enforceCallingOrSelfPermission( 5127 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5128 "addOnPermissionsChangeListener"); 5129 5130 synchronized (mPackages) { 5131 mOnPermissionChangeListeners.addListenerLocked(listener); 5132 } 5133 } 5134 5135 @Override 5136 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5137 synchronized (mPackages) { 5138 mOnPermissionChangeListeners.removeListenerLocked(listener); 5139 } 5140 } 5141 5142 @Override 5143 public boolean isProtectedBroadcast(String actionName) { 5144 synchronized (mPackages) { 5145 if (mProtectedBroadcasts.contains(actionName)) { 5146 return true; 5147 } else if (actionName != null) { 5148 // TODO: remove these terrible hacks 5149 if (actionName.startsWith("android.net.netmon.lingerExpired") 5150 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5151 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5152 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5153 return true; 5154 } 5155 } 5156 } 5157 return false; 5158 } 5159 5160 @Override 5161 public int checkSignatures(String pkg1, String pkg2) { 5162 synchronized (mPackages) { 5163 final PackageParser.Package p1 = mPackages.get(pkg1); 5164 final PackageParser.Package p2 = mPackages.get(pkg2); 5165 if (p1 == null || p1.mExtras == null 5166 || p2 == null || p2.mExtras == null) { 5167 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5168 } 5169 return compareSignatures(p1.mSignatures, p2.mSignatures); 5170 } 5171 } 5172 5173 @Override 5174 public int checkUidSignatures(int uid1, int uid2) { 5175 // Map to base uids. 5176 uid1 = UserHandle.getAppId(uid1); 5177 uid2 = UserHandle.getAppId(uid2); 5178 // reader 5179 synchronized (mPackages) { 5180 Signature[] s1; 5181 Signature[] s2; 5182 Object obj = mSettings.getUserIdLPr(uid1); 5183 if (obj != null) { 5184 if (obj instanceof SharedUserSetting) { 5185 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5186 } else if (obj instanceof PackageSetting) { 5187 s1 = ((PackageSetting)obj).signatures.mSignatures; 5188 } else { 5189 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5190 } 5191 } else { 5192 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5193 } 5194 obj = mSettings.getUserIdLPr(uid2); 5195 if (obj != null) { 5196 if (obj instanceof SharedUserSetting) { 5197 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5198 } else if (obj instanceof PackageSetting) { 5199 s2 = ((PackageSetting)obj).signatures.mSignatures; 5200 } else { 5201 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5202 } 5203 } else { 5204 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5205 } 5206 return compareSignatures(s1, s2); 5207 } 5208 } 5209 5210 /** 5211 * This method should typically only be used when granting or revoking 5212 * permissions, since the app may immediately restart after this call. 5213 * <p> 5214 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5215 * guard your work against the app being relaunched. 5216 */ 5217 private void killUid(int appId, int userId, String reason) { 5218 final long identity = Binder.clearCallingIdentity(); 5219 try { 5220 IActivityManager am = ActivityManager.getService(); 5221 if (am != null) { 5222 try { 5223 am.killUid(appId, userId, reason); 5224 } catch (RemoteException e) { 5225 /* ignore - same process */ 5226 } 5227 } 5228 } finally { 5229 Binder.restoreCallingIdentity(identity); 5230 } 5231 } 5232 5233 /** 5234 * Compares two sets of signatures. Returns: 5235 * <br /> 5236 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5237 * <br /> 5238 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5239 * <br /> 5240 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5241 * <br /> 5242 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5243 * <br /> 5244 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5245 */ 5246 static int compareSignatures(Signature[] s1, Signature[] s2) { 5247 if (s1 == null) { 5248 return s2 == null 5249 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5250 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5251 } 5252 5253 if (s2 == null) { 5254 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5255 } 5256 5257 if (s1.length != s2.length) { 5258 return PackageManager.SIGNATURE_NO_MATCH; 5259 } 5260 5261 // Since both signature sets are of size 1, we can compare without HashSets. 5262 if (s1.length == 1) { 5263 return s1[0].equals(s2[0]) ? 5264 PackageManager.SIGNATURE_MATCH : 5265 PackageManager.SIGNATURE_NO_MATCH; 5266 } 5267 5268 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5269 for (Signature sig : s1) { 5270 set1.add(sig); 5271 } 5272 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5273 for (Signature sig : s2) { 5274 set2.add(sig); 5275 } 5276 // Make sure s2 contains all signatures in s1. 5277 if (set1.equals(set2)) { 5278 return PackageManager.SIGNATURE_MATCH; 5279 } 5280 return PackageManager.SIGNATURE_NO_MATCH; 5281 } 5282 5283 /** 5284 * If the database version for this type of package (internal storage or 5285 * external storage) is less than the version where package signatures 5286 * were updated, return true. 5287 */ 5288 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5289 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5290 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5291 } 5292 5293 /** 5294 * Used for backward compatibility to make sure any packages with 5295 * certificate chains get upgraded to the new style. {@code existingSigs} 5296 * will be in the old format (since they were stored on disk from before the 5297 * system upgrade) and {@code scannedSigs} will be in the newer format. 5298 */ 5299 private int compareSignaturesCompat(PackageSignatures existingSigs, 5300 PackageParser.Package scannedPkg) { 5301 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5302 return PackageManager.SIGNATURE_NO_MATCH; 5303 } 5304 5305 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5306 for (Signature sig : existingSigs.mSignatures) { 5307 existingSet.add(sig); 5308 } 5309 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5310 for (Signature sig : scannedPkg.mSignatures) { 5311 try { 5312 Signature[] chainSignatures = sig.getChainSignatures(); 5313 for (Signature chainSig : chainSignatures) { 5314 scannedCompatSet.add(chainSig); 5315 } 5316 } catch (CertificateEncodingException e) { 5317 scannedCompatSet.add(sig); 5318 } 5319 } 5320 /* 5321 * Make sure the expanded scanned set contains all signatures in the 5322 * existing one. 5323 */ 5324 if (scannedCompatSet.equals(existingSet)) { 5325 // Migrate the old signatures to the new scheme. 5326 existingSigs.assignSignatures(scannedPkg.mSignatures); 5327 // The new KeySets will be re-added later in the scanning process. 5328 synchronized (mPackages) { 5329 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5330 } 5331 return PackageManager.SIGNATURE_MATCH; 5332 } 5333 return PackageManager.SIGNATURE_NO_MATCH; 5334 } 5335 5336 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5337 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5338 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5339 } 5340 5341 private int compareSignaturesRecover(PackageSignatures existingSigs, 5342 PackageParser.Package scannedPkg) { 5343 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5344 return PackageManager.SIGNATURE_NO_MATCH; 5345 } 5346 5347 String msg = null; 5348 try { 5349 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5350 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5351 + scannedPkg.packageName); 5352 return PackageManager.SIGNATURE_MATCH; 5353 } 5354 } catch (CertificateException e) { 5355 msg = e.getMessage(); 5356 } 5357 5358 logCriticalInfo(Log.INFO, 5359 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5360 return PackageManager.SIGNATURE_NO_MATCH; 5361 } 5362 5363 @Override 5364 public List<String> getAllPackages() { 5365 synchronized (mPackages) { 5366 return new ArrayList<String>(mPackages.keySet()); 5367 } 5368 } 5369 5370 @Override 5371 public String[] getPackagesForUid(int uid) { 5372 final int userId = UserHandle.getUserId(uid); 5373 uid = UserHandle.getAppId(uid); 5374 // reader 5375 synchronized (mPackages) { 5376 Object obj = mSettings.getUserIdLPr(uid); 5377 if (obj instanceof SharedUserSetting) { 5378 final SharedUserSetting sus = (SharedUserSetting) obj; 5379 final int N = sus.packages.size(); 5380 String[] res = new String[N]; 5381 final Iterator<PackageSetting> it = sus.packages.iterator(); 5382 int i = 0; 5383 while (it.hasNext()) { 5384 PackageSetting ps = it.next(); 5385 if (ps.getInstalled(userId)) { 5386 res[i++] = ps.name; 5387 } else { 5388 res = ArrayUtils.removeElement(String.class, res, res[i]); 5389 } 5390 } 5391 return res; 5392 } else if (obj instanceof PackageSetting) { 5393 final PackageSetting ps = (PackageSetting) obj; 5394 if (ps.getInstalled(userId)) { 5395 return new String[]{ps.name}; 5396 } 5397 } 5398 } 5399 return null; 5400 } 5401 5402 @Override 5403 public String getNameForUid(int uid) { 5404 // reader 5405 synchronized (mPackages) { 5406 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5407 if (obj instanceof SharedUserSetting) { 5408 final SharedUserSetting sus = (SharedUserSetting) obj; 5409 return sus.name + ":" + sus.userId; 5410 } else if (obj instanceof PackageSetting) { 5411 final PackageSetting ps = (PackageSetting) obj; 5412 return ps.name; 5413 } 5414 } 5415 return null; 5416 } 5417 5418 @Override 5419 public int getUidForSharedUser(String sharedUserName) { 5420 if(sharedUserName == null) { 5421 return -1; 5422 } 5423 // reader 5424 synchronized (mPackages) { 5425 SharedUserSetting suid; 5426 try { 5427 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5428 if (suid != null) { 5429 return suid.userId; 5430 } 5431 } catch (PackageManagerException ignore) { 5432 // can't happen, but, still need to catch it 5433 } 5434 return -1; 5435 } 5436 } 5437 5438 @Override 5439 public int getFlagsForUid(int uid) { 5440 synchronized (mPackages) { 5441 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5442 if (obj instanceof SharedUserSetting) { 5443 final SharedUserSetting sus = (SharedUserSetting) obj; 5444 return sus.pkgFlags; 5445 } else if (obj instanceof PackageSetting) { 5446 final PackageSetting ps = (PackageSetting) obj; 5447 return ps.pkgFlags; 5448 } 5449 } 5450 return 0; 5451 } 5452 5453 @Override 5454 public int getPrivateFlagsForUid(int uid) { 5455 synchronized (mPackages) { 5456 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5457 if (obj instanceof SharedUserSetting) { 5458 final SharedUserSetting sus = (SharedUserSetting) obj; 5459 return sus.pkgPrivateFlags; 5460 } else if (obj instanceof PackageSetting) { 5461 final PackageSetting ps = (PackageSetting) obj; 5462 return ps.pkgPrivateFlags; 5463 } 5464 } 5465 return 0; 5466 } 5467 5468 @Override 5469 public boolean isUidPrivileged(int uid) { 5470 uid = UserHandle.getAppId(uid); 5471 // reader 5472 synchronized (mPackages) { 5473 Object obj = mSettings.getUserIdLPr(uid); 5474 if (obj instanceof SharedUserSetting) { 5475 final SharedUserSetting sus = (SharedUserSetting) obj; 5476 final Iterator<PackageSetting> it = sus.packages.iterator(); 5477 while (it.hasNext()) { 5478 if (it.next().isPrivileged()) { 5479 return true; 5480 } 5481 } 5482 } else if (obj instanceof PackageSetting) { 5483 final PackageSetting ps = (PackageSetting) obj; 5484 return ps.isPrivileged(); 5485 } 5486 } 5487 return false; 5488 } 5489 5490 @Override 5491 public String[] getAppOpPermissionPackages(String permissionName) { 5492 synchronized (mPackages) { 5493 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5494 if (pkgs == null) { 5495 return null; 5496 } 5497 return pkgs.toArray(new String[pkgs.size()]); 5498 } 5499 } 5500 5501 @Override 5502 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5503 int flags, int userId) { 5504 try { 5505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5506 5507 if (!sUserManager.exists(userId)) return null; 5508 flags = updateFlagsForResolve(flags, userId, intent); 5509 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5510 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5511 5512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5513 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5514 flags, userId); 5515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5516 5517 final ResolveInfo bestChoice = 5518 chooseBestActivity(intent, resolvedType, flags, query, userId); 5519 return bestChoice; 5520 } finally { 5521 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5522 } 5523 } 5524 5525 @Override 5526 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5527 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5528 throw new SecurityException( 5529 "findPersistentPreferredActivity can only be run by the system"); 5530 } 5531 if (!sUserManager.exists(userId)) { 5532 return null; 5533 } 5534 intent = updateIntentForResolve(intent); 5535 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5536 final int flags = updateFlagsForResolve(0, userId, intent); 5537 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5538 userId); 5539 synchronized (mPackages) { 5540 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5541 userId); 5542 } 5543 } 5544 5545 @Override 5546 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5547 IntentFilter filter, int match, ComponentName activity) { 5548 final int userId = UserHandle.getCallingUserId(); 5549 if (DEBUG_PREFERRED) { 5550 Log.v(TAG, "setLastChosenActivity intent=" + intent 5551 + " resolvedType=" + resolvedType 5552 + " flags=" + flags 5553 + " filter=" + filter 5554 + " match=" + match 5555 + " activity=" + activity); 5556 filter.dump(new PrintStreamPrinter(System.out), " "); 5557 } 5558 intent.setComponent(null); 5559 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5560 userId); 5561 // Find any earlier preferred or last chosen entries and nuke them 5562 findPreferredActivity(intent, resolvedType, 5563 flags, query, 0, false, true, false, userId); 5564 // Add the new activity as the last chosen for this filter 5565 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5566 "Setting last chosen"); 5567 } 5568 5569 @Override 5570 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5571 final int userId = UserHandle.getCallingUserId(); 5572 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5573 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5574 userId); 5575 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5576 false, false, false, userId); 5577 } 5578 5579 private boolean isEphemeralDisabled() { 5580 // ephemeral apps have been disabled across the board 5581 if (DISABLE_EPHEMERAL_APPS) { 5582 return true; 5583 } 5584 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5585 if (!mSystemReady) { 5586 return true; 5587 } 5588 // we can't get a content resolver until the system is ready; these checks must happen last 5589 final ContentResolver resolver = mContext.getContentResolver(); 5590 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5591 return true; 5592 } 5593 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5594 } 5595 5596 private boolean isEphemeralAllowed( 5597 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5598 boolean skipPackageCheck) { 5599 // Short circuit and return early if possible. 5600 if (isEphemeralDisabled()) { 5601 return false; 5602 } 5603 final int callingUser = UserHandle.getCallingUserId(); 5604 if (callingUser != UserHandle.USER_SYSTEM) { 5605 return false; 5606 } 5607 if (mInstantAppResolverConnection == null) { 5608 return false; 5609 } 5610 if (mInstantAppInstallerComponent == null) { 5611 return false; 5612 } 5613 if (intent.getComponent() != null) { 5614 return false; 5615 } 5616 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5617 return false; 5618 } 5619 if (!skipPackageCheck && intent.getPackage() != null) { 5620 return false; 5621 } 5622 final boolean isWebUri = hasWebURI(intent); 5623 if (!isWebUri || intent.getData().getHost() == null) { 5624 return false; 5625 } 5626 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5627 // Or if there's already an ephemeral app installed that handles the action 5628 synchronized (mPackages) { 5629 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5630 for (int n = 0; n < count; n++) { 5631 ResolveInfo info = resolvedActivities.get(n); 5632 String packageName = info.activityInfo.packageName; 5633 PackageSetting ps = mSettings.mPackages.get(packageName); 5634 if (ps != null) { 5635 // Try to get the status from User settings first 5636 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5637 int status = (int) (packedStatus >> 32); 5638 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5639 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5640 if (DEBUG_EPHEMERAL) { 5641 Slog.v(TAG, "DENY ephemeral apps;" 5642 + " pkg: " + packageName + ", status: " + status); 5643 } 5644 return false; 5645 } 5646 if (ps.getInstantApp(userId)) { 5647 return false; 5648 } 5649 } 5650 } 5651 } 5652 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5653 return true; 5654 } 5655 5656 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5657 Intent origIntent, String resolvedType, String callingPackage, 5658 int userId) { 5659 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5660 new EphemeralRequest(responseObj, origIntent, resolvedType, 5661 callingPackage, userId)); 5662 mHandler.sendMessage(msg); 5663 } 5664 5665 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5666 int flags, List<ResolveInfo> query, int userId) { 5667 if (query != null) { 5668 final int N = query.size(); 5669 if (N == 1) { 5670 return query.get(0); 5671 } else if (N > 1) { 5672 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5673 // If there is more than one activity with the same priority, 5674 // then let the user decide between them. 5675 ResolveInfo r0 = query.get(0); 5676 ResolveInfo r1 = query.get(1); 5677 if (DEBUG_INTENT_MATCHING || debug) { 5678 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5679 + r1.activityInfo.name + "=" + r1.priority); 5680 } 5681 // If the first activity has a higher priority, or a different 5682 // default, then it is always desirable to pick it. 5683 if (r0.priority != r1.priority 5684 || r0.preferredOrder != r1.preferredOrder 5685 || r0.isDefault != r1.isDefault) { 5686 return query.get(0); 5687 } 5688 // If we have saved a preference for a preferred activity for 5689 // this Intent, use that. 5690 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5691 flags, query, r0.priority, true, false, debug, userId); 5692 if (ri != null) { 5693 return ri; 5694 } 5695 ri = new ResolveInfo(mResolveInfo); 5696 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5697 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5698 // If all of the options come from the same package, show the application's 5699 // label and icon instead of the generic resolver's. 5700 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5701 // and then throw away the ResolveInfo itself, meaning that the caller loses 5702 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5703 // a fallback for this case; we only set the target package's resources on 5704 // the ResolveInfo, not the ActivityInfo. 5705 final String intentPackage = intent.getPackage(); 5706 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5707 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5708 ri.resolvePackageName = intentPackage; 5709 if (userNeedsBadging(userId)) { 5710 ri.noResourceId = true; 5711 } else { 5712 ri.icon = appi.icon; 5713 } 5714 ri.iconResourceId = appi.icon; 5715 ri.labelRes = appi.labelRes; 5716 } 5717 ri.activityInfo.applicationInfo = new ApplicationInfo( 5718 ri.activityInfo.applicationInfo); 5719 if (userId != 0) { 5720 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5721 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5722 } 5723 // Make sure that the resolver is displayable in car mode 5724 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5725 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5726 return ri; 5727 } 5728 } 5729 return null; 5730 } 5731 5732 /** 5733 * Return true if the given list is not empty and all of its contents have 5734 * an activityInfo with the given package name. 5735 */ 5736 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5737 if (ArrayUtils.isEmpty(list)) { 5738 return false; 5739 } 5740 for (int i = 0, N = list.size(); i < N; i++) { 5741 final ResolveInfo ri = list.get(i); 5742 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5743 if (ai == null || !packageName.equals(ai.packageName)) { 5744 return false; 5745 } 5746 } 5747 return true; 5748 } 5749 5750 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5751 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5752 final int N = query.size(); 5753 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5754 .get(userId); 5755 // Get the list of persistent preferred activities that handle the intent 5756 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5757 List<PersistentPreferredActivity> pprefs = ppir != null 5758 ? ppir.queryIntent(intent, resolvedType, 5759 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5760 userId) 5761 : null; 5762 if (pprefs != null && pprefs.size() > 0) { 5763 final int M = pprefs.size(); 5764 for (int i=0; i<M; i++) { 5765 final PersistentPreferredActivity ppa = pprefs.get(i); 5766 if (DEBUG_PREFERRED || debug) { 5767 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5768 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5769 + "\n component=" + ppa.mComponent); 5770 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5771 } 5772 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5773 flags | MATCH_DISABLED_COMPONENTS, userId); 5774 if (DEBUG_PREFERRED || debug) { 5775 Slog.v(TAG, "Found persistent preferred activity:"); 5776 if (ai != null) { 5777 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5778 } else { 5779 Slog.v(TAG, " null"); 5780 } 5781 } 5782 if (ai == null) { 5783 // This previously registered persistent preferred activity 5784 // component is no longer known. Ignore it and do NOT remove it. 5785 continue; 5786 } 5787 for (int j=0; j<N; j++) { 5788 final ResolveInfo ri = query.get(j); 5789 if (!ri.activityInfo.applicationInfo.packageName 5790 .equals(ai.applicationInfo.packageName)) { 5791 continue; 5792 } 5793 if (!ri.activityInfo.name.equals(ai.name)) { 5794 continue; 5795 } 5796 // Found a persistent preference that can handle the intent. 5797 if (DEBUG_PREFERRED || debug) { 5798 Slog.v(TAG, "Returning persistent preferred activity: " + 5799 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5800 } 5801 return ri; 5802 } 5803 } 5804 } 5805 return null; 5806 } 5807 5808 // TODO: handle preferred activities missing while user has amnesia 5809 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5810 List<ResolveInfo> query, int priority, boolean always, 5811 boolean removeMatches, boolean debug, int userId) { 5812 if (!sUserManager.exists(userId)) return null; 5813 flags = updateFlagsForResolve(flags, userId, intent); 5814 intent = updateIntentForResolve(intent); 5815 // writer 5816 synchronized (mPackages) { 5817 // Try to find a matching persistent preferred activity. 5818 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5819 debug, userId); 5820 5821 // If a persistent preferred activity matched, use it. 5822 if (pri != null) { 5823 return pri; 5824 } 5825 5826 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5827 // Get the list of preferred activities that handle the intent 5828 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5829 List<PreferredActivity> prefs = pir != null 5830 ? pir.queryIntent(intent, resolvedType, 5831 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5832 userId) 5833 : null; 5834 if (prefs != null && prefs.size() > 0) { 5835 boolean changed = false; 5836 try { 5837 // First figure out how good the original match set is. 5838 // We will only allow preferred activities that came 5839 // from the same match quality. 5840 int match = 0; 5841 5842 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5843 5844 final int N = query.size(); 5845 for (int j=0; j<N; j++) { 5846 final ResolveInfo ri = query.get(j); 5847 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5848 + ": 0x" + Integer.toHexString(match)); 5849 if (ri.match > match) { 5850 match = ri.match; 5851 } 5852 } 5853 5854 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5855 + Integer.toHexString(match)); 5856 5857 match &= IntentFilter.MATCH_CATEGORY_MASK; 5858 final int M = prefs.size(); 5859 for (int i=0; i<M; i++) { 5860 final PreferredActivity pa = prefs.get(i); 5861 if (DEBUG_PREFERRED || debug) { 5862 Slog.v(TAG, "Checking PreferredActivity ds=" 5863 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5864 + "\n component=" + pa.mPref.mComponent); 5865 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5866 } 5867 if (pa.mPref.mMatch != match) { 5868 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5869 + Integer.toHexString(pa.mPref.mMatch)); 5870 continue; 5871 } 5872 // If it's not an "always" type preferred activity and that's what we're 5873 // looking for, skip it. 5874 if (always && !pa.mPref.mAlways) { 5875 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5876 continue; 5877 } 5878 final ActivityInfo ai = getActivityInfo( 5879 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5880 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5881 userId); 5882 if (DEBUG_PREFERRED || debug) { 5883 Slog.v(TAG, "Found preferred activity:"); 5884 if (ai != null) { 5885 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5886 } else { 5887 Slog.v(TAG, " null"); 5888 } 5889 } 5890 if (ai == null) { 5891 // This previously registered preferred activity 5892 // component is no longer known. Most likely an update 5893 // to the app was installed and in the new version this 5894 // component no longer exists. Clean it up by removing 5895 // it from the preferred activities list, and skip it. 5896 Slog.w(TAG, "Removing dangling preferred activity: " 5897 + pa.mPref.mComponent); 5898 pir.removeFilter(pa); 5899 changed = true; 5900 continue; 5901 } 5902 for (int j=0; j<N; j++) { 5903 final ResolveInfo ri = query.get(j); 5904 if (!ri.activityInfo.applicationInfo.packageName 5905 .equals(ai.applicationInfo.packageName)) { 5906 continue; 5907 } 5908 if (!ri.activityInfo.name.equals(ai.name)) { 5909 continue; 5910 } 5911 5912 if (removeMatches) { 5913 pir.removeFilter(pa); 5914 changed = true; 5915 if (DEBUG_PREFERRED) { 5916 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5917 } 5918 break; 5919 } 5920 5921 // Okay we found a previously set preferred or last chosen app. 5922 // If the result set is different from when this 5923 // was created, we need to clear it and re-ask the 5924 // user their preference, if we're looking for an "always" type entry. 5925 if (always && !pa.mPref.sameSet(query)) { 5926 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5927 + intent + " type " + resolvedType); 5928 if (DEBUG_PREFERRED) { 5929 Slog.v(TAG, "Removing preferred activity since set changed " 5930 + pa.mPref.mComponent); 5931 } 5932 pir.removeFilter(pa); 5933 // Re-add the filter as a "last chosen" entry (!always) 5934 PreferredActivity lastChosen = new PreferredActivity( 5935 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5936 pir.addFilter(lastChosen); 5937 changed = true; 5938 return null; 5939 } 5940 5941 // Yay! Either the set matched or we're looking for the last chosen 5942 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5943 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5944 return ri; 5945 } 5946 } 5947 } finally { 5948 if (changed) { 5949 if (DEBUG_PREFERRED) { 5950 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5951 } 5952 scheduleWritePackageRestrictionsLocked(userId); 5953 } 5954 } 5955 } 5956 } 5957 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5958 return null; 5959 } 5960 5961 /* 5962 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5963 */ 5964 @Override 5965 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5966 int targetUserId) { 5967 mContext.enforceCallingOrSelfPermission( 5968 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5969 List<CrossProfileIntentFilter> matches = 5970 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5971 if (matches != null) { 5972 int size = matches.size(); 5973 for (int i = 0; i < size; i++) { 5974 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5975 } 5976 } 5977 if (hasWebURI(intent)) { 5978 // cross-profile app linking works only towards the parent. 5979 final UserInfo parent = getProfileParent(sourceUserId); 5980 synchronized(mPackages) { 5981 int flags = updateFlagsForResolve(0, parent.id, intent); 5982 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5983 intent, resolvedType, flags, sourceUserId, parent.id); 5984 return xpDomainInfo != null; 5985 } 5986 } 5987 return false; 5988 } 5989 5990 private UserInfo getProfileParent(int userId) { 5991 final long identity = Binder.clearCallingIdentity(); 5992 try { 5993 return sUserManager.getProfileParent(userId); 5994 } finally { 5995 Binder.restoreCallingIdentity(identity); 5996 } 5997 } 5998 5999 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6000 String resolvedType, int userId) { 6001 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6002 if (resolver != null) { 6003 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6004 } 6005 return null; 6006 } 6007 6008 @Override 6009 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6010 String resolvedType, int flags, int userId) { 6011 try { 6012 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6013 6014 return new ParceledListSlice<>( 6015 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6016 } finally { 6017 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6018 } 6019 } 6020 6021 /** 6022 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6023 * instant, returns {@code null}. 6024 */ 6025 private String getInstantAppPackageName(int callingUid) { 6026 final int appId = UserHandle.getAppId(callingUid); 6027 synchronized (mPackages) { 6028 final Object obj = mSettings.getUserIdLPr(appId); 6029 if (obj instanceof PackageSetting) { 6030 final PackageSetting ps = (PackageSetting) obj; 6031 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6032 return isInstantApp ? ps.pkg.packageName : null; 6033 } 6034 } 6035 return null; 6036 } 6037 6038 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6039 String resolvedType, int flags, int userId) { 6040 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6041 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6042 flags = updateFlagsForResolve(flags, userId, intent); 6043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6044 false /* requireFullPermission */, false /* checkShell */, 6045 "query intent activities"); 6046 ComponentName comp = intent.getComponent(); 6047 if (comp == null) { 6048 if (intent.getSelector() != null) { 6049 intent = intent.getSelector(); 6050 comp = intent.getComponent(); 6051 } 6052 } 6053 6054 if (comp != null) { 6055 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6056 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6057 if (ai != null) { 6058 // When specifying an explicit component, we prevent the activity from being 6059 // used when either 1) the calling package is normal and the activity is within 6060 // an ephemeral application or 2) the calling package is ephemeral and the 6061 // activity is not visible to ephemeral applications. 6062 final boolean matchInstantApp = 6063 (flags & PackageManager.MATCH_INSTANT) != 0; 6064 final boolean matchVisibleToInstantAppOnly = 6065 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6066 final boolean isCallerInstantApp = 6067 instantAppPkgName != null; 6068 final boolean isTargetSameInstantApp = 6069 comp.getPackageName().equals(instantAppPkgName); 6070 final boolean isTargetInstantApp = 6071 (ai.applicationInfo.privateFlags 6072 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6073 final boolean isTargetHiddenFromInstantApp = 6074 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6075 final boolean blockResolution = 6076 !isTargetSameInstantApp 6077 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6078 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6079 && isTargetHiddenFromInstantApp)); 6080 if (!blockResolution) { 6081 final ResolveInfo ri = new ResolveInfo(); 6082 ri.activityInfo = ai; 6083 list.add(ri); 6084 } 6085 } 6086 return applyPostResolutionFilter(list, instantAppPkgName); 6087 } 6088 6089 // reader 6090 boolean sortResult = false; 6091 boolean addEphemeral = false; 6092 List<ResolveInfo> result; 6093 final String pkgName = intent.getPackage(); 6094 synchronized (mPackages) { 6095 if (pkgName == null) { 6096 List<CrossProfileIntentFilter> matchingFilters = 6097 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6098 // Check for results that need to skip the current profile. 6099 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6100 resolvedType, flags, userId); 6101 if (xpResolveInfo != null) { 6102 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6103 xpResult.add(xpResolveInfo); 6104 return applyPostResolutionFilter( 6105 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6106 } 6107 6108 // Check for results in the current profile. 6109 result = filterIfNotSystemUser(mActivities.queryIntent( 6110 intent, resolvedType, flags, userId), userId); 6111 addEphemeral = 6112 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6113 6114 // Check for cross profile results. 6115 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6116 xpResolveInfo = queryCrossProfileIntents( 6117 matchingFilters, intent, resolvedType, flags, userId, 6118 hasNonNegativePriorityResult); 6119 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6120 boolean isVisibleToUser = filterIfNotSystemUser( 6121 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6122 if (isVisibleToUser) { 6123 result.add(xpResolveInfo); 6124 sortResult = true; 6125 } 6126 } 6127 if (hasWebURI(intent)) { 6128 CrossProfileDomainInfo xpDomainInfo = null; 6129 final UserInfo parent = getProfileParent(userId); 6130 if (parent != null) { 6131 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6132 flags, userId, parent.id); 6133 } 6134 if (xpDomainInfo != null) { 6135 if (xpResolveInfo != null) { 6136 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6137 // in the result. 6138 result.remove(xpResolveInfo); 6139 } 6140 if (result.size() == 0 && !addEphemeral) { 6141 // No result in current profile, but found candidate in parent user. 6142 // And we are not going to add emphemeral app, so we can return the 6143 // result straight away. 6144 result.add(xpDomainInfo.resolveInfo); 6145 return applyPostResolutionFilter(result, instantAppPkgName); 6146 } 6147 } else if (result.size() <= 1 && !addEphemeral) { 6148 // No result in parent user and <= 1 result in current profile, and we 6149 // are not going to add emphemeral app, so we can return the result without 6150 // further processing. 6151 return applyPostResolutionFilter(result, instantAppPkgName); 6152 } 6153 // We have more than one candidate (combining results from current and parent 6154 // profile), so we need filtering and sorting. 6155 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6156 intent, flags, result, xpDomainInfo, userId); 6157 sortResult = true; 6158 } 6159 } else { 6160 final PackageParser.Package pkg = mPackages.get(pkgName); 6161 if (pkg != null) { 6162 result = applyPostResolutionFilter(filterIfNotSystemUser( 6163 mActivities.queryIntentForPackage( 6164 intent, resolvedType, flags, pkg.activities, userId), 6165 userId), instantAppPkgName); 6166 } else { 6167 // the caller wants to resolve for a particular package; however, there 6168 // were no installed results, so, try to find an ephemeral result 6169 addEphemeral = isEphemeralAllowed( 6170 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6171 result = new ArrayList<ResolveInfo>(); 6172 } 6173 } 6174 } 6175 if (addEphemeral) { 6176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6177 final EphemeralRequest requestObject = new EphemeralRequest( 6178 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6179 null /*callingPackage*/, userId); 6180 final AuxiliaryResolveInfo auxiliaryResponse = 6181 EphemeralResolver.doEphemeralResolutionPhaseOne( 6182 mContext, mInstantAppResolverConnection, requestObject); 6183 if (auxiliaryResponse != null) { 6184 if (DEBUG_EPHEMERAL) { 6185 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6186 } 6187 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6188 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6189 // make sure this resolver is the default 6190 ephemeralInstaller.isDefault = true; 6191 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6192 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6193 // add a non-generic filter 6194 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6195 ephemeralInstaller.filter.addDataPath( 6196 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6197 result.add(ephemeralInstaller); 6198 } 6199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6200 } 6201 if (sortResult) { 6202 Collections.sort(result, mResolvePrioritySorter); 6203 } 6204 return applyPostResolutionFilter(result, instantAppPkgName); 6205 } 6206 6207 private static class CrossProfileDomainInfo { 6208 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6209 ResolveInfo resolveInfo; 6210 /* Best domain verification status of the activities found in the other profile */ 6211 int bestDomainVerificationStatus; 6212 } 6213 6214 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6215 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6216 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6217 sourceUserId)) { 6218 return null; 6219 } 6220 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6221 resolvedType, flags, parentUserId); 6222 6223 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6224 return null; 6225 } 6226 CrossProfileDomainInfo result = null; 6227 int size = resultTargetUser.size(); 6228 for (int i = 0; i < size; i++) { 6229 ResolveInfo riTargetUser = resultTargetUser.get(i); 6230 // Intent filter verification is only for filters that specify a host. So don't return 6231 // those that handle all web uris. 6232 if (riTargetUser.handleAllWebDataURI) { 6233 continue; 6234 } 6235 String packageName = riTargetUser.activityInfo.packageName; 6236 PackageSetting ps = mSettings.mPackages.get(packageName); 6237 if (ps == null) { 6238 continue; 6239 } 6240 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6241 int status = (int)(verificationState >> 32); 6242 if (result == null) { 6243 result = new CrossProfileDomainInfo(); 6244 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6245 sourceUserId, parentUserId); 6246 result.bestDomainVerificationStatus = status; 6247 } else { 6248 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6249 result.bestDomainVerificationStatus); 6250 } 6251 } 6252 // Don't consider matches with status NEVER across profiles. 6253 if (result != null && result.bestDomainVerificationStatus 6254 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6255 return null; 6256 } 6257 return result; 6258 } 6259 6260 /** 6261 * Verification statuses are ordered from the worse to the best, except for 6262 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6263 */ 6264 private int bestDomainVerificationStatus(int status1, int status2) { 6265 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6266 return status2; 6267 } 6268 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6269 return status1; 6270 } 6271 return (int) MathUtils.max(status1, status2); 6272 } 6273 6274 private boolean isUserEnabled(int userId) { 6275 long callingId = Binder.clearCallingIdentity(); 6276 try { 6277 UserInfo userInfo = sUserManager.getUserInfo(userId); 6278 return userInfo != null && userInfo.isEnabled(); 6279 } finally { 6280 Binder.restoreCallingIdentity(callingId); 6281 } 6282 } 6283 6284 /** 6285 * Filter out activities with systemUserOnly flag set, when current user is not System. 6286 * 6287 * @return filtered list 6288 */ 6289 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6290 if (userId == UserHandle.USER_SYSTEM) { 6291 return resolveInfos; 6292 } 6293 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6294 ResolveInfo info = resolveInfos.get(i); 6295 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6296 resolveInfos.remove(i); 6297 } 6298 } 6299 return resolveInfos; 6300 } 6301 6302 /** 6303 * Filters out ephemeral activities. 6304 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6305 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6306 * 6307 * @param resolveInfos The pre-filtered list of resolved activities 6308 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6309 * is performed. 6310 * @return A filtered list of resolved activities. 6311 */ 6312 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6313 String ephemeralPkgName) { 6314 // TODO: When adding on-demand split support for non-instant apps, remove this check 6315 // and always apply post filtering 6316 if (ephemeralPkgName == null) { 6317 return resolveInfos; 6318 } 6319 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6320 final ResolveInfo info = resolveInfos.get(i); 6321 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6322 // allow activities that are defined in the provided package 6323 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6324 if (info.activityInfo.splitName != null 6325 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6326 info.activityInfo.splitName)) { 6327 // requested activity is defined in a split that hasn't been installed yet. 6328 // add the installer to the resolve list 6329 if (DEBUG_EPHEMERAL) { 6330 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6331 } 6332 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6333 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6334 info.activityInfo.packageName, info.activityInfo.splitName, 6335 info.activityInfo.applicationInfo.versionCode); 6336 // make sure this resolver is the default 6337 installerInfo.isDefault = true; 6338 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6339 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6340 // add a non-generic filter 6341 installerInfo.filter = new IntentFilter(); 6342 // load resources from the correct package 6343 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6344 resolveInfos.set(i, installerInfo); 6345 } 6346 continue; 6347 } 6348 // allow activities that have been explicitly exposed to ephemeral apps 6349 if (!isEphemeralApp 6350 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6351 continue; 6352 } 6353 resolveInfos.remove(i); 6354 } 6355 return resolveInfos; 6356 } 6357 6358 /** 6359 * @param resolveInfos list of resolve infos in descending priority order 6360 * @return if the list contains a resolve info with non-negative priority 6361 */ 6362 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6363 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6364 } 6365 6366 private static boolean hasWebURI(Intent intent) { 6367 if (intent.getData() == null) { 6368 return false; 6369 } 6370 final String scheme = intent.getScheme(); 6371 if (TextUtils.isEmpty(scheme)) { 6372 return false; 6373 } 6374 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6375 } 6376 6377 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6378 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6379 int userId) { 6380 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6381 6382 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6383 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6384 candidates.size()); 6385 } 6386 6387 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6388 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6389 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6390 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6391 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6392 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6393 6394 synchronized (mPackages) { 6395 final int count = candidates.size(); 6396 // First, try to use linked apps. Partition the candidates into four lists: 6397 // one for the final results, one for the "do not use ever", one for "undefined status" 6398 // and finally one for "browser app type". 6399 for (int n=0; n<count; n++) { 6400 ResolveInfo info = candidates.get(n); 6401 String packageName = info.activityInfo.packageName; 6402 PackageSetting ps = mSettings.mPackages.get(packageName); 6403 if (ps != null) { 6404 // Add to the special match all list (Browser use case) 6405 if (info.handleAllWebDataURI) { 6406 matchAllList.add(info); 6407 continue; 6408 } 6409 // Try to get the status from User settings first 6410 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6411 int status = (int)(packedStatus >> 32); 6412 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6413 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6414 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6415 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6416 + " : linkgen=" + linkGeneration); 6417 } 6418 // Use link-enabled generation as preferredOrder, i.e. 6419 // prefer newly-enabled over earlier-enabled. 6420 info.preferredOrder = linkGeneration; 6421 alwaysList.add(info); 6422 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6423 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6424 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6425 } 6426 neverList.add(info); 6427 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6428 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6429 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6430 } 6431 alwaysAskList.add(info); 6432 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6433 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6434 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6435 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6436 } 6437 undefinedList.add(info); 6438 } 6439 } 6440 } 6441 6442 // We'll want to include browser possibilities in a few cases 6443 boolean includeBrowser = false; 6444 6445 // First try to add the "always" resolution(s) for the current user, if any 6446 if (alwaysList.size() > 0) { 6447 result.addAll(alwaysList); 6448 } else { 6449 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6450 result.addAll(undefinedList); 6451 // Maybe add one for the other profile. 6452 if (xpDomainInfo != null && ( 6453 xpDomainInfo.bestDomainVerificationStatus 6454 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6455 result.add(xpDomainInfo.resolveInfo); 6456 } 6457 includeBrowser = true; 6458 } 6459 6460 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6461 // If there were 'always' entries their preferred order has been set, so we also 6462 // back that off to make the alternatives equivalent 6463 if (alwaysAskList.size() > 0) { 6464 for (ResolveInfo i : result) { 6465 i.preferredOrder = 0; 6466 } 6467 result.addAll(alwaysAskList); 6468 includeBrowser = true; 6469 } 6470 6471 if (includeBrowser) { 6472 // Also add browsers (all of them or only the default one) 6473 if (DEBUG_DOMAIN_VERIFICATION) { 6474 Slog.v(TAG, " ...including browsers in candidate set"); 6475 } 6476 if ((matchFlags & MATCH_ALL) != 0) { 6477 result.addAll(matchAllList); 6478 } else { 6479 // Browser/generic handling case. If there's a default browser, go straight 6480 // to that (but only if there is no other higher-priority match). 6481 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6482 int maxMatchPrio = 0; 6483 ResolveInfo defaultBrowserMatch = null; 6484 final int numCandidates = matchAllList.size(); 6485 for (int n = 0; n < numCandidates; n++) { 6486 ResolveInfo info = matchAllList.get(n); 6487 // track the highest overall match priority... 6488 if (info.priority > maxMatchPrio) { 6489 maxMatchPrio = info.priority; 6490 } 6491 // ...and the highest-priority default browser match 6492 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6493 if (defaultBrowserMatch == null 6494 || (defaultBrowserMatch.priority < info.priority)) { 6495 if (debug) { 6496 Slog.v(TAG, "Considering default browser match " + info); 6497 } 6498 defaultBrowserMatch = info; 6499 } 6500 } 6501 } 6502 if (defaultBrowserMatch != null 6503 && defaultBrowserMatch.priority >= maxMatchPrio 6504 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6505 { 6506 if (debug) { 6507 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6508 } 6509 result.add(defaultBrowserMatch); 6510 } else { 6511 result.addAll(matchAllList); 6512 } 6513 } 6514 6515 // If there is nothing selected, add all candidates and remove the ones that the user 6516 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6517 if (result.size() == 0) { 6518 result.addAll(candidates); 6519 result.removeAll(neverList); 6520 } 6521 } 6522 } 6523 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6524 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6525 result.size()); 6526 for (ResolveInfo info : result) { 6527 Slog.v(TAG, " + " + info.activityInfo); 6528 } 6529 } 6530 return result; 6531 } 6532 6533 // Returns a packed value as a long: 6534 // 6535 // high 'int'-sized word: link status: undefined/ask/never/always. 6536 // low 'int'-sized word: relative priority among 'always' results. 6537 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6538 long result = ps.getDomainVerificationStatusForUser(userId); 6539 // if none available, get the master status 6540 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6541 if (ps.getIntentFilterVerificationInfo() != null) { 6542 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6543 } 6544 } 6545 return result; 6546 } 6547 6548 private ResolveInfo querySkipCurrentProfileIntents( 6549 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6550 int flags, int sourceUserId) { 6551 if (matchingFilters != null) { 6552 int size = matchingFilters.size(); 6553 for (int i = 0; i < size; i ++) { 6554 CrossProfileIntentFilter filter = matchingFilters.get(i); 6555 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6556 // Checking if there are activities in the target user that can handle the 6557 // intent. 6558 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6559 resolvedType, flags, sourceUserId); 6560 if (resolveInfo != null) { 6561 return resolveInfo; 6562 } 6563 } 6564 } 6565 } 6566 return null; 6567 } 6568 6569 // Return matching ResolveInfo in target user if any. 6570 private ResolveInfo queryCrossProfileIntents( 6571 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6572 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6573 if (matchingFilters != null) { 6574 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6575 // match the same intent. For performance reasons, it is better not to 6576 // run queryIntent twice for the same userId 6577 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6578 int size = matchingFilters.size(); 6579 for (int i = 0; i < size; i++) { 6580 CrossProfileIntentFilter filter = matchingFilters.get(i); 6581 int targetUserId = filter.getTargetUserId(); 6582 boolean skipCurrentProfile = 6583 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6584 boolean skipCurrentProfileIfNoMatchFound = 6585 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6586 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6587 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6588 // Checking if there are activities in the target user that can handle the 6589 // intent. 6590 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6591 resolvedType, flags, sourceUserId); 6592 if (resolveInfo != null) return resolveInfo; 6593 alreadyTriedUserIds.put(targetUserId, true); 6594 } 6595 } 6596 } 6597 return null; 6598 } 6599 6600 /** 6601 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6602 * will forward the intent to the filter's target user. 6603 * Otherwise, returns null. 6604 */ 6605 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6606 String resolvedType, int flags, int sourceUserId) { 6607 int targetUserId = filter.getTargetUserId(); 6608 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6609 resolvedType, flags, targetUserId); 6610 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6611 // If all the matches in the target profile are suspended, return null. 6612 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6613 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6614 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6615 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6616 targetUserId); 6617 } 6618 } 6619 } 6620 return null; 6621 } 6622 6623 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6624 int sourceUserId, int targetUserId) { 6625 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6626 long ident = Binder.clearCallingIdentity(); 6627 boolean targetIsProfile; 6628 try { 6629 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6630 } finally { 6631 Binder.restoreCallingIdentity(ident); 6632 } 6633 String className; 6634 if (targetIsProfile) { 6635 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6636 } else { 6637 className = FORWARD_INTENT_TO_PARENT; 6638 } 6639 ComponentName forwardingActivityComponentName = new ComponentName( 6640 mAndroidApplication.packageName, className); 6641 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6642 sourceUserId); 6643 if (!targetIsProfile) { 6644 forwardingActivityInfo.showUserIcon = targetUserId; 6645 forwardingResolveInfo.noResourceId = true; 6646 } 6647 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6648 forwardingResolveInfo.priority = 0; 6649 forwardingResolveInfo.preferredOrder = 0; 6650 forwardingResolveInfo.match = 0; 6651 forwardingResolveInfo.isDefault = true; 6652 forwardingResolveInfo.filter = filter; 6653 forwardingResolveInfo.targetUserId = targetUserId; 6654 return forwardingResolveInfo; 6655 } 6656 6657 @Override 6658 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6659 Intent[] specifics, String[] specificTypes, Intent intent, 6660 String resolvedType, int flags, int userId) { 6661 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6662 specificTypes, intent, resolvedType, flags, userId)); 6663 } 6664 6665 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6666 Intent[] specifics, String[] specificTypes, Intent intent, 6667 String resolvedType, int flags, int userId) { 6668 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6669 flags = updateFlagsForResolve(flags, userId, intent); 6670 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6671 false /* requireFullPermission */, false /* checkShell */, 6672 "query intent activity options"); 6673 final String resultsAction = intent.getAction(); 6674 6675 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6676 | PackageManager.GET_RESOLVED_FILTER, userId); 6677 6678 if (DEBUG_INTENT_MATCHING) { 6679 Log.v(TAG, "Query " + intent + ": " + results); 6680 } 6681 6682 int specificsPos = 0; 6683 int N; 6684 6685 // todo: note that the algorithm used here is O(N^2). This 6686 // isn't a problem in our current environment, but if we start running 6687 // into situations where we have more than 5 or 10 matches then this 6688 // should probably be changed to something smarter... 6689 6690 // First we go through and resolve each of the specific items 6691 // that were supplied, taking care of removing any corresponding 6692 // duplicate items in the generic resolve list. 6693 if (specifics != null) { 6694 for (int i=0; i<specifics.length; i++) { 6695 final Intent sintent = specifics[i]; 6696 if (sintent == null) { 6697 continue; 6698 } 6699 6700 if (DEBUG_INTENT_MATCHING) { 6701 Log.v(TAG, "Specific #" + i + ": " + sintent); 6702 } 6703 6704 String action = sintent.getAction(); 6705 if (resultsAction != null && resultsAction.equals(action)) { 6706 // If this action was explicitly requested, then don't 6707 // remove things that have it. 6708 action = null; 6709 } 6710 6711 ResolveInfo ri = null; 6712 ActivityInfo ai = null; 6713 6714 ComponentName comp = sintent.getComponent(); 6715 if (comp == null) { 6716 ri = resolveIntent( 6717 sintent, 6718 specificTypes != null ? specificTypes[i] : null, 6719 flags, userId); 6720 if (ri == null) { 6721 continue; 6722 } 6723 if (ri == mResolveInfo) { 6724 // ACK! Must do something better with this. 6725 } 6726 ai = ri.activityInfo; 6727 comp = new ComponentName(ai.applicationInfo.packageName, 6728 ai.name); 6729 } else { 6730 ai = getActivityInfo(comp, flags, userId); 6731 if (ai == null) { 6732 continue; 6733 } 6734 } 6735 6736 // Look for any generic query activities that are duplicates 6737 // of this specific one, and remove them from the results. 6738 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6739 N = results.size(); 6740 int j; 6741 for (j=specificsPos; j<N; j++) { 6742 ResolveInfo sri = results.get(j); 6743 if ((sri.activityInfo.name.equals(comp.getClassName()) 6744 && sri.activityInfo.applicationInfo.packageName.equals( 6745 comp.getPackageName())) 6746 || (action != null && sri.filter.matchAction(action))) { 6747 results.remove(j); 6748 if (DEBUG_INTENT_MATCHING) Log.v( 6749 TAG, "Removing duplicate item from " + j 6750 + " due to specific " + specificsPos); 6751 if (ri == null) { 6752 ri = sri; 6753 } 6754 j--; 6755 N--; 6756 } 6757 } 6758 6759 // Add this specific item to its proper place. 6760 if (ri == null) { 6761 ri = new ResolveInfo(); 6762 ri.activityInfo = ai; 6763 } 6764 results.add(specificsPos, ri); 6765 ri.specificIndex = i; 6766 specificsPos++; 6767 } 6768 } 6769 6770 // Now we go through the remaining generic results and remove any 6771 // duplicate actions that are found here. 6772 N = results.size(); 6773 for (int i=specificsPos; i<N-1; i++) { 6774 final ResolveInfo rii = results.get(i); 6775 if (rii.filter == null) { 6776 continue; 6777 } 6778 6779 // Iterate over all of the actions of this result's intent 6780 // filter... typically this should be just one. 6781 final Iterator<String> it = rii.filter.actionsIterator(); 6782 if (it == null) { 6783 continue; 6784 } 6785 while (it.hasNext()) { 6786 final String action = it.next(); 6787 if (resultsAction != null && resultsAction.equals(action)) { 6788 // If this action was explicitly requested, then don't 6789 // remove things that have it. 6790 continue; 6791 } 6792 for (int j=i+1; j<N; j++) { 6793 final ResolveInfo rij = results.get(j); 6794 if (rij.filter != null && rij.filter.hasAction(action)) { 6795 results.remove(j); 6796 if (DEBUG_INTENT_MATCHING) Log.v( 6797 TAG, "Removing duplicate item from " + j 6798 + " due to action " + action + " at " + i); 6799 j--; 6800 N--; 6801 } 6802 } 6803 } 6804 6805 // If the caller didn't request filter information, drop it now 6806 // so we don't have to marshall/unmarshall it. 6807 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6808 rii.filter = null; 6809 } 6810 } 6811 6812 // Filter out the caller activity if so requested. 6813 if (caller != null) { 6814 N = results.size(); 6815 for (int i=0; i<N; i++) { 6816 ActivityInfo ainfo = results.get(i).activityInfo; 6817 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6818 && caller.getClassName().equals(ainfo.name)) { 6819 results.remove(i); 6820 break; 6821 } 6822 } 6823 } 6824 6825 // If the caller didn't request filter information, 6826 // drop them now so we don't have to 6827 // marshall/unmarshall it. 6828 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6829 N = results.size(); 6830 for (int i=0; i<N; i++) { 6831 results.get(i).filter = null; 6832 } 6833 } 6834 6835 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6836 return results; 6837 } 6838 6839 @Override 6840 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6841 String resolvedType, int flags, int userId) { 6842 return new ParceledListSlice<>( 6843 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6844 } 6845 6846 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6847 String resolvedType, int flags, int userId) { 6848 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6849 flags = updateFlagsForResolve(flags, userId, intent); 6850 ComponentName comp = intent.getComponent(); 6851 if (comp == null) { 6852 if (intent.getSelector() != null) { 6853 intent = intent.getSelector(); 6854 comp = intent.getComponent(); 6855 } 6856 } 6857 if (comp != null) { 6858 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6859 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6860 if (ai != null) { 6861 ResolveInfo ri = new ResolveInfo(); 6862 ri.activityInfo = ai; 6863 list.add(ri); 6864 } 6865 return list; 6866 } 6867 6868 // reader 6869 synchronized (mPackages) { 6870 String pkgName = intent.getPackage(); 6871 if (pkgName == null) { 6872 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6873 } 6874 final PackageParser.Package pkg = mPackages.get(pkgName); 6875 if (pkg != null) { 6876 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6877 userId); 6878 } 6879 return Collections.emptyList(); 6880 } 6881 } 6882 6883 @Override 6884 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6885 if (!sUserManager.exists(userId)) return null; 6886 flags = updateFlagsForResolve(flags, userId, intent); 6887 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6888 if (query != null) { 6889 if (query.size() >= 1) { 6890 // If there is more than one service with the same priority, 6891 // just arbitrarily pick the first one. 6892 return query.get(0); 6893 } 6894 } 6895 return null; 6896 } 6897 6898 @Override 6899 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6900 String resolvedType, int flags, int userId) { 6901 return new ParceledListSlice<>( 6902 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6903 } 6904 6905 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6906 String resolvedType, int flags, int userId) { 6907 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6908 flags = updateFlagsForResolve(flags, userId, intent); 6909 ComponentName comp = intent.getComponent(); 6910 if (comp == null) { 6911 if (intent.getSelector() != null) { 6912 intent = intent.getSelector(); 6913 comp = intent.getComponent(); 6914 } 6915 } 6916 if (comp != null) { 6917 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6918 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6919 if (si != null) { 6920 final ResolveInfo ri = new ResolveInfo(); 6921 ri.serviceInfo = si; 6922 list.add(ri); 6923 } 6924 return list; 6925 } 6926 6927 // reader 6928 synchronized (mPackages) { 6929 String pkgName = intent.getPackage(); 6930 if (pkgName == null) { 6931 return mServices.queryIntent(intent, resolvedType, flags, userId); 6932 } 6933 final PackageParser.Package pkg = mPackages.get(pkgName); 6934 if (pkg != null) { 6935 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6936 userId); 6937 } 6938 return Collections.emptyList(); 6939 } 6940 } 6941 6942 @Override 6943 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6944 String resolvedType, int flags, int userId) { 6945 return new ParceledListSlice<>( 6946 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6947 } 6948 6949 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6950 Intent intent, String resolvedType, int flags, int userId) { 6951 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6952 flags = updateFlagsForResolve(flags, userId, intent); 6953 ComponentName comp = intent.getComponent(); 6954 if (comp == null) { 6955 if (intent.getSelector() != null) { 6956 intent = intent.getSelector(); 6957 comp = intent.getComponent(); 6958 } 6959 } 6960 if (comp != null) { 6961 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6962 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6963 if (pi != null) { 6964 final ResolveInfo ri = new ResolveInfo(); 6965 ri.providerInfo = pi; 6966 list.add(ri); 6967 } 6968 return list; 6969 } 6970 6971 // reader 6972 synchronized (mPackages) { 6973 String pkgName = intent.getPackage(); 6974 if (pkgName == null) { 6975 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6976 } 6977 final PackageParser.Package pkg = mPackages.get(pkgName); 6978 if (pkg != null) { 6979 return mProviders.queryIntentForPackage( 6980 intent, resolvedType, flags, pkg.providers, userId); 6981 } 6982 return Collections.emptyList(); 6983 } 6984 } 6985 6986 @Override 6987 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6988 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6989 flags = updateFlagsForPackage(flags, userId, null); 6990 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6991 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6992 true /* requireFullPermission */, false /* checkShell */, 6993 "get installed packages"); 6994 6995 // writer 6996 synchronized (mPackages) { 6997 ArrayList<PackageInfo> list; 6998 if (listUninstalled) { 6999 list = new ArrayList<>(mSettings.mPackages.size()); 7000 for (PackageSetting ps : mSettings.mPackages.values()) { 7001 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7002 continue; 7003 } 7004 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7005 if (pi != null) { 7006 list.add(pi); 7007 } 7008 } 7009 } else { 7010 list = new ArrayList<>(mPackages.size()); 7011 for (PackageParser.Package p : mPackages.values()) { 7012 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7013 Binder.getCallingUid(), userId)) { 7014 continue; 7015 } 7016 final PackageInfo pi = generatePackageInfo((PackageSetting) 7017 p.mExtras, flags, userId); 7018 if (pi != null) { 7019 list.add(pi); 7020 } 7021 } 7022 } 7023 7024 return new ParceledListSlice<>(list); 7025 } 7026 } 7027 7028 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7029 String[] permissions, boolean[] tmp, int flags, int userId) { 7030 int numMatch = 0; 7031 final PermissionsState permissionsState = ps.getPermissionsState(); 7032 for (int i=0; i<permissions.length; i++) { 7033 final String permission = permissions[i]; 7034 if (permissionsState.hasPermission(permission, userId)) { 7035 tmp[i] = true; 7036 numMatch++; 7037 } else { 7038 tmp[i] = false; 7039 } 7040 } 7041 if (numMatch == 0) { 7042 return; 7043 } 7044 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7045 7046 // The above might return null in cases of uninstalled apps or install-state 7047 // skew across users/profiles. 7048 if (pi != null) { 7049 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7050 if (numMatch == permissions.length) { 7051 pi.requestedPermissions = permissions; 7052 } else { 7053 pi.requestedPermissions = new String[numMatch]; 7054 numMatch = 0; 7055 for (int i=0; i<permissions.length; i++) { 7056 if (tmp[i]) { 7057 pi.requestedPermissions[numMatch] = permissions[i]; 7058 numMatch++; 7059 } 7060 } 7061 } 7062 } 7063 list.add(pi); 7064 } 7065 } 7066 7067 @Override 7068 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7069 String[] permissions, int flags, int userId) { 7070 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7071 flags = updateFlagsForPackage(flags, userId, permissions); 7072 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7073 true /* requireFullPermission */, false /* checkShell */, 7074 "get packages holding permissions"); 7075 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7076 7077 // writer 7078 synchronized (mPackages) { 7079 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7080 boolean[] tmpBools = new boolean[permissions.length]; 7081 if (listUninstalled) { 7082 for (PackageSetting ps : mSettings.mPackages.values()) { 7083 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7084 userId); 7085 } 7086 } else { 7087 for (PackageParser.Package pkg : mPackages.values()) { 7088 PackageSetting ps = (PackageSetting)pkg.mExtras; 7089 if (ps != null) { 7090 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7091 userId); 7092 } 7093 } 7094 } 7095 7096 return new ParceledListSlice<PackageInfo>(list); 7097 } 7098 } 7099 7100 @Override 7101 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7102 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7103 flags = updateFlagsForApplication(flags, userId, null); 7104 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7105 7106 // writer 7107 synchronized (mPackages) { 7108 ArrayList<ApplicationInfo> list; 7109 if (listUninstalled) { 7110 list = new ArrayList<>(mSettings.mPackages.size()); 7111 for (PackageSetting ps : mSettings.mPackages.values()) { 7112 ApplicationInfo ai; 7113 int effectiveFlags = flags; 7114 if (ps.isSystem()) { 7115 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7116 } 7117 if (ps.pkg != null) { 7118 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7119 continue; 7120 } 7121 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7122 ps.readUserState(userId), userId); 7123 if (ai != null) { 7124 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7125 } 7126 } else { 7127 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7128 // and already converts to externally visible package name 7129 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7130 Binder.getCallingUid(), effectiveFlags, userId); 7131 } 7132 if (ai != null) { 7133 list.add(ai); 7134 } 7135 } 7136 } else { 7137 list = new ArrayList<>(mPackages.size()); 7138 for (PackageParser.Package p : mPackages.values()) { 7139 if (p.mExtras != null) { 7140 PackageSetting ps = (PackageSetting) p.mExtras; 7141 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7142 continue; 7143 } 7144 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7145 ps.readUserState(userId), userId); 7146 if (ai != null) { 7147 ai.packageName = resolveExternalPackageNameLPr(p); 7148 list.add(ai); 7149 } 7150 } 7151 } 7152 } 7153 7154 return new ParceledListSlice<>(list); 7155 } 7156 } 7157 7158 @Override 7159 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7160 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7161 return null; 7162 } 7163 7164 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7165 "getEphemeralApplications"); 7166 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7167 true /* requireFullPermission */, false /* checkShell */, 7168 "getEphemeralApplications"); 7169 synchronized (mPackages) { 7170 List<InstantAppInfo> instantApps = mInstantAppRegistry 7171 .getInstantAppsLPr(userId); 7172 if (instantApps != null) { 7173 return new ParceledListSlice<>(instantApps); 7174 } 7175 } 7176 return null; 7177 } 7178 7179 @Override 7180 public boolean isInstantApp(String packageName, int userId) { 7181 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7182 true /* requireFullPermission */, false /* checkShell */, 7183 "isInstantApp"); 7184 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7185 return false; 7186 } 7187 7188 if (!isCallerSameApp(packageName)) { 7189 return false; 7190 } 7191 synchronized (mPackages) { 7192 final PackageSetting ps = mSettings.mPackages.get(packageName); 7193 if (ps != null) { 7194 return ps.getInstantApp(userId); 7195 } 7196 } 7197 return false; 7198 } 7199 7200 @Override 7201 public byte[] getInstantAppCookie(String packageName, int userId) { 7202 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7203 return null; 7204 } 7205 7206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7207 true /* requireFullPermission */, false /* checkShell */, 7208 "getInstantAppCookie"); 7209 if (!isCallerSameApp(packageName)) { 7210 return null; 7211 } 7212 synchronized (mPackages) { 7213 return mInstantAppRegistry.getInstantAppCookieLPw( 7214 packageName, userId); 7215 } 7216 } 7217 7218 @Override 7219 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7220 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7221 return true; 7222 } 7223 7224 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7225 true /* requireFullPermission */, true /* checkShell */, 7226 "setInstantAppCookie"); 7227 if (!isCallerSameApp(packageName)) { 7228 return false; 7229 } 7230 synchronized (mPackages) { 7231 return mInstantAppRegistry.setInstantAppCookieLPw( 7232 packageName, cookie, userId); 7233 } 7234 } 7235 7236 @Override 7237 public Bitmap getInstantAppIcon(String packageName, int userId) { 7238 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7239 return null; 7240 } 7241 7242 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7243 "getInstantAppIcon"); 7244 7245 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7246 true /* requireFullPermission */, false /* checkShell */, 7247 "getInstantAppIcon"); 7248 7249 synchronized (mPackages) { 7250 return mInstantAppRegistry.getInstantAppIconLPw( 7251 packageName, userId); 7252 } 7253 } 7254 7255 private boolean isCallerSameApp(String packageName) { 7256 PackageParser.Package pkg = mPackages.get(packageName); 7257 return pkg != null 7258 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7259 } 7260 7261 @Override 7262 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7263 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7264 } 7265 7266 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7267 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7268 7269 // reader 7270 synchronized (mPackages) { 7271 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7272 final int userId = UserHandle.getCallingUserId(); 7273 while (i.hasNext()) { 7274 final PackageParser.Package p = i.next(); 7275 if (p.applicationInfo == null) continue; 7276 7277 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7278 && !p.applicationInfo.isDirectBootAware(); 7279 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7280 && p.applicationInfo.isDirectBootAware(); 7281 7282 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7283 && (!mSafeMode || isSystemApp(p)) 7284 && (matchesUnaware || matchesAware)) { 7285 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7286 if (ps != null) { 7287 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7288 ps.readUserState(userId), userId); 7289 if (ai != null) { 7290 finalList.add(ai); 7291 } 7292 } 7293 } 7294 } 7295 } 7296 7297 return finalList; 7298 } 7299 7300 @Override 7301 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7302 if (!sUserManager.exists(userId)) return null; 7303 flags = updateFlagsForComponent(flags, userId, name); 7304 // reader 7305 synchronized (mPackages) { 7306 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7307 PackageSetting ps = provider != null 7308 ? mSettings.mPackages.get(provider.owner.packageName) 7309 : null; 7310 return ps != null 7311 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7312 ? PackageParser.generateProviderInfo(provider, flags, 7313 ps.readUserState(userId), userId) 7314 : null; 7315 } 7316 } 7317 7318 /** 7319 * @deprecated 7320 */ 7321 @Deprecated 7322 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7323 // reader 7324 synchronized (mPackages) { 7325 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7326 .entrySet().iterator(); 7327 final int userId = UserHandle.getCallingUserId(); 7328 while (i.hasNext()) { 7329 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7330 PackageParser.Provider p = entry.getValue(); 7331 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7332 7333 if (ps != null && p.syncable 7334 && (!mSafeMode || (p.info.applicationInfo.flags 7335 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7336 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7337 ps.readUserState(userId), userId); 7338 if (info != null) { 7339 outNames.add(entry.getKey()); 7340 outInfo.add(info); 7341 } 7342 } 7343 } 7344 } 7345 } 7346 7347 @Override 7348 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7349 int uid, int flags) { 7350 final int userId = processName != null ? UserHandle.getUserId(uid) 7351 : UserHandle.getCallingUserId(); 7352 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7353 flags = updateFlagsForComponent(flags, userId, processName); 7354 7355 ArrayList<ProviderInfo> finalList = null; 7356 // reader 7357 synchronized (mPackages) { 7358 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7359 while (i.hasNext()) { 7360 final PackageParser.Provider p = i.next(); 7361 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7362 if (ps != null && p.info.authority != null 7363 && (processName == null 7364 || (p.info.processName.equals(processName) 7365 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7366 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7367 if (finalList == null) { 7368 finalList = new ArrayList<ProviderInfo>(3); 7369 } 7370 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7371 ps.readUserState(userId), userId); 7372 if (info != null) { 7373 finalList.add(info); 7374 } 7375 } 7376 } 7377 } 7378 7379 if (finalList != null) { 7380 Collections.sort(finalList, mProviderInitOrderSorter); 7381 return new ParceledListSlice<ProviderInfo>(finalList); 7382 } 7383 7384 return ParceledListSlice.emptyList(); 7385 } 7386 7387 @Override 7388 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7389 // reader 7390 synchronized (mPackages) { 7391 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7392 return PackageParser.generateInstrumentationInfo(i, flags); 7393 } 7394 } 7395 7396 @Override 7397 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7398 String targetPackage, int flags) { 7399 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7400 } 7401 7402 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7403 int flags) { 7404 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7405 7406 // reader 7407 synchronized (mPackages) { 7408 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7409 while (i.hasNext()) { 7410 final PackageParser.Instrumentation p = i.next(); 7411 if (targetPackage == null 7412 || targetPackage.equals(p.info.targetPackage)) { 7413 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7414 flags); 7415 if (ii != null) { 7416 finalList.add(ii); 7417 } 7418 } 7419 } 7420 } 7421 7422 return finalList; 7423 } 7424 7425 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7426 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7427 if (overlays == null) { 7428 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7429 return; 7430 } 7431 for (PackageParser.Package opkg : overlays.values()) { 7432 // Not much to do if idmap fails: we already logged the error 7433 // and we certainly don't want to abort installation of pkg simply 7434 // because an overlay didn't fit properly. For these reasons, 7435 // ignore the return value of createIdmapForPackagePairLI. 7436 createIdmapForPackagePairLI(pkg, opkg); 7437 } 7438 } 7439 7440 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7441 PackageParser.Package opkg) { 7442 if (!opkg.mTrustedOverlay) { 7443 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7444 opkg.baseCodePath + ": overlay not trusted"); 7445 return false; 7446 } 7447 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7448 if (overlaySet == null) { 7449 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7450 opkg.baseCodePath + " but target package has no known overlays"); 7451 return false; 7452 } 7453 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7454 // TODO: generate idmap for split APKs 7455 try { 7456 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7457 } catch (InstallerException e) { 7458 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7459 + opkg.baseCodePath); 7460 return false; 7461 } 7462 PackageParser.Package[] overlayArray = 7463 overlaySet.values().toArray(new PackageParser.Package[0]); 7464 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7465 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7466 return p1.mOverlayPriority - p2.mOverlayPriority; 7467 } 7468 }; 7469 Arrays.sort(overlayArray, cmp); 7470 7471 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7472 int i = 0; 7473 for (PackageParser.Package p : overlayArray) { 7474 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7475 } 7476 return true; 7477 } 7478 7479 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7481 try { 7482 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7483 } finally { 7484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7485 } 7486 } 7487 7488 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7489 final File[] files = dir.listFiles(); 7490 if (ArrayUtils.isEmpty(files)) { 7491 Log.d(TAG, "No files in app dir " + dir); 7492 return; 7493 } 7494 7495 if (DEBUG_PACKAGE_SCANNING) { 7496 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7497 + " flags=0x" + Integer.toHexString(parseFlags)); 7498 } 7499 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7500 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7501 7502 // Submit files for parsing in parallel 7503 int fileCount = 0; 7504 for (File file : files) { 7505 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7506 && !PackageInstallerService.isStageName(file.getName()); 7507 if (!isPackage) { 7508 // Ignore entries which are not packages 7509 continue; 7510 } 7511 parallelPackageParser.submit(file, parseFlags); 7512 fileCount++; 7513 } 7514 7515 // Process results one by one 7516 for (; fileCount > 0; fileCount--) { 7517 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7518 Throwable throwable = parseResult.throwable; 7519 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7520 7521 if (throwable == null) { 7522 // Static shared libraries have synthetic package names 7523 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7524 renameStaticSharedLibraryPackage(parseResult.pkg); 7525 } 7526 try { 7527 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7528 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7529 currentTime, null); 7530 } 7531 } catch (PackageManagerException e) { 7532 errorCode = e.error; 7533 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7534 } 7535 } else if (throwable instanceof PackageParser.PackageParserException) { 7536 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7537 throwable; 7538 errorCode = e.error; 7539 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7540 } else { 7541 throw new IllegalStateException("Unexpected exception occurred while parsing " 7542 + parseResult.scanFile, throwable); 7543 } 7544 7545 // Delete invalid userdata apps 7546 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7547 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7548 logCriticalInfo(Log.WARN, 7549 "Deleting invalid package at " + parseResult.scanFile); 7550 removeCodePathLI(parseResult.scanFile); 7551 } 7552 } 7553 parallelPackageParser.close(); 7554 } 7555 7556 private static File getSettingsProblemFile() { 7557 File dataDir = Environment.getDataDirectory(); 7558 File systemDir = new File(dataDir, "system"); 7559 File fname = new File(systemDir, "uiderrors.txt"); 7560 return fname; 7561 } 7562 7563 static void reportSettingsProblem(int priority, String msg) { 7564 logCriticalInfo(priority, msg); 7565 } 7566 7567 static void logCriticalInfo(int priority, String msg) { 7568 Slog.println(priority, TAG, msg); 7569 EventLogTags.writePmCriticalInfo(msg); 7570 try { 7571 File fname = getSettingsProblemFile(); 7572 FileOutputStream out = new FileOutputStream(fname, true); 7573 PrintWriter pw = new FastPrintWriter(out); 7574 SimpleDateFormat formatter = new SimpleDateFormat(); 7575 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7576 pw.println(dateString + ": " + msg); 7577 pw.close(); 7578 FileUtils.setPermissions( 7579 fname.toString(), 7580 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7581 -1, -1); 7582 } catch (java.io.IOException e) { 7583 } 7584 } 7585 7586 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7587 if (srcFile.isDirectory()) { 7588 final File baseFile = new File(pkg.baseCodePath); 7589 long maxModifiedTime = baseFile.lastModified(); 7590 if (pkg.splitCodePaths != null) { 7591 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7592 final File splitFile = new File(pkg.splitCodePaths[i]); 7593 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7594 } 7595 } 7596 return maxModifiedTime; 7597 } 7598 return srcFile.lastModified(); 7599 } 7600 7601 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7602 final int policyFlags) throws PackageManagerException { 7603 // When upgrading from pre-N MR1, verify the package time stamp using the package 7604 // directory and not the APK file. 7605 final long lastModifiedTime = mIsPreNMR1Upgrade 7606 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7607 if (ps != null 7608 && ps.codePath.equals(srcFile) 7609 && ps.timeStamp == lastModifiedTime 7610 && !isCompatSignatureUpdateNeeded(pkg) 7611 && !isRecoverSignatureUpdateNeeded(pkg)) { 7612 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7614 ArraySet<PublicKey> signingKs; 7615 synchronized (mPackages) { 7616 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7617 } 7618 if (ps.signatures.mSignatures != null 7619 && ps.signatures.mSignatures.length != 0 7620 && signingKs != null) { 7621 // Optimization: reuse the existing cached certificates 7622 // if the package appears to be unchanged. 7623 pkg.mSignatures = ps.signatures.mSignatures; 7624 pkg.mSigningKeys = signingKs; 7625 return; 7626 } 7627 7628 Slog.w(TAG, "PackageSetting for " + ps.name 7629 + " is missing signatures. Collecting certs again to recover them."); 7630 } else { 7631 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7632 } 7633 7634 try { 7635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7636 PackageParser.collectCertificates(pkg, policyFlags); 7637 } catch (PackageParserException e) { 7638 throw PackageManagerException.from(e); 7639 } finally { 7640 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7641 } 7642 } 7643 7644 /** 7645 * Traces a package scan. 7646 * @see #scanPackageLI(File, int, int, long, UserHandle) 7647 */ 7648 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7649 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7650 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7651 try { 7652 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7653 } finally { 7654 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7655 } 7656 } 7657 7658 /** 7659 * Scans a package and returns the newly parsed package. 7660 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7661 */ 7662 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7663 long currentTime, UserHandle user) throws PackageManagerException { 7664 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7665 PackageParser pp = new PackageParser(); 7666 pp.setSeparateProcesses(mSeparateProcesses); 7667 pp.setOnlyCoreApps(mOnlyCore); 7668 pp.setDisplayMetrics(mMetrics); 7669 7670 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7671 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7672 } 7673 7674 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7675 final PackageParser.Package pkg; 7676 try { 7677 pkg = pp.parsePackage(scanFile, parseFlags); 7678 } catch (PackageParserException e) { 7679 throw PackageManagerException.from(e); 7680 } finally { 7681 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7682 } 7683 7684 // Static shared libraries have synthetic package names 7685 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7686 renameStaticSharedLibraryPackage(pkg); 7687 } 7688 7689 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7690 } 7691 7692 /** 7693 * Scans a package and returns the newly parsed package. 7694 * @throws PackageManagerException on a parse error. 7695 */ 7696 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7697 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7698 throws PackageManagerException { 7699 // If the package has children and this is the first dive in the function 7700 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7701 // packages (parent and children) would be successfully scanned before the 7702 // actual scan since scanning mutates internal state and we want to atomically 7703 // install the package and its children. 7704 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7705 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7706 scanFlags |= SCAN_CHECK_ONLY; 7707 } 7708 } else { 7709 scanFlags &= ~SCAN_CHECK_ONLY; 7710 } 7711 7712 // Scan the parent 7713 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7714 scanFlags, currentTime, user); 7715 7716 // Scan the children 7717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7718 for (int i = 0; i < childCount; i++) { 7719 PackageParser.Package childPackage = pkg.childPackages.get(i); 7720 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7721 currentTime, user); 7722 } 7723 7724 7725 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7726 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7727 } 7728 7729 return scannedPkg; 7730 } 7731 7732 /** 7733 * Scans a package and returns the newly parsed package. 7734 * @throws PackageManagerException on a parse error. 7735 */ 7736 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7737 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7738 throws PackageManagerException { 7739 PackageSetting ps = null; 7740 PackageSetting updatedPkg; 7741 // reader 7742 synchronized (mPackages) { 7743 // Look to see if we already know about this package. 7744 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7745 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7746 // This package has been renamed to its original name. Let's 7747 // use that. 7748 ps = mSettings.getPackageLPr(oldName); 7749 } 7750 // If there was no original package, see one for the real package name. 7751 if (ps == null) { 7752 ps = mSettings.getPackageLPr(pkg.packageName); 7753 } 7754 // Check to see if this package could be hiding/updating a system 7755 // package. Must look for it either under the original or real 7756 // package name depending on our state. 7757 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7758 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7759 7760 // If this is a package we don't know about on the system partition, we 7761 // may need to remove disabled child packages on the system partition 7762 // or may need to not add child packages if the parent apk is updated 7763 // on the data partition and no longer defines this child package. 7764 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7765 // If this is a parent package for an updated system app and this system 7766 // app got an OTA update which no longer defines some of the child packages 7767 // we have to prune them from the disabled system packages. 7768 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7769 if (disabledPs != null) { 7770 final int scannedChildCount = (pkg.childPackages != null) 7771 ? pkg.childPackages.size() : 0; 7772 final int disabledChildCount = disabledPs.childPackageNames != null 7773 ? disabledPs.childPackageNames.size() : 0; 7774 for (int i = 0; i < disabledChildCount; i++) { 7775 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7776 boolean disabledPackageAvailable = false; 7777 for (int j = 0; j < scannedChildCount; j++) { 7778 PackageParser.Package childPkg = pkg.childPackages.get(j); 7779 if (childPkg.packageName.equals(disabledChildPackageName)) { 7780 disabledPackageAvailable = true; 7781 break; 7782 } 7783 } 7784 if (!disabledPackageAvailable) { 7785 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7786 } 7787 } 7788 } 7789 } 7790 } 7791 7792 boolean updatedPkgBetter = false; 7793 // First check if this is a system package that may involve an update 7794 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7795 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7796 // it needs to drop FLAG_PRIVILEGED. 7797 if (locationIsPrivileged(scanFile)) { 7798 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7799 } else { 7800 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7801 } 7802 7803 if (ps != null && !ps.codePath.equals(scanFile)) { 7804 // The path has changed from what was last scanned... check the 7805 // version of the new path against what we have stored to determine 7806 // what to do. 7807 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7808 if (pkg.mVersionCode <= ps.versionCode) { 7809 // The system package has been updated and the code path does not match 7810 // Ignore entry. Skip it. 7811 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7812 + " ignored: updated version " + ps.versionCode 7813 + " better than this " + pkg.mVersionCode); 7814 if (!updatedPkg.codePath.equals(scanFile)) { 7815 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7816 + ps.name + " changing from " + updatedPkg.codePathString 7817 + " to " + scanFile); 7818 updatedPkg.codePath = scanFile; 7819 updatedPkg.codePathString = scanFile.toString(); 7820 updatedPkg.resourcePath = scanFile; 7821 updatedPkg.resourcePathString = scanFile.toString(); 7822 } 7823 updatedPkg.pkg = pkg; 7824 updatedPkg.versionCode = pkg.mVersionCode; 7825 7826 // Update the disabled system child packages to point to the package too. 7827 final int childCount = updatedPkg.childPackageNames != null 7828 ? updatedPkg.childPackageNames.size() : 0; 7829 for (int i = 0; i < childCount; i++) { 7830 String childPackageName = updatedPkg.childPackageNames.get(i); 7831 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7832 childPackageName); 7833 if (updatedChildPkg != null) { 7834 updatedChildPkg.pkg = pkg; 7835 updatedChildPkg.versionCode = pkg.mVersionCode; 7836 } 7837 } 7838 7839 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7840 + scanFile + " ignored: updated version " + ps.versionCode 7841 + " better than this " + pkg.mVersionCode); 7842 } else { 7843 // The current app on the system partition is better than 7844 // what we have updated to on the data partition; switch 7845 // back to the system partition version. 7846 // At this point, its safely assumed that package installation for 7847 // apps in system partition will go through. If not there won't be a working 7848 // version of the app 7849 // writer 7850 synchronized (mPackages) { 7851 // Just remove the loaded entries from package lists. 7852 mPackages.remove(ps.name); 7853 } 7854 7855 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7856 + " reverting from " + ps.codePathString 7857 + ": new version " + pkg.mVersionCode 7858 + " better than installed " + ps.versionCode); 7859 7860 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7861 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7862 synchronized (mInstallLock) { 7863 args.cleanUpResourcesLI(); 7864 } 7865 synchronized (mPackages) { 7866 mSettings.enableSystemPackageLPw(ps.name); 7867 } 7868 updatedPkgBetter = true; 7869 } 7870 } 7871 } 7872 7873 if (updatedPkg != null) { 7874 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7875 // initially 7876 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7877 7878 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7879 // flag set initially 7880 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7881 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7882 } 7883 } 7884 7885 // Verify certificates against what was last scanned 7886 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7887 7888 /* 7889 * A new system app appeared, but we already had a non-system one of the 7890 * same name installed earlier. 7891 */ 7892 boolean shouldHideSystemApp = false; 7893 if (updatedPkg == null && ps != null 7894 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7895 /* 7896 * Check to make sure the signatures match first. If they don't, 7897 * wipe the installed application and its data. 7898 */ 7899 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7900 != PackageManager.SIGNATURE_MATCH) { 7901 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7902 + " signatures don't match existing userdata copy; removing"); 7903 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7904 "scanPackageInternalLI")) { 7905 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7906 } 7907 ps = null; 7908 } else { 7909 /* 7910 * If the newly-added system app is an older version than the 7911 * already installed version, hide it. It will be scanned later 7912 * and re-added like an update. 7913 */ 7914 if (pkg.mVersionCode <= ps.versionCode) { 7915 shouldHideSystemApp = true; 7916 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7917 + " but new version " + pkg.mVersionCode + " better than installed " 7918 + ps.versionCode + "; hiding system"); 7919 } else { 7920 /* 7921 * The newly found system app is a newer version that the 7922 * one previously installed. Simply remove the 7923 * already-installed application and replace it with our own 7924 * while keeping the application data. 7925 */ 7926 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7927 + " reverting from " + ps.codePathString + ": new version " 7928 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7929 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7930 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7931 synchronized (mInstallLock) { 7932 args.cleanUpResourcesLI(); 7933 } 7934 } 7935 } 7936 } 7937 7938 // The apk is forward locked (not public) if its code and resources 7939 // are kept in different files. (except for app in either system or 7940 // vendor path). 7941 // TODO grab this value from PackageSettings 7942 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7943 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7944 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7945 } 7946 } 7947 7948 // TODO: extend to support forward-locked splits 7949 String resourcePath = null; 7950 String baseResourcePath = null; 7951 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7952 if (ps != null && ps.resourcePathString != null) { 7953 resourcePath = ps.resourcePathString; 7954 baseResourcePath = ps.resourcePathString; 7955 } else { 7956 // Should not happen at all. Just log an error. 7957 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7958 } 7959 } else { 7960 resourcePath = pkg.codePath; 7961 baseResourcePath = pkg.baseCodePath; 7962 } 7963 7964 // Set application objects path explicitly. 7965 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7966 pkg.setApplicationInfoCodePath(pkg.codePath); 7967 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7968 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7969 pkg.setApplicationInfoResourcePath(resourcePath); 7970 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7971 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7972 7973 final int userId = ((user == null) ? 0 : user.getIdentifier()); 7974 if (ps != null && ps.getInstantApp(userId)) { 7975 scanFlags |= SCAN_AS_INSTANT_APP; 7976 } 7977 7978 // Note that we invoke the following method only if we are about to unpack an application 7979 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7980 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7981 7982 /* 7983 * If the system app should be overridden by a previously installed 7984 * data, hide the system app now and let the /data/app scan pick it up 7985 * again. 7986 */ 7987 if (shouldHideSystemApp) { 7988 synchronized (mPackages) { 7989 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7990 } 7991 } 7992 7993 return scannedPkg; 7994 } 7995 7996 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7997 // Derive the new package synthetic package name 7998 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7999 + pkg.staticSharedLibVersion); 8000 } 8001 8002 private static String fixProcessName(String defProcessName, 8003 String processName) { 8004 if (processName == null) { 8005 return defProcessName; 8006 } 8007 return processName; 8008 } 8009 8010 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8011 throws PackageManagerException { 8012 if (pkgSetting.signatures.mSignatures != null) { 8013 // Already existing package. Make sure signatures match 8014 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8015 == PackageManager.SIGNATURE_MATCH; 8016 if (!match) { 8017 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8018 == PackageManager.SIGNATURE_MATCH; 8019 } 8020 if (!match) { 8021 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8022 == PackageManager.SIGNATURE_MATCH; 8023 } 8024 if (!match) { 8025 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8026 + pkg.packageName + " signatures do not match the " 8027 + "previously installed version; ignoring!"); 8028 } 8029 } 8030 8031 // Check for shared user signatures 8032 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8033 // Already existing package. Make sure signatures match 8034 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8035 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8036 if (!match) { 8037 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8038 == PackageManager.SIGNATURE_MATCH; 8039 } 8040 if (!match) { 8041 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8042 == PackageManager.SIGNATURE_MATCH; 8043 } 8044 if (!match) { 8045 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8046 "Package " + pkg.packageName 8047 + " has no signatures that match those in shared user " 8048 + pkgSetting.sharedUser.name + "; ignoring!"); 8049 } 8050 } 8051 } 8052 8053 /** 8054 * Enforces that only the system UID or root's UID can call a method exposed 8055 * via Binder. 8056 * 8057 * @param message used as message if SecurityException is thrown 8058 * @throws SecurityException if the caller is not system or root 8059 */ 8060 private static final void enforceSystemOrRoot(String message) { 8061 final int uid = Binder.getCallingUid(); 8062 if (uid != Process.SYSTEM_UID && uid != 0) { 8063 throw new SecurityException(message); 8064 } 8065 } 8066 8067 @Override 8068 public void performFstrimIfNeeded() { 8069 enforceSystemOrRoot("Only the system can request fstrim"); 8070 8071 // Before everything else, see whether we need to fstrim. 8072 try { 8073 IStorageManager sm = PackageHelper.getStorageManager(); 8074 if (sm != null) { 8075 boolean doTrim = false; 8076 final long interval = android.provider.Settings.Global.getLong( 8077 mContext.getContentResolver(), 8078 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8079 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8080 if (interval > 0) { 8081 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8082 if (timeSinceLast > interval) { 8083 doTrim = true; 8084 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8085 + "; running immediately"); 8086 } 8087 } 8088 if (doTrim) { 8089 final boolean dexOptDialogShown; 8090 synchronized (mPackages) { 8091 dexOptDialogShown = mDexOptDialogShown; 8092 } 8093 if (!isFirstBoot() && dexOptDialogShown) { 8094 try { 8095 ActivityManager.getService().showBootMessage( 8096 mContext.getResources().getString( 8097 R.string.android_upgrading_fstrim), true); 8098 } catch (RemoteException e) { 8099 } 8100 } 8101 sm.runMaintenance(); 8102 } 8103 } else { 8104 Slog.e(TAG, "storageManager service unavailable!"); 8105 } 8106 } catch (RemoteException e) { 8107 // Can't happen; StorageManagerService is local 8108 } 8109 } 8110 8111 @Override 8112 public void updatePackagesIfNeeded() { 8113 enforceSystemOrRoot("Only the system can request package update"); 8114 8115 // We need to re-extract after an OTA. 8116 boolean causeUpgrade = isUpgrade(); 8117 8118 // First boot or factory reset. 8119 // Note: we also handle devices that are upgrading to N right now as if it is their 8120 // first boot, as they do not have profile data. 8121 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8122 8123 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8124 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8125 8126 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8127 return; 8128 } 8129 8130 List<PackageParser.Package> pkgs; 8131 synchronized (mPackages) { 8132 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8133 } 8134 8135 final long startTime = System.nanoTime(); 8136 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8137 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8138 8139 final int elapsedTimeSeconds = 8140 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8141 8142 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8143 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8144 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8145 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8146 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8147 } 8148 8149 /** 8150 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8151 * containing statistics about the invocation. The array consists of three elements, 8152 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8153 * and {@code numberOfPackagesFailed}. 8154 */ 8155 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8156 String compilerFilter) { 8157 8158 int numberOfPackagesVisited = 0; 8159 int numberOfPackagesOptimized = 0; 8160 int numberOfPackagesSkipped = 0; 8161 int numberOfPackagesFailed = 0; 8162 final int numberOfPackagesToDexopt = pkgs.size(); 8163 8164 for (PackageParser.Package pkg : pkgs) { 8165 numberOfPackagesVisited++; 8166 8167 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8168 if (DEBUG_DEXOPT) { 8169 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8170 } 8171 numberOfPackagesSkipped++; 8172 continue; 8173 } 8174 8175 if (DEBUG_DEXOPT) { 8176 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8177 numberOfPackagesToDexopt + ": " + pkg.packageName); 8178 } 8179 8180 if (showDialog) { 8181 try { 8182 ActivityManager.getService().showBootMessage( 8183 mContext.getResources().getString(R.string.android_upgrading_apk, 8184 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8185 } catch (RemoteException e) { 8186 } 8187 synchronized (mPackages) { 8188 mDexOptDialogShown = true; 8189 } 8190 } 8191 8192 // If the OTA updates a system app which was previously preopted to a non-preopted state 8193 // the app might end up being verified at runtime. That's because by default the apps 8194 // are verify-profile but for preopted apps there's no profile. 8195 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8196 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8197 // filter (by default interpret-only). 8198 // Note that at this stage unused apps are already filtered. 8199 if (isSystemApp(pkg) && 8200 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8201 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8202 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8203 } 8204 8205 // checkProfiles is false to avoid merging profiles during boot which 8206 // might interfere with background compilation (b/28612421). 8207 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8208 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8209 // trade-off worth doing to save boot time work. 8210 int dexOptStatus = performDexOptTraced(pkg.packageName, 8211 false /* checkProfiles */, 8212 compilerFilter, 8213 false /* force */); 8214 switch (dexOptStatus) { 8215 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8216 numberOfPackagesOptimized++; 8217 break; 8218 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8219 numberOfPackagesSkipped++; 8220 break; 8221 case PackageDexOptimizer.DEX_OPT_FAILED: 8222 numberOfPackagesFailed++; 8223 break; 8224 default: 8225 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8226 break; 8227 } 8228 } 8229 8230 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8231 numberOfPackagesFailed }; 8232 } 8233 8234 @Override 8235 public void notifyPackageUse(String packageName, int reason) { 8236 synchronized (mPackages) { 8237 PackageParser.Package p = mPackages.get(packageName); 8238 if (p == null) { 8239 return; 8240 } 8241 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8242 } 8243 } 8244 8245 @Override 8246 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8247 int userId = UserHandle.getCallingUserId(); 8248 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8249 if (ai == null) { 8250 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8251 + loadingPackageName + ", user=" + userId); 8252 return; 8253 } 8254 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8255 } 8256 8257 // TODO: this is not used nor needed. Delete it. 8258 @Override 8259 public boolean performDexOptIfNeeded(String packageName) { 8260 int dexOptStatus = performDexOptTraced(packageName, 8261 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8262 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8263 } 8264 8265 @Override 8266 public boolean performDexOpt(String packageName, 8267 boolean checkProfiles, int compileReason, boolean force) { 8268 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8269 getCompilerFilterForReason(compileReason), force); 8270 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8271 } 8272 8273 @Override 8274 public boolean performDexOptMode(String packageName, 8275 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8276 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8277 targetCompilerFilter, force); 8278 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8279 } 8280 8281 private int performDexOptTraced(String packageName, 8282 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8284 try { 8285 return performDexOptInternal(packageName, checkProfiles, 8286 targetCompilerFilter, force); 8287 } finally { 8288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8289 } 8290 } 8291 8292 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8293 // if the package can now be considered up to date for the given filter. 8294 private int performDexOptInternal(String packageName, 8295 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8296 PackageParser.Package p; 8297 synchronized (mPackages) { 8298 p = mPackages.get(packageName); 8299 if (p == null) { 8300 // Package could not be found. Report failure. 8301 return PackageDexOptimizer.DEX_OPT_FAILED; 8302 } 8303 mPackageUsage.maybeWriteAsync(mPackages); 8304 mCompilerStats.maybeWriteAsync(); 8305 } 8306 long callingId = Binder.clearCallingIdentity(); 8307 try { 8308 synchronized (mInstallLock) { 8309 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8310 targetCompilerFilter, force); 8311 } 8312 } finally { 8313 Binder.restoreCallingIdentity(callingId); 8314 } 8315 } 8316 8317 public ArraySet<String> getOptimizablePackages() { 8318 ArraySet<String> pkgs = new ArraySet<String>(); 8319 synchronized (mPackages) { 8320 for (PackageParser.Package p : mPackages.values()) { 8321 if (PackageDexOptimizer.canOptimizePackage(p)) { 8322 pkgs.add(p.packageName); 8323 } 8324 } 8325 } 8326 return pkgs; 8327 } 8328 8329 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8330 boolean checkProfiles, String targetCompilerFilter, 8331 boolean force) { 8332 // Select the dex optimizer based on the force parameter. 8333 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8334 // allocate an object here. 8335 PackageDexOptimizer pdo = force 8336 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8337 : mPackageDexOptimizer; 8338 8339 // Optimize all dependencies first. Note: we ignore the return value and march on 8340 // on errors. 8341 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8342 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8343 if (!deps.isEmpty()) { 8344 for (PackageParser.Package depPackage : deps) { 8345 // TODO: Analyze and investigate if we (should) profile libraries. 8346 // Currently this will do a full compilation of the library by default. 8347 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8348 false /* checkProfiles */, 8349 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8350 getOrCreateCompilerPackageStats(depPackage)); 8351 } 8352 } 8353 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8354 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8355 } 8356 8357 // Performs dexopt on the used secondary dex files belonging to the given package. 8358 // Returns true if all dex files were process successfully (which could mean either dexopt or 8359 // skip). Returns false if any of the files caused errors. 8360 @Override 8361 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8362 boolean force) { 8363 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8364 } 8365 8366 /** 8367 * Reconcile the information we have about the secondary dex files belonging to 8368 * {@code packagName} and the actual dex files. For all dex files that were 8369 * deleted, update the internal records and delete the generated oat files. 8370 */ 8371 @Override 8372 public void reconcileSecondaryDexFiles(String packageName) { 8373 mDexManager.reconcileSecondaryDexFiles(packageName); 8374 } 8375 8376 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8377 // a reference there. 8378 /*package*/ DexManager getDexManager() { 8379 return mDexManager; 8380 } 8381 8382 /** 8383 * Execute the background dexopt job immediately. 8384 */ 8385 @Override 8386 public boolean runBackgroundDexoptJob() { 8387 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8388 } 8389 8390 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8391 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8392 || p.usesStaticLibraries != null) { 8393 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8394 Set<String> collectedNames = new HashSet<>(); 8395 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8396 8397 retValue.remove(p); 8398 8399 return retValue; 8400 } else { 8401 return Collections.emptyList(); 8402 } 8403 } 8404 8405 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8406 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8407 if (!collectedNames.contains(p.packageName)) { 8408 collectedNames.add(p.packageName); 8409 collected.add(p); 8410 8411 if (p.usesLibraries != null) { 8412 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8413 null, collected, collectedNames); 8414 } 8415 if (p.usesOptionalLibraries != null) { 8416 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8417 null, collected, collectedNames); 8418 } 8419 if (p.usesStaticLibraries != null) { 8420 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8421 p.usesStaticLibrariesVersions, collected, collectedNames); 8422 } 8423 } 8424 } 8425 8426 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8427 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8428 final int libNameCount = libs.size(); 8429 for (int i = 0; i < libNameCount; i++) { 8430 String libName = libs.get(i); 8431 int version = (versions != null && versions.length == libNameCount) 8432 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8433 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8434 if (libPkg != null) { 8435 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8436 } 8437 } 8438 } 8439 8440 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8441 synchronized (mPackages) { 8442 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8443 if (libEntry != null) { 8444 return mPackages.get(libEntry.apk); 8445 } 8446 return null; 8447 } 8448 } 8449 8450 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8451 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8452 if (versionedLib == null) { 8453 return null; 8454 } 8455 return versionedLib.get(version); 8456 } 8457 8458 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8459 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8460 pkg.staticSharedLibName); 8461 if (versionedLib == null) { 8462 return null; 8463 } 8464 int previousLibVersion = -1; 8465 final int versionCount = versionedLib.size(); 8466 for (int i = 0; i < versionCount; i++) { 8467 final int libVersion = versionedLib.keyAt(i); 8468 if (libVersion < pkg.staticSharedLibVersion) { 8469 previousLibVersion = Math.max(previousLibVersion, libVersion); 8470 } 8471 } 8472 if (previousLibVersion >= 0) { 8473 return versionedLib.get(previousLibVersion); 8474 } 8475 return null; 8476 } 8477 8478 public void shutdown() { 8479 mPackageUsage.writeNow(mPackages); 8480 mCompilerStats.writeNow(); 8481 } 8482 8483 @Override 8484 public void dumpProfiles(String packageName) { 8485 PackageParser.Package pkg; 8486 synchronized (mPackages) { 8487 pkg = mPackages.get(packageName); 8488 if (pkg == null) { 8489 throw new IllegalArgumentException("Unknown package: " + packageName); 8490 } 8491 } 8492 /* Only the shell, root, or the app user should be able to dump profiles. */ 8493 int callingUid = Binder.getCallingUid(); 8494 if (callingUid != Process.SHELL_UID && 8495 callingUid != Process.ROOT_UID && 8496 callingUid != pkg.applicationInfo.uid) { 8497 throw new SecurityException("dumpProfiles"); 8498 } 8499 8500 synchronized (mInstallLock) { 8501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8502 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8503 try { 8504 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8505 String codePaths = TextUtils.join(";", allCodePaths); 8506 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8507 } catch (InstallerException e) { 8508 Slog.w(TAG, "Failed to dump profiles", e); 8509 } 8510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8511 } 8512 } 8513 8514 @Override 8515 public void forceDexOpt(String packageName) { 8516 enforceSystemOrRoot("forceDexOpt"); 8517 8518 PackageParser.Package pkg; 8519 synchronized (mPackages) { 8520 pkg = mPackages.get(packageName); 8521 if (pkg == null) { 8522 throw new IllegalArgumentException("Unknown package: " + packageName); 8523 } 8524 } 8525 8526 synchronized (mInstallLock) { 8527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8528 8529 // Whoever is calling forceDexOpt wants a fully compiled package. 8530 // Don't use profiles since that may cause compilation to be skipped. 8531 final int res = performDexOptInternalWithDependenciesLI(pkg, 8532 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8533 true /* force */); 8534 8535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8536 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8537 throw new IllegalStateException("Failed to dexopt: " + res); 8538 } 8539 } 8540 } 8541 8542 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8543 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8544 Slog.w(TAG, "Unable to update from " + oldPkg.name 8545 + " to " + newPkg.packageName 8546 + ": old package not in system partition"); 8547 return false; 8548 } else if (mPackages.get(oldPkg.name) != null) { 8549 Slog.w(TAG, "Unable to update from " + oldPkg.name 8550 + " to " + newPkg.packageName 8551 + ": old package still exists"); 8552 return false; 8553 } 8554 return true; 8555 } 8556 8557 void removeCodePathLI(File codePath) { 8558 if (codePath.isDirectory()) { 8559 try { 8560 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8561 } catch (InstallerException e) { 8562 Slog.w(TAG, "Failed to remove code path", e); 8563 } 8564 } else { 8565 codePath.delete(); 8566 } 8567 } 8568 8569 private int[] resolveUserIds(int userId) { 8570 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8571 } 8572 8573 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8574 if (pkg == null) { 8575 Slog.wtf(TAG, "Package was null!", new Throwable()); 8576 return; 8577 } 8578 clearAppDataLeafLIF(pkg, userId, flags); 8579 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8580 for (int i = 0; i < childCount; i++) { 8581 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8582 } 8583 } 8584 8585 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8586 final PackageSetting ps; 8587 synchronized (mPackages) { 8588 ps = mSettings.mPackages.get(pkg.packageName); 8589 } 8590 for (int realUserId : resolveUserIds(userId)) { 8591 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8592 try { 8593 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8594 ceDataInode); 8595 } catch (InstallerException e) { 8596 Slog.w(TAG, String.valueOf(e)); 8597 } 8598 } 8599 } 8600 8601 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8602 if (pkg == null) { 8603 Slog.wtf(TAG, "Package was null!", new Throwable()); 8604 return; 8605 } 8606 destroyAppDataLeafLIF(pkg, userId, flags); 8607 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8608 for (int i = 0; i < childCount; i++) { 8609 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8610 } 8611 } 8612 8613 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8614 final PackageSetting ps; 8615 synchronized (mPackages) { 8616 ps = mSettings.mPackages.get(pkg.packageName); 8617 } 8618 for (int realUserId : resolveUserIds(userId)) { 8619 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8620 try { 8621 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8622 ceDataInode); 8623 } catch (InstallerException e) { 8624 Slog.w(TAG, String.valueOf(e)); 8625 } 8626 } 8627 } 8628 8629 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8630 if (pkg == null) { 8631 Slog.wtf(TAG, "Package was null!", new Throwable()); 8632 return; 8633 } 8634 destroyAppProfilesLeafLIF(pkg); 8635 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8636 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8637 for (int i = 0; i < childCount; i++) { 8638 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8639 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8640 true /* removeBaseMarker */); 8641 } 8642 } 8643 8644 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8645 boolean removeBaseMarker) { 8646 if (pkg.isForwardLocked()) { 8647 return; 8648 } 8649 8650 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8651 try { 8652 path = PackageManagerServiceUtils.realpath(new File(path)); 8653 } catch (IOException e) { 8654 // TODO: Should we return early here ? 8655 Slog.w(TAG, "Failed to get canonical path", e); 8656 continue; 8657 } 8658 8659 final String useMarker = path.replace('/', '@'); 8660 for (int realUserId : resolveUserIds(userId)) { 8661 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8662 if (removeBaseMarker) { 8663 File foreignUseMark = new File(profileDir, useMarker); 8664 if (foreignUseMark.exists()) { 8665 if (!foreignUseMark.delete()) { 8666 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8667 + pkg.packageName); 8668 } 8669 } 8670 } 8671 8672 File[] markers = profileDir.listFiles(); 8673 if (markers != null) { 8674 final String searchString = "@" + pkg.packageName + "@"; 8675 // We also delete all markers that contain the package name we're 8676 // uninstalling. These are associated with secondary dex-files belonging 8677 // to the package. Reconstructing the path of these dex files is messy 8678 // in general. 8679 for (File marker : markers) { 8680 if (marker.getName().indexOf(searchString) > 0) { 8681 if (!marker.delete()) { 8682 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8683 + pkg.packageName); 8684 } 8685 } 8686 } 8687 } 8688 } 8689 } 8690 } 8691 8692 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8693 try { 8694 mInstaller.destroyAppProfiles(pkg.packageName); 8695 } catch (InstallerException e) { 8696 Slog.w(TAG, String.valueOf(e)); 8697 } 8698 } 8699 8700 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8701 if (pkg == null) { 8702 Slog.wtf(TAG, "Package was null!", new Throwable()); 8703 return; 8704 } 8705 clearAppProfilesLeafLIF(pkg); 8706 // We don't remove the base foreign use marker when clearing profiles because 8707 // we will rename it when the app is updated. Unlike the actual profile contents, 8708 // the foreign use marker is good across installs. 8709 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8710 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8711 for (int i = 0; i < childCount; i++) { 8712 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8713 } 8714 } 8715 8716 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8717 try { 8718 mInstaller.clearAppProfiles(pkg.packageName); 8719 } catch (InstallerException e) { 8720 Slog.w(TAG, String.valueOf(e)); 8721 } 8722 } 8723 8724 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8725 long lastUpdateTime) { 8726 // Set parent install/update time 8727 PackageSetting ps = (PackageSetting) pkg.mExtras; 8728 if (ps != null) { 8729 ps.firstInstallTime = firstInstallTime; 8730 ps.lastUpdateTime = lastUpdateTime; 8731 } 8732 // Set children install/update time 8733 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8734 for (int i = 0; i < childCount; i++) { 8735 PackageParser.Package childPkg = pkg.childPackages.get(i); 8736 ps = (PackageSetting) childPkg.mExtras; 8737 if (ps != null) { 8738 ps.firstInstallTime = firstInstallTime; 8739 ps.lastUpdateTime = lastUpdateTime; 8740 } 8741 } 8742 } 8743 8744 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8745 PackageParser.Package changingLib) { 8746 if (file.path != null) { 8747 usesLibraryFiles.add(file.path); 8748 return; 8749 } 8750 PackageParser.Package p = mPackages.get(file.apk); 8751 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8752 // If we are doing this while in the middle of updating a library apk, 8753 // then we need to make sure to use that new apk for determining the 8754 // dependencies here. (We haven't yet finished committing the new apk 8755 // to the package manager state.) 8756 if (p == null || p.packageName.equals(changingLib.packageName)) { 8757 p = changingLib; 8758 } 8759 } 8760 if (p != null) { 8761 usesLibraryFiles.addAll(p.getAllCodePaths()); 8762 } 8763 } 8764 8765 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8766 PackageParser.Package changingLib) throws PackageManagerException { 8767 if (pkg == null) { 8768 return; 8769 } 8770 ArraySet<String> usesLibraryFiles = null; 8771 if (pkg.usesLibraries != null) { 8772 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8773 null, null, pkg.packageName, changingLib, true, null); 8774 } 8775 if (pkg.usesStaticLibraries != null) { 8776 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8777 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8778 pkg.packageName, changingLib, true, usesLibraryFiles); 8779 } 8780 if (pkg.usesOptionalLibraries != null) { 8781 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8782 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8783 } 8784 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8785 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8786 } else { 8787 pkg.usesLibraryFiles = null; 8788 } 8789 } 8790 8791 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8792 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8793 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8794 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8795 throws PackageManagerException { 8796 final int libCount = requestedLibraries.size(); 8797 for (int i = 0; i < libCount; i++) { 8798 final String libName = requestedLibraries.get(i); 8799 final int libVersion = requiredVersions != null ? requiredVersions[i] 8800 : SharedLibraryInfo.VERSION_UNDEFINED; 8801 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8802 if (libEntry == null) { 8803 if (required) { 8804 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8805 "Package " + packageName + " requires unavailable shared library " 8806 + libName + "; failing!"); 8807 } else { 8808 Slog.w(TAG, "Package " + packageName 8809 + " desires unavailable shared library " 8810 + libName + "; ignoring!"); 8811 } 8812 } else { 8813 if (requiredVersions != null && requiredCertDigests != null) { 8814 if (libEntry.info.getVersion() != requiredVersions[i]) { 8815 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8816 "Package " + packageName + " requires unavailable static shared" 8817 + " library " + libName + " version " 8818 + libEntry.info.getVersion() + "; failing!"); 8819 } 8820 8821 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8822 if (libPkg == null) { 8823 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8824 "Package " + packageName + " requires unavailable static shared" 8825 + " library; failing!"); 8826 } 8827 8828 String expectedCertDigest = requiredCertDigests[i]; 8829 String libCertDigest = PackageUtils.computeCertSha256Digest( 8830 libPkg.mSignatures[0]); 8831 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8832 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8833 "Package " + packageName + " requires differently signed" + 8834 " static shared library; failing!"); 8835 } 8836 } 8837 8838 if (outUsedLibraries == null) { 8839 outUsedLibraries = new ArraySet<>(); 8840 } 8841 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8842 } 8843 } 8844 return outUsedLibraries; 8845 } 8846 8847 private static boolean hasString(List<String> list, List<String> which) { 8848 if (list == null) { 8849 return false; 8850 } 8851 for (int i=list.size()-1; i>=0; i--) { 8852 for (int j=which.size()-1; j>=0; j--) { 8853 if (which.get(j).equals(list.get(i))) { 8854 return true; 8855 } 8856 } 8857 } 8858 return false; 8859 } 8860 8861 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8862 PackageParser.Package changingPkg) { 8863 ArrayList<PackageParser.Package> res = null; 8864 for (PackageParser.Package pkg : mPackages.values()) { 8865 if (changingPkg != null 8866 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8867 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8868 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8869 changingPkg.staticSharedLibName)) { 8870 return null; 8871 } 8872 if (res == null) { 8873 res = new ArrayList<>(); 8874 } 8875 res.add(pkg); 8876 try { 8877 updateSharedLibrariesLPr(pkg, changingPkg); 8878 } catch (PackageManagerException e) { 8879 // If a system app update or an app and a required lib missing we 8880 // delete the package and for updated system apps keep the data as 8881 // it is better for the user to reinstall than to be in an limbo 8882 // state. Also libs disappearing under an app should never happen 8883 // - just in case. 8884 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8885 final int flags = pkg.isUpdatedSystemApp() 8886 ? PackageManager.DELETE_KEEP_DATA : 0; 8887 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8888 flags , null, true, null); 8889 } 8890 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8891 } 8892 } 8893 return res; 8894 } 8895 8896 /** 8897 * Derive the value of the {@code cpuAbiOverride} based on the provided 8898 * value and an optional stored value from the package settings. 8899 */ 8900 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8901 String cpuAbiOverride = null; 8902 8903 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8904 cpuAbiOverride = null; 8905 } else if (abiOverride != null) { 8906 cpuAbiOverride = abiOverride; 8907 } else if (settings != null) { 8908 cpuAbiOverride = settings.cpuAbiOverrideString; 8909 } 8910 8911 return cpuAbiOverride; 8912 } 8913 8914 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8915 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8916 throws PackageManagerException { 8917 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8918 // If the package has children and this is the first dive in the function 8919 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8920 // whether all packages (parent and children) would be successfully scanned 8921 // before the actual scan since scanning mutates internal state and we want 8922 // to atomically install the package and its children. 8923 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8924 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8925 scanFlags |= SCAN_CHECK_ONLY; 8926 } 8927 } else { 8928 scanFlags &= ~SCAN_CHECK_ONLY; 8929 } 8930 8931 final PackageParser.Package scannedPkg; 8932 try { 8933 // Scan the parent 8934 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8935 // Scan the children 8936 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8937 for (int i = 0; i < childCount; i++) { 8938 PackageParser.Package childPkg = pkg.childPackages.get(i); 8939 scanPackageLI(childPkg, policyFlags, 8940 scanFlags, currentTime, user); 8941 } 8942 } finally { 8943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8944 } 8945 8946 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8947 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8948 } 8949 8950 return scannedPkg; 8951 } 8952 8953 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8954 int scanFlags, long currentTime, @Nullable UserHandle user) 8955 throws PackageManagerException { 8956 boolean success = false; 8957 try { 8958 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8959 currentTime, user); 8960 success = true; 8961 return res; 8962 } finally { 8963 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8964 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8965 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8966 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8967 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8968 } 8969 } 8970 } 8971 8972 /** 8973 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8974 */ 8975 private static boolean apkHasCode(String fileName) { 8976 StrictJarFile jarFile = null; 8977 try { 8978 jarFile = new StrictJarFile(fileName, 8979 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8980 return jarFile.findEntry("classes.dex") != null; 8981 } catch (IOException ignore) { 8982 } finally { 8983 try { 8984 if (jarFile != null) { 8985 jarFile.close(); 8986 } 8987 } catch (IOException ignore) {} 8988 } 8989 return false; 8990 } 8991 8992 /** 8993 * Enforces code policy for the package. This ensures that if an APK has 8994 * declared hasCode="true" in its manifest that the APK actually contains 8995 * code. 8996 * 8997 * @throws PackageManagerException If bytecode could not be found when it should exist 8998 */ 8999 private static void assertCodePolicy(PackageParser.Package pkg) 9000 throws PackageManagerException { 9001 final boolean shouldHaveCode = 9002 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9003 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9004 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9005 "Package " + pkg.baseCodePath + " code is missing"); 9006 } 9007 9008 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9009 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9010 final boolean splitShouldHaveCode = 9011 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9012 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9013 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9014 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9015 } 9016 } 9017 } 9018 } 9019 9020 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9021 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9022 throws PackageManagerException { 9023 if (DEBUG_PACKAGE_SCANNING) { 9024 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9025 Log.d(TAG, "Scanning package " + pkg.packageName); 9026 } 9027 9028 applyPolicy(pkg, policyFlags); 9029 9030 assertPackageIsValid(pkg, policyFlags, scanFlags); 9031 9032 // Initialize package source and resource directories 9033 final File scanFile = new File(pkg.codePath); 9034 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9035 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9036 9037 SharedUserSetting suid = null; 9038 PackageSetting pkgSetting = null; 9039 9040 // Getting the package setting may have a side-effect, so if we 9041 // are only checking if scan would succeed, stash a copy of the 9042 // old setting to restore at the end. 9043 PackageSetting nonMutatedPs = null; 9044 9045 // We keep references to the derived CPU Abis from settings in oder to reuse 9046 // them in the case where we're not upgrading or booting for the first time. 9047 String primaryCpuAbiFromSettings = null; 9048 String secondaryCpuAbiFromSettings = null; 9049 9050 // writer 9051 synchronized (mPackages) { 9052 if (pkg.mSharedUserId != null) { 9053 // SIDE EFFECTS; may potentially allocate a new shared user 9054 suid = mSettings.getSharedUserLPw( 9055 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9056 if (DEBUG_PACKAGE_SCANNING) { 9057 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9058 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9059 + "): packages=" + suid.packages); 9060 } 9061 } 9062 9063 // Check if we are renaming from an original package name. 9064 PackageSetting origPackage = null; 9065 String realName = null; 9066 if (pkg.mOriginalPackages != null) { 9067 // This package may need to be renamed to a previously 9068 // installed name. Let's check on that... 9069 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9070 if (pkg.mOriginalPackages.contains(renamed)) { 9071 // This package had originally been installed as the 9072 // original name, and we have already taken care of 9073 // transitioning to the new one. Just update the new 9074 // one to continue using the old name. 9075 realName = pkg.mRealPackage; 9076 if (!pkg.packageName.equals(renamed)) { 9077 // Callers into this function may have already taken 9078 // care of renaming the package; only do it here if 9079 // it is not already done. 9080 pkg.setPackageName(renamed); 9081 } 9082 } else { 9083 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9084 if ((origPackage = mSettings.getPackageLPr( 9085 pkg.mOriginalPackages.get(i))) != null) { 9086 // We do have the package already installed under its 9087 // original name... should we use it? 9088 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9089 // New package is not compatible with original. 9090 origPackage = null; 9091 continue; 9092 } else if (origPackage.sharedUser != null) { 9093 // Make sure uid is compatible between packages. 9094 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9095 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9096 + " to " + pkg.packageName + ": old uid " 9097 + origPackage.sharedUser.name 9098 + " differs from " + pkg.mSharedUserId); 9099 origPackage = null; 9100 continue; 9101 } 9102 // TODO: Add case when shared user id is added [b/28144775] 9103 } else { 9104 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9105 + pkg.packageName + " to old name " + origPackage.name); 9106 } 9107 break; 9108 } 9109 } 9110 } 9111 } 9112 9113 if (mTransferedPackages.contains(pkg.packageName)) { 9114 Slog.w(TAG, "Package " + pkg.packageName 9115 + " was transferred to another, but its .apk remains"); 9116 } 9117 9118 // See comments in nonMutatedPs declaration 9119 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9120 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9121 if (foundPs != null) { 9122 nonMutatedPs = new PackageSetting(foundPs); 9123 } 9124 } 9125 9126 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9127 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9128 if (foundPs != null) { 9129 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9130 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9131 } 9132 } 9133 9134 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9135 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9136 PackageManagerService.reportSettingsProblem(Log.WARN, 9137 "Package " + pkg.packageName + " shared user changed from " 9138 + (pkgSetting.sharedUser != null 9139 ? pkgSetting.sharedUser.name : "<nothing>") 9140 + " to " 9141 + (suid != null ? suid.name : "<nothing>") 9142 + "; replacing with new"); 9143 pkgSetting = null; 9144 } 9145 final PackageSetting oldPkgSetting = 9146 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9147 final PackageSetting disabledPkgSetting = 9148 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9149 9150 String[] usesStaticLibraries = null; 9151 if (pkg.usesStaticLibraries != null) { 9152 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9153 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9154 } 9155 9156 if (pkgSetting == null) { 9157 final String parentPackageName = (pkg.parentPackage != null) 9158 ? pkg.parentPackage.packageName : null; 9159 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9160 // REMOVE SharedUserSetting from method; update in a separate call 9161 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9162 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9163 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9164 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9165 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9166 true /*allowInstall*/, instantApp, parentPackageName, 9167 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9168 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9169 // SIDE EFFECTS; updates system state; move elsewhere 9170 if (origPackage != null) { 9171 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9172 } 9173 mSettings.addUserToSettingLPw(pkgSetting); 9174 } else { 9175 // REMOVE SharedUserSetting from method; update in a separate call. 9176 // 9177 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9178 // secondaryCpuAbi are not known at this point so we always update them 9179 // to null here, only to reset them at a later point. 9180 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9181 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9182 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9183 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9184 UserManagerService.getInstance(), usesStaticLibraries, 9185 pkg.usesStaticLibrariesVersions); 9186 } 9187 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9188 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9189 9190 // SIDE EFFECTS; modifies system state; move elsewhere 9191 if (pkgSetting.origPackage != null) { 9192 // If we are first transitioning from an original package, 9193 // fix up the new package's name now. We need to do this after 9194 // looking up the package under its new name, so getPackageLP 9195 // can take care of fiddling things correctly. 9196 pkg.setPackageName(origPackage.name); 9197 9198 // File a report about this. 9199 String msg = "New package " + pkgSetting.realName 9200 + " renamed to replace old package " + pkgSetting.name; 9201 reportSettingsProblem(Log.WARN, msg); 9202 9203 // Make a note of it. 9204 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9205 mTransferedPackages.add(origPackage.name); 9206 } 9207 9208 // No longer need to retain this. 9209 pkgSetting.origPackage = null; 9210 } 9211 9212 // SIDE EFFECTS; modifies system state; move elsewhere 9213 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9214 // Make a note of it. 9215 mTransferedPackages.add(pkg.packageName); 9216 } 9217 9218 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9219 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9220 } 9221 9222 if ((scanFlags & SCAN_BOOTING) == 0 9223 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9224 // Check all shared libraries and map to their actual file path. 9225 // We only do this here for apps not on a system dir, because those 9226 // are the only ones that can fail an install due to this. We 9227 // will take care of the system apps by updating all of their 9228 // library paths after the scan is done. Also during the initial 9229 // scan don't update any libs as we do this wholesale after all 9230 // apps are scanned to avoid dependency based scanning. 9231 updateSharedLibrariesLPr(pkg, null); 9232 } 9233 9234 if (mFoundPolicyFile) { 9235 SELinuxMMAC.assignSeInfoValue(pkg); 9236 } 9237 pkg.applicationInfo.uid = pkgSetting.appId; 9238 pkg.mExtras = pkgSetting; 9239 9240 9241 // Static shared libs have same package with different versions where 9242 // we internally use a synthetic package name to allow multiple versions 9243 // of the same package, therefore we need to compare signatures against 9244 // the package setting for the latest library version. 9245 PackageSetting signatureCheckPs = pkgSetting; 9246 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9247 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9248 if (libraryEntry != null) { 9249 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9250 } 9251 } 9252 9253 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9254 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9255 // We just determined the app is signed correctly, so bring 9256 // over the latest parsed certs. 9257 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9258 } else { 9259 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9260 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9261 "Package " + pkg.packageName + " upgrade keys do not match the " 9262 + "previously installed version"); 9263 } else { 9264 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9265 String msg = "System package " + pkg.packageName 9266 + " signature changed; retaining data."; 9267 reportSettingsProblem(Log.WARN, msg); 9268 } 9269 } 9270 } else { 9271 try { 9272 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9273 verifySignaturesLP(signatureCheckPs, pkg); 9274 // We just determined the app is signed correctly, so bring 9275 // over the latest parsed certs. 9276 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9277 } catch (PackageManagerException e) { 9278 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9279 throw e; 9280 } 9281 // The signature has changed, but this package is in the system 9282 // image... let's recover! 9283 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9284 // However... if this package is part of a shared user, but it 9285 // doesn't match the signature of the shared user, let's fail. 9286 // What this means is that you can't change the signatures 9287 // associated with an overall shared user, which doesn't seem all 9288 // that unreasonable. 9289 if (signatureCheckPs.sharedUser != null) { 9290 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9291 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9292 throw new PackageManagerException( 9293 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9294 "Signature mismatch for shared user: " 9295 + pkgSetting.sharedUser); 9296 } 9297 } 9298 // File a report about this. 9299 String msg = "System package " + pkg.packageName 9300 + " signature changed; retaining data."; 9301 reportSettingsProblem(Log.WARN, msg); 9302 } 9303 } 9304 9305 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9306 // This package wants to adopt ownership of permissions from 9307 // another package. 9308 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9309 final String origName = pkg.mAdoptPermissions.get(i); 9310 final PackageSetting orig = mSettings.getPackageLPr(origName); 9311 if (orig != null) { 9312 if (verifyPackageUpdateLPr(orig, pkg)) { 9313 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9314 + pkg.packageName); 9315 // SIDE EFFECTS; updates permissions system state; move elsewhere 9316 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9317 } 9318 } 9319 } 9320 } 9321 } 9322 9323 pkg.applicationInfo.processName = fixProcessName( 9324 pkg.applicationInfo.packageName, 9325 pkg.applicationInfo.processName); 9326 9327 if (pkg != mPlatformPackage) { 9328 // Get all of our default paths setup 9329 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9330 } 9331 9332 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9333 9334 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9335 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9337 derivePackageAbi( 9338 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9340 9341 // Some system apps still use directory structure for native libraries 9342 // in which case we might end up not detecting abi solely based on apk 9343 // structure. Try to detect abi based on directory structure. 9344 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9345 pkg.applicationInfo.primaryCpuAbi == null) { 9346 setBundledAppAbisAndRoots(pkg, pkgSetting); 9347 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9348 } 9349 } else { 9350 // This is not a first boot or an upgrade, don't bother deriving the 9351 // ABI during the scan. Instead, trust the value that was stored in the 9352 // package setting. 9353 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9354 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9355 9356 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9357 9358 if (DEBUG_ABI_SELECTION) { 9359 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9360 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9361 pkg.applicationInfo.secondaryCpuAbi); 9362 } 9363 } 9364 } else { 9365 if ((scanFlags & SCAN_MOVE) != 0) { 9366 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9367 // but we already have this packages package info in the PackageSetting. We just 9368 // use that and derive the native library path based on the new codepath. 9369 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9370 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9371 } 9372 9373 // Set native library paths again. For moves, the path will be updated based on the 9374 // ABIs we've determined above. For non-moves, the path will be updated based on the 9375 // ABIs we determined during compilation, but the path will depend on the final 9376 // package path (after the rename away from the stage path). 9377 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9378 } 9379 9380 // This is a special case for the "system" package, where the ABI is 9381 // dictated by the zygote configuration (and init.rc). We should keep track 9382 // of this ABI so that we can deal with "normal" applications that run under 9383 // the same UID correctly. 9384 if (mPlatformPackage == pkg) { 9385 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9386 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9387 } 9388 9389 // If there's a mismatch between the abi-override in the package setting 9390 // and the abiOverride specified for the install. Warn about this because we 9391 // would've already compiled the app without taking the package setting into 9392 // account. 9393 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9394 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9395 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9396 " for package " + pkg.packageName); 9397 } 9398 } 9399 9400 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9401 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9402 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9403 9404 // Copy the derived override back to the parsed package, so that we can 9405 // update the package settings accordingly. 9406 pkg.cpuAbiOverride = cpuAbiOverride; 9407 9408 if (DEBUG_ABI_SELECTION) { 9409 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9410 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9411 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9412 } 9413 9414 // Push the derived path down into PackageSettings so we know what to 9415 // clean up at uninstall time. 9416 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9417 9418 if (DEBUG_ABI_SELECTION) { 9419 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9420 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9421 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9422 } 9423 9424 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9425 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9426 // We don't do this here during boot because we can do it all 9427 // at once after scanning all existing packages. 9428 // 9429 // We also do this *before* we perform dexopt on this package, so that 9430 // we can avoid redundant dexopts, and also to make sure we've got the 9431 // code and package path correct. 9432 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9433 } 9434 9435 if (mFactoryTest && pkg.requestedPermissions.contains( 9436 android.Manifest.permission.FACTORY_TEST)) { 9437 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9438 } 9439 9440 if (isSystemApp(pkg)) { 9441 pkgSetting.isOrphaned = true; 9442 } 9443 9444 // Take care of first install / last update times. 9445 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9446 if (currentTime != 0) { 9447 if (pkgSetting.firstInstallTime == 0) { 9448 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9449 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9450 pkgSetting.lastUpdateTime = currentTime; 9451 } 9452 } else if (pkgSetting.firstInstallTime == 0) { 9453 // We need *something*. Take time time stamp of the file. 9454 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9455 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9456 if (scanFileTime != pkgSetting.timeStamp) { 9457 // A package on the system image has changed; consider this 9458 // to be an update. 9459 pkgSetting.lastUpdateTime = scanFileTime; 9460 } 9461 } 9462 pkgSetting.setTimeStamp(scanFileTime); 9463 9464 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9465 if (nonMutatedPs != null) { 9466 synchronized (mPackages) { 9467 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9468 } 9469 } 9470 } else { 9471 final int userId = user == null ? 0 : user.getIdentifier(); 9472 // Modify state for the given package setting 9473 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9474 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9475 if (pkgSetting.getInstantApp(userId)) { 9476 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9477 } 9478 } 9479 return pkg; 9480 } 9481 9482 /** 9483 * Applies policy to the parsed package based upon the given policy flags. 9484 * Ensures the package is in a good state. 9485 * <p> 9486 * Implementation detail: This method must NOT have any side effect. It would 9487 * ideally be static, but, it requires locks to read system state. 9488 */ 9489 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9490 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9491 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9492 if (pkg.applicationInfo.isDirectBootAware()) { 9493 // we're direct boot aware; set for all components 9494 for (PackageParser.Service s : pkg.services) { 9495 s.info.encryptionAware = s.info.directBootAware = true; 9496 } 9497 for (PackageParser.Provider p : pkg.providers) { 9498 p.info.encryptionAware = p.info.directBootAware = true; 9499 } 9500 for (PackageParser.Activity a : pkg.activities) { 9501 a.info.encryptionAware = a.info.directBootAware = true; 9502 } 9503 for (PackageParser.Activity r : pkg.receivers) { 9504 r.info.encryptionAware = r.info.directBootAware = true; 9505 } 9506 } 9507 } else { 9508 // Only allow system apps to be flagged as core apps. 9509 pkg.coreApp = false; 9510 // clear flags not applicable to regular apps 9511 pkg.applicationInfo.privateFlags &= 9512 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9513 pkg.applicationInfo.privateFlags &= 9514 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9515 } 9516 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9517 9518 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9519 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9520 } 9521 9522 if (!isSystemApp(pkg)) { 9523 // Only system apps can use these features. 9524 pkg.mOriginalPackages = null; 9525 pkg.mRealPackage = null; 9526 pkg.mAdoptPermissions = null; 9527 } 9528 } 9529 9530 /** 9531 * Asserts the parsed package is valid according to the given policy. If the 9532 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9533 * <p> 9534 * Implementation detail: This method must NOT have any side effects. It would 9535 * ideally be static, but, it requires locks to read system state. 9536 * 9537 * @throws PackageManagerException If the package fails any of the validation checks 9538 */ 9539 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9540 throws PackageManagerException { 9541 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9542 assertCodePolicy(pkg); 9543 } 9544 9545 if (pkg.applicationInfo.getCodePath() == null || 9546 pkg.applicationInfo.getResourcePath() == null) { 9547 // Bail out. The resource and code paths haven't been set. 9548 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9549 "Code and resource paths haven't been set correctly"); 9550 } 9551 9552 // Make sure we're not adding any bogus keyset info 9553 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9554 ksms.assertScannedPackageValid(pkg); 9555 9556 synchronized (mPackages) { 9557 // The special "android" package can only be defined once 9558 if (pkg.packageName.equals("android")) { 9559 if (mAndroidApplication != null) { 9560 Slog.w(TAG, "*************************************************"); 9561 Slog.w(TAG, "Core android package being redefined. Skipping."); 9562 Slog.w(TAG, " codePath=" + pkg.codePath); 9563 Slog.w(TAG, "*************************************************"); 9564 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9565 "Core android package being redefined. Skipping."); 9566 } 9567 } 9568 9569 // A package name must be unique; don't allow duplicates 9570 if (mPackages.containsKey(pkg.packageName)) { 9571 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9572 "Application package " + pkg.packageName 9573 + " already installed. Skipping duplicate."); 9574 } 9575 9576 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9577 // Static libs have a synthetic package name containing the version 9578 // but we still want the base name to be unique. 9579 if (mPackages.containsKey(pkg.manifestPackageName)) { 9580 throw new PackageManagerException( 9581 "Duplicate static shared lib provider package"); 9582 } 9583 9584 // Static shared libraries should have at least O target SDK 9585 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9586 throw new PackageManagerException( 9587 "Packages declaring static-shared libs must target O SDK or higher"); 9588 } 9589 9590 // Package declaring static a shared lib cannot be instant apps 9591 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9592 throw new PackageManagerException( 9593 "Packages declaring static-shared libs cannot be instant apps"); 9594 } 9595 9596 // Package declaring static a shared lib cannot be renamed since the package 9597 // name is synthetic and apps can't code around package manager internals. 9598 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9599 throw new PackageManagerException( 9600 "Packages declaring static-shared libs cannot be renamed"); 9601 } 9602 9603 // Package declaring static a shared lib cannot declare child packages 9604 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9605 throw new PackageManagerException( 9606 "Packages declaring static-shared libs cannot have child packages"); 9607 } 9608 9609 // Package declaring static a shared lib cannot declare dynamic libs 9610 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9611 throw new PackageManagerException( 9612 "Packages declaring static-shared libs cannot declare dynamic libs"); 9613 } 9614 9615 // Package declaring static a shared lib cannot declare shared users 9616 if (pkg.mSharedUserId != null) { 9617 throw new PackageManagerException( 9618 "Packages declaring static-shared libs cannot declare shared users"); 9619 } 9620 9621 // Static shared libs cannot declare activities 9622 if (!pkg.activities.isEmpty()) { 9623 throw new PackageManagerException( 9624 "Static shared libs cannot declare activities"); 9625 } 9626 9627 // Static shared libs cannot declare services 9628 if (!pkg.services.isEmpty()) { 9629 throw new PackageManagerException( 9630 "Static shared libs cannot declare services"); 9631 } 9632 9633 // Static shared libs cannot declare providers 9634 if (!pkg.providers.isEmpty()) { 9635 throw new PackageManagerException( 9636 "Static shared libs cannot declare content providers"); 9637 } 9638 9639 // Static shared libs cannot declare receivers 9640 if (!pkg.receivers.isEmpty()) { 9641 throw new PackageManagerException( 9642 "Static shared libs cannot declare broadcast receivers"); 9643 } 9644 9645 // Static shared libs cannot declare permission groups 9646 if (!pkg.permissionGroups.isEmpty()) { 9647 throw new PackageManagerException( 9648 "Static shared libs cannot declare permission groups"); 9649 } 9650 9651 // Static shared libs cannot declare permissions 9652 if (!pkg.permissions.isEmpty()) { 9653 throw new PackageManagerException( 9654 "Static shared libs cannot declare permissions"); 9655 } 9656 9657 // Static shared libs cannot declare protected broadcasts 9658 if (pkg.protectedBroadcasts != null) { 9659 throw new PackageManagerException( 9660 "Static shared libs cannot declare protected broadcasts"); 9661 } 9662 9663 // Static shared libs cannot be overlay targets 9664 if (pkg.mOverlayTarget != null) { 9665 throw new PackageManagerException( 9666 "Static shared libs cannot be overlay targets"); 9667 } 9668 9669 // The version codes must be ordered as lib versions 9670 int minVersionCode = Integer.MIN_VALUE; 9671 int maxVersionCode = Integer.MAX_VALUE; 9672 9673 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9674 pkg.staticSharedLibName); 9675 if (versionedLib != null) { 9676 final int versionCount = versionedLib.size(); 9677 for (int i = 0; i < versionCount; i++) { 9678 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9679 // TODO: We will change version code to long, so in the new API it is long 9680 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9681 .getVersionCode(); 9682 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9683 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9684 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9685 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9686 } else { 9687 minVersionCode = maxVersionCode = libVersionCode; 9688 break; 9689 } 9690 } 9691 } 9692 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9693 throw new PackageManagerException("Static shared" 9694 + " lib version codes must be ordered as lib versions"); 9695 } 9696 } 9697 9698 // Only privileged apps and updated privileged apps can add child packages. 9699 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9700 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9701 throw new PackageManagerException("Only privileged apps can add child " 9702 + "packages. Ignoring package " + pkg.packageName); 9703 } 9704 final int childCount = pkg.childPackages.size(); 9705 for (int i = 0; i < childCount; i++) { 9706 PackageParser.Package childPkg = pkg.childPackages.get(i); 9707 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9708 childPkg.packageName)) { 9709 throw new PackageManagerException("Can't override child of " 9710 + "another disabled app. Ignoring package " + pkg.packageName); 9711 } 9712 } 9713 } 9714 9715 // If we're only installing presumed-existing packages, require that the 9716 // scanned APK is both already known and at the path previously established 9717 // for it. Previously unknown packages we pick up normally, but if we have an 9718 // a priori expectation about this package's install presence, enforce it. 9719 // With a singular exception for new system packages. When an OTA contains 9720 // a new system package, we allow the codepath to change from a system location 9721 // to the user-installed location. If we don't allow this change, any newer, 9722 // user-installed version of the application will be ignored. 9723 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9724 if (mExpectingBetter.containsKey(pkg.packageName)) { 9725 logCriticalInfo(Log.WARN, 9726 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9727 } else { 9728 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9729 if (known != null) { 9730 if (DEBUG_PACKAGE_SCANNING) { 9731 Log.d(TAG, "Examining " + pkg.codePath 9732 + " and requiring known paths " + known.codePathString 9733 + " & " + known.resourcePathString); 9734 } 9735 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9736 || !pkg.applicationInfo.getResourcePath().equals( 9737 known.resourcePathString)) { 9738 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9739 "Application package " + pkg.packageName 9740 + " found at " + pkg.applicationInfo.getCodePath() 9741 + " but expected at " + known.codePathString 9742 + "; ignoring."); 9743 } 9744 } 9745 } 9746 } 9747 9748 // Verify that this new package doesn't have any content providers 9749 // that conflict with existing packages. Only do this if the 9750 // package isn't already installed, since we don't want to break 9751 // things that are installed. 9752 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9753 final int N = pkg.providers.size(); 9754 int i; 9755 for (i=0; i<N; i++) { 9756 PackageParser.Provider p = pkg.providers.get(i); 9757 if (p.info.authority != null) { 9758 String names[] = p.info.authority.split(";"); 9759 for (int j = 0; j < names.length; j++) { 9760 if (mProvidersByAuthority.containsKey(names[j])) { 9761 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9762 final String otherPackageName = 9763 ((other != null && other.getComponentName() != null) ? 9764 other.getComponentName().getPackageName() : "?"); 9765 throw new PackageManagerException( 9766 INSTALL_FAILED_CONFLICTING_PROVIDER, 9767 "Can't install because provider name " + names[j] 9768 + " (in package " + pkg.applicationInfo.packageName 9769 + ") is already used by " + otherPackageName); 9770 } 9771 } 9772 } 9773 } 9774 } 9775 } 9776 } 9777 9778 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9779 int type, String declaringPackageName, int declaringVersionCode) { 9780 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9781 if (versionedLib == null) { 9782 versionedLib = new SparseArray<>(); 9783 mSharedLibraries.put(name, versionedLib); 9784 if (type == SharedLibraryInfo.TYPE_STATIC) { 9785 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9786 } 9787 } else if (versionedLib.indexOfKey(version) >= 0) { 9788 return false; 9789 } 9790 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9791 version, type, declaringPackageName, declaringVersionCode); 9792 versionedLib.put(version, libEntry); 9793 return true; 9794 } 9795 9796 private boolean removeSharedLibraryLPw(String name, int version) { 9797 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9798 if (versionedLib == null) { 9799 return false; 9800 } 9801 final int libIdx = versionedLib.indexOfKey(version); 9802 if (libIdx < 0) { 9803 return false; 9804 } 9805 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9806 versionedLib.remove(version); 9807 if (versionedLib.size() <= 0) { 9808 mSharedLibraries.remove(name); 9809 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9810 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9811 .getPackageName()); 9812 } 9813 } 9814 return true; 9815 } 9816 9817 /** 9818 * Adds a scanned package to the system. When this method is finished, the package will 9819 * be available for query, resolution, etc... 9820 */ 9821 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9822 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9823 final String pkgName = pkg.packageName; 9824 if (mCustomResolverComponentName != null && 9825 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9826 setUpCustomResolverActivity(pkg); 9827 } 9828 9829 if (pkg.packageName.equals("android")) { 9830 synchronized (mPackages) { 9831 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9832 // Set up information for our fall-back user intent resolution activity. 9833 mPlatformPackage = pkg; 9834 pkg.mVersionCode = mSdkVersion; 9835 mAndroidApplication = pkg.applicationInfo; 9836 if (!mResolverReplaced) { 9837 mResolveActivity.applicationInfo = mAndroidApplication; 9838 mResolveActivity.name = ResolverActivity.class.getName(); 9839 mResolveActivity.packageName = mAndroidApplication.packageName; 9840 mResolveActivity.processName = "system:ui"; 9841 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9842 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9843 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9844 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9845 mResolveActivity.exported = true; 9846 mResolveActivity.enabled = true; 9847 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9848 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9849 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9850 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9851 | ActivityInfo.CONFIG_ORIENTATION 9852 | ActivityInfo.CONFIG_KEYBOARD 9853 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9854 mResolveInfo.activityInfo = mResolveActivity; 9855 mResolveInfo.priority = 0; 9856 mResolveInfo.preferredOrder = 0; 9857 mResolveInfo.match = 0; 9858 mResolveComponentName = new ComponentName( 9859 mAndroidApplication.packageName, mResolveActivity.name); 9860 } 9861 } 9862 } 9863 } 9864 9865 ArrayList<PackageParser.Package> clientLibPkgs = null; 9866 // writer 9867 synchronized (mPackages) { 9868 boolean hasStaticSharedLibs = false; 9869 9870 // Any app can add new static shared libraries 9871 if (pkg.staticSharedLibName != null) { 9872 // Static shared libs don't allow renaming as they have synthetic package 9873 // names to allow install of multiple versions, so use name from manifest. 9874 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9875 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9876 pkg.manifestPackageName, pkg.mVersionCode)) { 9877 hasStaticSharedLibs = true; 9878 } else { 9879 Slog.w(TAG, "Package " + pkg.packageName + " library " 9880 + pkg.staticSharedLibName + " already exists; skipping"); 9881 } 9882 // Static shared libs cannot be updated once installed since they 9883 // use synthetic package name which includes the version code, so 9884 // not need to update other packages's shared lib dependencies. 9885 } 9886 9887 if (!hasStaticSharedLibs 9888 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9889 // Only system apps can add new dynamic shared libraries. 9890 if (pkg.libraryNames != null) { 9891 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9892 String name = pkg.libraryNames.get(i); 9893 boolean allowed = false; 9894 if (pkg.isUpdatedSystemApp()) { 9895 // New library entries can only be added through the 9896 // system image. This is important to get rid of a lot 9897 // of nasty edge cases: for example if we allowed a non- 9898 // system update of the app to add a library, then uninstalling 9899 // the update would make the library go away, and assumptions 9900 // we made such as through app install filtering would now 9901 // have allowed apps on the device which aren't compatible 9902 // with it. Better to just have the restriction here, be 9903 // conservative, and create many fewer cases that can negatively 9904 // impact the user experience. 9905 final PackageSetting sysPs = mSettings 9906 .getDisabledSystemPkgLPr(pkg.packageName); 9907 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9908 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9909 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9910 allowed = true; 9911 break; 9912 } 9913 } 9914 } 9915 } else { 9916 allowed = true; 9917 } 9918 if (allowed) { 9919 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9920 SharedLibraryInfo.VERSION_UNDEFINED, 9921 SharedLibraryInfo.TYPE_DYNAMIC, 9922 pkg.packageName, pkg.mVersionCode)) { 9923 Slog.w(TAG, "Package " + pkg.packageName + " library " 9924 + name + " already exists; skipping"); 9925 } 9926 } else { 9927 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9928 + name + " that is not declared on system image; skipping"); 9929 } 9930 } 9931 9932 if ((scanFlags & SCAN_BOOTING) == 0) { 9933 // If we are not booting, we need to update any applications 9934 // that are clients of our shared library. If we are booting, 9935 // this will all be done once the scan is complete. 9936 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9937 } 9938 } 9939 } 9940 } 9941 9942 if ((scanFlags & SCAN_BOOTING) != 0) { 9943 // No apps can run during boot scan, so they don't need to be frozen 9944 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9945 // Caller asked to not kill app, so it's probably not frozen 9946 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9947 // Caller asked us to ignore frozen check for some reason; they 9948 // probably didn't know the package name 9949 } else { 9950 // We're doing major surgery on this package, so it better be frozen 9951 // right now to keep it from launching 9952 checkPackageFrozen(pkgName); 9953 } 9954 9955 // Also need to kill any apps that are dependent on the library. 9956 if (clientLibPkgs != null) { 9957 for (int i=0; i<clientLibPkgs.size(); i++) { 9958 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9959 killApplication(clientPkg.applicationInfo.packageName, 9960 clientPkg.applicationInfo.uid, "update lib"); 9961 } 9962 } 9963 9964 // writer 9965 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9966 9967 boolean createIdmapFailed = false; 9968 synchronized (mPackages) { 9969 // We don't expect installation to fail beyond this point 9970 9971 if (pkgSetting.pkg != null) { 9972 // Note that |user| might be null during the initial boot scan. If a codePath 9973 // for an app has changed during a boot scan, it's due to an app update that's 9974 // part of the system partition and marker changes must be applied to all users. 9975 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9976 final int[] userIds = resolveUserIds(userId); 9977 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9978 } 9979 9980 // Add the new setting to mSettings 9981 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9982 // Add the new setting to mPackages 9983 mPackages.put(pkg.applicationInfo.packageName, pkg); 9984 // Make sure we don't accidentally delete its data. 9985 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9986 while (iter.hasNext()) { 9987 PackageCleanItem item = iter.next(); 9988 if (pkgName.equals(item.packageName)) { 9989 iter.remove(); 9990 } 9991 } 9992 9993 // Add the package's KeySets to the global KeySetManagerService 9994 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9995 ksms.addScannedPackageLPw(pkg); 9996 9997 int N = pkg.providers.size(); 9998 StringBuilder r = null; 9999 int i; 10000 for (i=0; i<N; i++) { 10001 PackageParser.Provider p = pkg.providers.get(i); 10002 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10003 p.info.processName); 10004 mProviders.addProvider(p); 10005 p.syncable = p.info.isSyncable; 10006 if (p.info.authority != null) { 10007 String names[] = p.info.authority.split(";"); 10008 p.info.authority = null; 10009 for (int j = 0; j < names.length; j++) { 10010 if (j == 1 && p.syncable) { 10011 // We only want the first authority for a provider to possibly be 10012 // syncable, so if we already added this provider using a different 10013 // authority clear the syncable flag. We copy the provider before 10014 // changing it because the mProviders object contains a reference 10015 // to a provider that we don't want to change. 10016 // Only do this for the second authority since the resulting provider 10017 // object can be the same for all future authorities for this provider. 10018 p = new PackageParser.Provider(p); 10019 p.syncable = false; 10020 } 10021 if (!mProvidersByAuthority.containsKey(names[j])) { 10022 mProvidersByAuthority.put(names[j], p); 10023 if (p.info.authority == null) { 10024 p.info.authority = names[j]; 10025 } else { 10026 p.info.authority = p.info.authority + ";" + names[j]; 10027 } 10028 if (DEBUG_PACKAGE_SCANNING) { 10029 if (chatty) 10030 Log.d(TAG, "Registered content provider: " + names[j] 10031 + ", className = " + p.info.name + ", isSyncable = " 10032 + p.info.isSyncable); 10033 } 10034 } else { 10035 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10036 Slog.w(TAG, "Skipping provider name " + names[j] + 10037 " (in package " + pkg.applicationInfo.packageName + 10038 "): name already used by " 10039 + ((other != null && other.getComponentName() != null) 10040 ? other.getComponentName().getPackageName() : "?")); 10041 } 10042 } 10043 } 10044 if (chatty) { 10045 if (r == null) { 10046 r = new StringBuilder(256); 10047 } else { 10048 r.append(' '); 10049 } 10050 r.append(p.info.name); 10051 } 10052 } 10053 if (r != null) { 10054 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10055 } 10056 10057 N = pkg.services.size(); 10058 r = null; 10059 for (i=0; i<N; i++) { 10060 PackageParser.Service s = pkg.services.get(i); 10061 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10062 s.info.processName); 10063 mServices.addService(s); 10064 if (chatty) { 10065 if (r == null) { 10066 r = new StringBuilder(256); 10067 } else { 10068 r.append(' '); 10069 } 10070 r.append(s.info.name); 10071 } 10072 } 10073 if (r != null) { 10074 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10075 } 10076 10077 N = pkg.receivers.size(); 10078 r = null; 10079 for (i=0; i<N; i++) { 10080 PackageParser.Activity a = pkg.receivers.get(i); 10081 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10082 a.info.processName); 10083 mReceivers.addActivity(a, "receiver"); 10084 if (chatty) { 10085 if (r == null) { 10086 r = new StringBuilder(256); 10087 } else { 10088 r.append(' '); 10089 } 10090 r.append(a.info.name); 10091 } 10092 } 10093 if (r != null) { 10094 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10095 } 10096 10097 N = pkg.activities.size(); 10098 r = null; 10099 for (i=0; i<N; i++) { 10100 PackageParser.Activity a = pkg.activities.get(i); 10101 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10102 a.info.processName); 10103 mActivities.addActivity(a, "activity"); 10104 if (chatty) { 10105 if (r == null) { 10106 r = new StringBuilder(256); 10107 } else { 10108 r.append(' '); 10109 } 10110 r.append(a.info.name); 10111 } 10112 } 10113 if (r != null) { 10114 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10115 } 10116 10117 N = pkg.permissionGroups.size(); 10118 r = null; 10119 for (i=0; i<N; i++) { 10120 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10121 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10122 final String curPackageName = cur == null ? null : cur.info.packageName; 10123 // Dont allow ephemeral apps to define new permission groups. 10124 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10125 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10126 + pg.info.packageName 10127 + " ignored: instant apps cannot define new permission groups."); 10128 continue; 10129 } 10130 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10131 if (cur == null || isPackageUpdate) { 10132 mPermissionGroups.put(pg.info.name, pg); 10133 if (chatty) { 10134 if (r == null) { 10135 r = new StringBuilder(256); 10136 } else { 10137 r.append(' '); 10138 } 10139 if (isPackageUpdate) { 10140 r.append("UPD:"); 10141 } 10142 r.append(pg.info.name); 10143 } 10144 } else { 10145 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10146 + pg.info.packageName + " ignored: original from " 10147 + cur.info.packageName); 10148 if (chatty) { 10149 if (r == null) { 10150 r = new StringBuilder(256); 10151 } else { 10152 r.append(' '); 10153 } 10154 r.append("DUP:"); 10155 r.append(pg.info.name); 10156 } 10157 } 10158 } 10159 if (r != null) { 10160 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10161 } 10162 10163 N = pkg.permissions.size(); 10164 r = null; 10165 for (i=0; i<N; i++) { 10166 PackageParser.Permission p = pkg.permissions.get(i); 10167 10168 // Dont allow ephemeral apps to define new permissions. 10169 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10170 Slog.w(TAG, "Permission " + p.info.name + " from package " 10171 + p.info.packageName 10172 + " ignored: instant apps cannot define new permissions."); 10173 continue; 10174 } 10175 10176 // Assume by default that we did not install this permission into the system. 10177 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10178 10179 // Now that permission groups have a special meaning, we ignore permission 10180 // groups for legacy apps to prevent unexpected behavior. In particular, 10181 // permissions for one app being granted to someone just becase they happen 10182 // to be in a group defined by another app (before this had no implications). 10183 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10184 p.group = mPermissionGroups.get(p.info.group); 10185 // Warn for a permission in an unknown group. 10186 if (p.info.group != null && p.group == null) { 10187 Slog.w(TAG, "Permission " + p.info.name + " from package " 10188 + p.info.packageName + " in an unknown group " + p.info.group); 10189 } 10190 } 10191 10192 ArrayMap<String, BasePermission> permissionMap = 10193 p.tree ? mSettings.mPermissionTrees 10194 : mSettings.mPermissions; 10195 BasePermission bp = permissionMap.get(p.info.name); 10196 10197 // Allow system apps to redefine non-system permissions 10198 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10199 final boolean currentOwnerIsSystem = (bp.perm != null 10200 && isSystemApp(bp.perm.owner)); 10201 if (isSystemApp(p.owner)) { 10202 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10203 // It's a built-in permission and no owner, take ownership now 10204 bp.packageSetting = pkgSetting; 10205 bp.perm = p; 10206 bp.uid = pkg.applicationInfo.uid; 10207 bp.sourcePackage = p.info.packageName; 10208 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10209 } else if (!currentOwnerIsSystem) { 10210 String msg = "New decl " + p.owner + " of permission " 10211 + p.info.name + " is system; overriding " + bp.sourcePackage; 10212 reportSettingsProblem(Log.WARN, msg); 10213 bp = null; 10214 } 10215 } 10216 } 10217 10218 if (bp == null) { 10219 bp = new BasePermission(p.info.name, p.info.packageName, 10220 BasePermission.TYPE_NORMAL); 10221 permissionMap.put(p.info.name, bp); 10222 } 10223 10224 if (bp.perm == null) { 10225 if (bp.sourcePackage == null 10226 || bp.sourcePackage.equals(p.info.packageName)) { 10227 BasePermission tree = findPermissionTreeLP(p.info.name); 10228 if (tree == null 10229 || tree.sourcePackage.equals(p.info.packageName)) { 10230 bp.packageSetting = pkgSetting; 10231 bp.perm = p; 10232 bp.uid = pkg.applicationInfo.uid; 10233 bp.sourcePackage = p.info.packageName; 10234 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10235 if (chatty) { 10236 if (r == null) { 10237 r = new StringBuilder(256); 10238 } else { 10239 r.append(' '); 10240 } 10241 r.append(p.info.name); 10242 } 10243 } else { 10244 Slog.w(TAG, "Permission " + p.info.name + " from package " 10245 + p.info.packageName + " ignored: base tree " 10246 + tree.name + " is from package " 10247 + tree.sourcePackage); 10248 } 10249 } else { 10250 Slog.w(TAG, "Permission " + p.info.name + " from package " 10251 + p.info.packageName + " ignored: original from " 10252 + bp.sourcePackage); 10253 } 10254 } else if (chatty) { 10255 if (r == null) { 10256 r = new StringBuilder(256); 10257 } else { 10258 r.append(' '); 10259 } 10260 r.append("DUP:"); 10261 r.append(p.info.name); 10262 } 10263 if (bp.perm == p) { 10264 bp.protectionLevel = p.info.protectionLevel; 10265 } 10266 } 10267 10268 if (r != null) { 10269 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10270 } 10271 10272 N = pkg.instrumentation.size(); 10273 r = null; 10274 for (i=0; i<N; i++) { 10275 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10276 a.info.packageName = pkg.applicationInfo.packageName; 10277 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10278 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10279 a.info.splitNames = pkg.splitNames; 10280 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10281 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10282 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10283 a.info.dataDir = pkg.applicationInfo.dataDir; 10284 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10285 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10286 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10287 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10288 mInstrumentation.put(a.getComponentName(), a); 10289 if (chatty) { 10290 if (r == null) { 10291 r = new StringBuilder(256); 10292 } else { 10293 r.append(' '); 10294 } 10295 r.append(a.info.name); 10296 } 10297 } 10298 if (r != null) { 10299 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10300 } 10301 10302 if (pkg.protectedBroadcasts != null) { 10303 N = pkg.protectedBroadcasts.size(); 10304 for (i=0; i<N; i++) { 10305 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10306 } 10307 } 10308 10309 // Create idmap files for pairs of (packages, overlay packages). 10310 // Note: "android", ie framework-res.apk, is handled by native layers. 10311 if (pkg.mOverlayTarget != null) { 10312 // This is an overlay package. 10313 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10314 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10315 mOverlays.put(pkg.mOverlayTarget, 10316 new ArrayMap<String, PackageParser.Package>()); 10317 } 10318 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10319 map.put(pkg.packageName, pkg); 10320 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10321 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10322 createIdmapFailed = true; 10323 } 10324 } 10325 } else if (mOverlays.containsKey(pkg.packageName) && 10326 !pkg.packageName.equals("android")) { 10327 // This is a regular package, with one or more known overlay packages. 10328 createIdmapsForPackageLI(pkg); 10329 } 10330 } 10331 10332 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10333 10334 if (createIdmapFailed) { 10335 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10336 "scanPackageLI failed to createIdmap"); 10337 } 10338 } 10339 10340 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10341 PackageParser.Package update, int[] userIds) { 10342 if (existing.applicationInfo == null || update.applicationInfo == null) { 10343 // This isn't due to an app installation. 10344 return; 10345 } 10346 10347 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10348 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10349 10350 // The codePath hasn't changed, so there's nothing for us to do. 10351 if (Objects.equals(oldCodePath, newCodePath)) { 10352 return; 10353 } 10354 10355 File canonicalNewCodePath; 10356 try { 10357 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10358 } catch (IOException e) { 10359 Slog.w(TAG, "Failed to get canonical path.", e); 10360 return; 10361 } 10362 10363 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10364 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10365 // that the last component of the path (i.e, the name) doesn't need canonicalization 10366 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10367 // but may change in the future. Hopefully this function won't exist at that point. 10368 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10369 oldCodePath.getName()); 10370 10371 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10372 // with "@". 10373 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10374 if (!oldMarkerPrefix.endsWith("@")) { 10375 oldMarkerPrefix += "@"; 10376 } 10377 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10378 if (!newMarkerPrefix.endsWith("@")) { 10379 newMarkerPrefix += "@"; 10380 } 10381 10382 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10383 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10384 for (String updatedPath : updatedPaths) { 10385 String updatedPathName = new File(updatedPath).getName(); 10386 markerSuffixes.add(updatedPathName.replace('/', '@')); 10387 } 10388 10389 for (int userId : userIds) { 10390 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10391 10392 for (String markerSuffix : markerSuffixes) { 10393 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10394 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10395 if (oldForeignUseMark.exists()) { 10396 try { 10397 Os.rename(oldForeignUseMark.getAbsolutePath(), 10398 newForeignUseMark.getAbsolutePath()); 10399 } catch (ErrnoException e) { 10400 Slog.w(TAG, "Failed to rename foreign use marker", e); 10401 oldForeignUseMark.delete(); 10402 } 10403 } 10404 } 10405 } 10406 } 10407 10408 /** 10409 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10410 * is derived purely on the basis of the contents of {@code scanFile} and 10411 * {@code cpuAbiOverride}. 10412 * 10413 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10414 */ 10415 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10416 String cpuAbiOverride, boolean extractLibs, 10417 File appLib32InstallDir) 10418 throws PackageManagerException { 10419 // Give ourselves some initial paths; we'll come back for another 10420 // pass once we've determined ABI below. 10421 setNativeLibraryPaths(pkg, appLib32InstallDir); 10422 10423 // We would never need to extract libs for forward-locked and external packages, 10424 // since the container service will do it for us. We shouldn't attempt to 10425 // extract libs from system app when it was not updated. 10426 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10427 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10428 extractLibs = false; 10429 } 10430 10431 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10432 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10433 10434 NativeLibraryHelper.Handle handle = null; 10435 try { 10436 handle = NativeLibraryHelper.Handle.create(pkg); 10437 // TODO(multiArch): This can be null for apps that didn't go through the 10438 // usual installation process. We can calculate it again, like we 10439 // do during install time. 10440 // 10441 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10442 // unnecessary. 10443 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10444 10445 // Null out the abis so that they can be recalculated. 10446 pkg.applicationInfo.primaryCpuAbi = null; 10447 pkg.applicationInfo.secondaryCpuAbi = null; 10448 if (isMultiArch(pkg.applicationInfo)) { 10449 // Warn if we've set an abiOverride for multi-lib packages.. 10450 // By definition, we need to copy both 32 and 64 bit libraries for 10451 // such packages. 10452 if (pkg.cpuAbiOverride != null 10453 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10454 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10455 } 10456 10457 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10458 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10459 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10460 if (extractLibs) { 10461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10462 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10463 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10464 useIsaSpecificSubdirs); 10465 } else { 10466 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10467 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10468 } 10469 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10470 } 10471 10472 maybeThrowExceptionForMultiArchCopy( 10473 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10474 10475 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10476 if (extractLibs) { 10477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10478 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10479 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10480 useIsaSpecificSubdirs); 10481 } else { 10482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10483 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10484 } 10485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10486 } 10487 10488 maybeThrowExceptionForMultiArchCopy( 10489 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10490 10491 if (abi64 >= 0) { 10492 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10493 } 10494 10495 if (abi32 >= 0) { 10496 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10497 if (abi64 >= 0) { 10498 if (pkg.use32bitAbi) { 10499 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10500 pkg.applicationInfo.primaryCpuAbi = abi; 10501 } else { 10502 pkg.applicationInfo.secondaryCpuAbi = abi; 10503 } 10504 } else { 10505 pkg.applicationInfo.primaryCpuAbi = abi; 10506 } 10507 } 10508 10509 } else { 10510 String[] abiList = (cpuAbiOverride != null) ? 10511 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10512 10513 // Enable gross and lame hacks for apps that are built with old 10514 // SDK tools. We must scan their APKs for renderscript bitcode and 10515 // not launch them if it's present. Don't bother checking on devices 10516 // that don't have 64 bit support. 10517 boolean needsRenderScriptOverride = false; 10518 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10519 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10520 abiList = Build.SUPPORTED_32_BIT_ABIS; 10521 needsRenderScriptOverride = true; 10522 } 10523 10524 final int copyRet; 10525 if (extractLibs) { 10526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10527 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10528 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10529 } else { 10530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10531 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10532 } 10533 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10534 10535 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10536 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10537 "Error unpackaging native libs for app, errorCode=" + copyRet); 10538 } 10539 10540 if (copyRet >= 0) { 10541 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10542 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10543 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10544 } else if (needsRenderScriptOverride) { 10545 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10546 } 10547 } 10548 } catch (IOException ioe) { 10549 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10550 } finally { 10551 IoUtils.closeQuietly(handle); 10552 } 10553 10554 // Now that we've calculated the ABIs and determined if it's an internal app, 10555 // we will go ahead and populate the nativeLibraryPath. 10556 setNativeLibraryPaths(pkg, appLib32InstallDir); 10557 } 10558 10559 /** 10560 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10561 * i.e, so that all packages can be run inside a single process if required. 10562 * 10563 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10564 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10565 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10566 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10567 * updating a package that belongs to a shared user. 10568 * 10569 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10570 * adds unnecessary complexity. 10571 */ 10572 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10573 PackageParser.Package scannedPackage) { 10574 String requiredInstructionSet = null; 10575 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10576 requiredInstructionSet = VMRuntime.getInstructionSet( 10577 scannedPackage.applicationInfo.primaryCpuAbi); 10578 } 10579 10580 PackageSetting requirer = null; 10581 for (PackageSetting ps : packagesForUser) { 10582 // If packagesForUser contains scannedPackage, we skip it. This will happen 10583 // when scannedPackage is an update of an existing package. Without this check, 10584 // we will never be able to change the ABI of any package belonging to a shared 10585 // user, even if it's compatible with other packages. 10586 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10587 if (ps.primaryCpuAbiString == null) { 10588 continue; 10589 } 10590 10591 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10592 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10593 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10594 // this but there's not much we can do. 10595 String errorMessage = "Instruction set mismatch, " 10596 + ((requirer == null) ? "[caller]" : requirer) 10597 + " requires " + requiredInstructionSet + " whereas " + ps 10598 + " requires " + instructionSet; 10599 Slog.w(TAG, errorMessage); 10600 } 10601 10602 if (requiredInstructionSet == null) { 10603 requiredInstructionSet = instructionSet; 10604 requirer = ps; 10605 } 10606 } 10607 } 10608 10609 if (requiredInstructionSet != null) { 10610 String adjustedAbi; 10611 if (requirer != null) { 10612 // requirer != null implies that either scannedPackage was null or that scannedPackage 10613 // did not require an ABI, in which case we have to adjust scannedPackage to match 10614 // the ABI of the set (which is the same as requirer's ABI) 10615 adjustedAbi = requirer.primaryCpuAbiString; 10616 if (scannedPackage != null) { 10617 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10618 } 10619 } else { 10620 // requirer == null implies that we're updating all ABIs in the set to 10621 // match scannedPackage. 10622 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10623 } 10624 10625 for (PackageSetting ps : packagesForUser) { 10626 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10627 if (ps.primaryCpuAbiString != null) { 10628 continue; 10629 } 10630 10631 ps.primaryCpuAbiString = adjustedAbi; 10632 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10633 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10634 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10635 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10636 + " (requirer=" 10637 + (requirer == null ? "null" : requirer.pkg.packageName) 10638 + ", scannedPackage=" 10639 + (scannedPackage != null ? scannedPackage.packageName : "null") 10640 + ")"); 10641 try { 10642 mInstaller.rmdex(ps.codePathString, 10643 getDexCodeInstructionSet(getPreferredInstructionSet())); 10644 } catch (InstallerException ignored) { 10645 } 10646 } 10647 } 10648 } 10649 } 10650 } 10651 10652 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10653 synchronized (mPackages) { 10654 mResolverReplaced = true; 10655 // Set up information for custom user intent resolution activity. 10656 mResolveActivity.applicationInfo = pkg.applicationInfo; 10657 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10658 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10659 mResolveActivity.processName = pkg.applicationInfo.packageName; 10660 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10661 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10662 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10663 mResolveActivity.theme = 0; 10664 mResolveActivity.exported = true; 10665 mResolveActivity.enabled = true; 10666 mResolveInfo.activityInfo = mResolveActivity; 10667 mResolveInfo.priority = 0; 10668 mResolveInfo.preferredOrder = 0; 10669 mResolveInfo.match = 0; 10670 mResolveComponentName = mCustomResolverComponentName; 10671 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10672 mResolveComponentName); 10673 } 10674 } 10675 10676 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10677 if (installerComponent == null) { 10678 if (DEBUG_EPHEMERAL) { 10679 Slog.d(TAG, "Clear ephemeral installer activity"); 10680 } 10681 mInstantAppInstallerActivity.applicationInfo = null; 10682 return; 10683 } 10684 10685 if (DEBUG_EPHEMERAL) { 10686 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10687 } 10688 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10689 // Set up information for ephemeral installer activity 10690 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10691 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10692 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10693 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10694 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10695 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10696 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10697 mInstantAppInstallerActivity.theme = 0; 10698 mInstantAppInstallerActivity.exported = true; 10699 mInstantAppInstallerActivity.enabled = true; 10700 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10701 mInstantAppInstallerInfo.priority = 0; 10702 mInstantAppInstallerInfo.preferredOrder = 1; 10703 mInstantAppInstallerInfo.isDefault = true; 10704 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10705 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10706 } 10707 10708 private static String calculateBundledApkRoot(final String codePathString) { 10709 final File codePath = new File(codePathString); 10710 final File codeRoot; 10711 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10712 codeRoot = Environment.getRootDirectory(); 10713 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10714 codeRoot = Environment.getOemDirectory(); 10715 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10716 codeRoot = Environment.getVendorDirectory(); 10717 } else { 10718 // Unrecognized code path; take its top real segment as the apk root: 10719 // e.g. /something/app/blah.apk => /something 10720 try { 10721 File f = codePath.getCanonicalFile(); 10722 File parent = f.getParentFile(); // non-null because codePath is a file 10723 File tmp; 10724 while ((tmp = parent.getParentFile()) != null) { 10725 f = parent; 10726 parent = tmp; 10727 } 10728 codeRoot = f; 10729 Slog.w(TAG, "Unrecognized code path " 10730 + codePath + " - using " + codeRoot); 10731 } catch (IOException e) { 10732 // Can't canonicalize the code path -- shenanigans? 10733 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10734 return Environment.getRootDirectory().getPath(); 10735 } 10736 } 10737 return codeRoot.getPath(); 10738 } 10739 10740 /** 10741 * Derive and set the location of native libraries for the given package, 10742 * which varies depending on where and how the package was installed. 10743 */ 10744 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10745 final ApplicationInfo info = pkg.applicationInfo; 10746 final String codePath = pkg.codePath; 10747 final File codeFile = new File(codePath); 10748 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10749 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10750 10751 info.nativeLibraryRootDir = null; 10752 info.nativeLibraryRootRequiresIsa = false; 10753 info.nativeLibraryDir = null; 10754 info.secondaryNativeLibraryDir = null; 10755 10756 if (isApkFile(codeFile)) { 10757 // Monolithic install 10758 if (bundledApp) { 10759 // If "/system/lib64/apkname" exists, assume that is the per-package 10760 // native library directory to use; otherwise use "/system/lib/apkname". 10761 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10762 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10763 getPrimaryInstructionSet(info)); 10764 10765 // This is a bundled system app so choose the path based on the ABI. 10766 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10767 // is just the default path. 10768 final String apkName = deriveCodePathName(codePath); 10769 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10770 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10771 apkName).getAbsolutePath(); 10772 10773 if (info.secondaryCpuAbi != null) { 10774 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10775 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10776 secondaryLibDir, apkName).getAbsolutePath(); 10777 } 10778 } else if (asecApp) { 10779 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10780 .getAbsolutePath(); 10781 } else { 10782 final String apkName = deriveCodePathName(codePath); 10783 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10784 .getAbsolutePath(); 10785 } 10786 10787 info.nativeLibraryRootRequiresIsa = false; 10788 info.nativeLibraryDir = info.nativeLibraryRootDir; 10789 } else { 10790 // Cluster install 10791 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10792 info.nativeLibraryRootRequiresIsa = true; 10793 10794 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10795 getPrimaryInstructionSet(info)).getAbsolutePath(); 10796 10797 if (info.secondaryCpuAbi != null) { 10798 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10799 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10800 } 10801 } 10802 } 10803 10804 /** 10805 * Calculate the abis and roots for a bundled app. These can uniquely 10806 * be determined from the contents of the system partition, i.e whether 10807 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10808 * of this information, and instead assume that the system was built 10809 * sensibly. 10810 */ 10811 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10812 PackageSetting pkgSetting) { 10813 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10814 10815 // If "/system/lib64/apkname" exists, assume that is the per-package 10816 // native library directory to use; otherwise use "/system/lib/apkname". 10817 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10818 setBundledAppAbi(pkg, apkRoot, apkName); 10819 // pkgSetting might be null during rescan following uninstall of updates 10820 // to a bundled app, so accommodate that possibility. The settings in 10821 // that case will be established later from the parsed package. 10822 // 10823 // If the settings aren't null, sync them up with what we've just derived. 10824 // note that apkRoot isn't stored in the package settings. 10825 if (pkgSetting != null) { 10826 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10827 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10828 } 10829 } 10830 10831 /** 10832 * Deduces the ABI of a bundled app and sets the relevant fields on the 10833 * parsed pkg object. 10834 * 10835 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10836 * under which system libraries are installed. 10837 * @param apkName the name of the installed package. 10838 */ 10839 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10840 final File codeFile = new File(pkg.codePath); 10841 10842 final boolean has64BitLibs; 10843 final boolean has32BitLibs; 10844 if (isApkFile(codeFile)) { 10845 // Monolithic install 10846 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10847 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10848 } else { 10849 // Cluster install 10850 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10851 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10852 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10853 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10854 has64BitLibs = (new File(rootDir, isa)).exists(); 10855 } else { 10856 has64BitLibs = false; 10857 } 10858 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10859 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10860 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10861 has32BitLibs = (new File(rootDir, isa)).exists(); 10862 } else { 10863 has32BitLibs = false; 10864 } 10865 } 10866 10867 if (has64BitLibs && !has32BitLibs) { 10868 // The package has 64 bit libs, but not 32 bit libs. Its primary 10869 // ABI should be 64 bit. We can safely assume here that the bundled 10870 // native libraries correspond to the most preferred ABI in the list. 10871 10872 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10873 pkg.applicationInfo.secondaryCpuAbi = null; 10874 } else if (has32BitLibs && !has64BitLibs) { 10875 // The package has 32 bit libs but not 64 bit libs. Its primary 10876 // ABI should be 32 bit. 10877 10878 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10879 pkg.applicationInfo.secondaryCpuAbi = null; 10880 } else if (has32BitLibs && has64BitLibs) { 10881 // The application has both 64 and 32 bit bundled libraries. We check 10882 // here that the app declares multiArch support, and warn if it doesn't. 10883 // 10884 // We will be lenient here and record both ABIs. The primary will be the 10885 // ABI that's higher on the list, i.e, a device that's configured to prefer 10886 // 64 bit apps will see a 64 bit primary ABI, 10887 10888 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10889 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10890 } 10891 10892 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10893 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10894 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10895 } else { 10896 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10897 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10898 } 10899 } else { 10900 pkg.applicationInfo.primaryCpuAbi = null; 10901 pkg.applicationInfo.secondaryCpuAbi = null; 10902 } 10903 } 10904 10905 private void killApplication(String pkgName, int appId, String reason) { 10906 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10907 } 10908 10909 private void killApplication(String pkgName, int appId, int userId, String reason) { 10910 // Request the ActivityManager to kill the process(only for existing packages) 10911 // so that we do not end up in a confused state while the user is still using the older 10912 // version of the application while the new one gets installed. 10913 final long token = Binder.clearCallingIdentity(); 10914 try { 10915 IActivityManager am = ActivityManager.getService(); 10916 if (am != null) { 10917 try { 10918 am.killApplication(pkgName, appId, userId, reason); 10919 } catch (RemoteException e) { 10920 } 10921 } 10922 } finally { 10923 Binder.restoreCallingIdentity(token); 10924 } 10925 } 10926 10927 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10928 // Remove the parent package setting 10929 PackageSetting ps = (PackageSetting) pkg.mExtras; 10930 if (ps != null) { 10931 removePackageLI(ps, chatty); 10932 } 10933 // Remove the child package setting 10934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10935 for (int i = 0; i < childCount; i++) { 10936 PackageParser.Package childPkg = pkg.childPackages.get(i); 10937 ps = (PackageSetting) childPkg.mExtras; 10938 if (ps != null) { 10939 removePackageLI(ps, chatty); 10940 } 10941 } 10942 } 10943 10944 void removePackageLI(PackageSetting ps, boolean chatty) { 10945 if (DEBUG_INSTALL) { 10946 if (chatty) 10947 Log.d(TAG, "Removing package " + ps.name); 10948 } 10949 10950 // writer 10951 synchronized (mPackages) { 10952 mPackages.remove(ps.name); 10953 final PackageParser.Package pkg = ps.pkg; 10954 if (pkg != null) { 10955 cleanPackageDataStructuresLILPw(pkg, chatty); 10956 } 10957 } 10958 } 10959 10960 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10961 if (DEBUG_INSTALL) { 10962 if (chatty) 10963 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10964 } 10965 10966 // writer 10967 synchronized (mPackages) { 10968 // Remove the parent package 10969 mPackages.remove(pkg.applicationInfo.packageName); 10970 cleanPackageDataStructuresLILPw(pkg, chatty); 10971 10972 // Remove the child packages 10973 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10974 for (int i = 0; i < childCount; i++) { 10975 PackageParser.Package childPkg = pkg.childPackages.get(i); 10976 mPackages.remove(childPkg.applicationInfo.packageName); 10977 cleanPackageDataStructuresLILPw(childPkg, chatty); 10978 } 10979 } 10980 } 10981 10982 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10983 int N = pkg.providers.size(); 10984 StringBuilder r = null; 10985 int i; 10986 for (i=0; i<N; i++) { 10987 PackageParser.Provider p = pkg.providers.get(i); 10988 mProviders.removeProvider(p); 10989 if (p.info.authority == null) { 10990 10991 /* There was another ContentProvider with this authority when 10992 * this app was installed so this authority is null, 10993 * Ignore it as we don't have to unregister the provider. 10994 */ 10995 continue; 10996 } 10997 String names[] = p.info.authority.split(";"); 10998 for (int j = 0; j < names.length; j++) { 10999 if (mProvidersByAuthority.get(names[j]) == p) { 11000 mProvidersByAuthority.remove(names[j]); 11001 if (DEBUG_REMOVE) { 11002 if (chatty) 11003 Log.d(TAG, "Unregistered content provider: " + names[j] 11004 + ", className = " + p.info.name + ", isSyncable = " 11005 + p.info.isSyncable); 11006 } 11007 } 11008 } 11009 if (DEBUG_REMOVE && chatty) { 11010 if (r == null) { 11011 r = new StringBuilder(256); 11012 } else { 11013 r.append(' '); 11014 } 11015 r.append(p.info.name); 11016 } 11017 } 11018 if (r != null) { 11019 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11020 } 11021 11022 N = pkg.services.size(); 11023 r = null; 11024 for (i=0; i<N; i++) { 11025 PackageParser.Service s = pkg.services.get(i); 11026 mServices.removeService(s); 11027 if (chatty) { 11028 if (r == null) { 11029 r = new StringBuilder(256); 11030 } else { 11031 r.append(' '); 11032 } 11033 r.append(s.info.name); 11034 } 11035 } 11036 if (r != null) { 11037 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11038 } 11039 11040 N = pkg.receivers.size(); 11041 r = null; 11042 for (i=0; i<N; i++) { 11043 PackageParser.Activity a = pkg.receivers.get(i); 11044 mReceivers.removeActivity(a, "receiver"); 11045 if (DEBUG_REMOVE && chatty) { 11046 if (r == null) { 11047 r = new StringBuilder(256); 11048 } else { 11049 r.append(' '); 11050 } 11051 r.append(a.info.name); 11052 } 11053 } 11054 if (r != null) { 11055 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11056 } 11057 11058 N = pkg.activities.size(); 11059 r = null; 11060 for (i=0; i<N; i++) { 11061 PackageParser.Activity a = pkg.activities.get(i); 11062 mActivities.removeActivity(a, "activity"); 11063 if (DEBUG_REMOVE && chatty) { 11064 if (r == null) { 11065 r = new StringBuilder(256); 11066 } else { 11067 r.append(' '); 11068 } 11069 r.append(a.info.name); 11070 } 11071 } 11072 if (r != null) { 11073 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11074 } 11075 11076 N = pkg.permissions.size(); 11077 r = null; 11078 for (i=0; i<N; i++) { 11079 PackageParser.Permission p = pkg.permissions.get(i); 11080 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11081 if (bp == null) { 11082 bp = mSettings.mPermissionTrees.get(p.info.name); 11083 } 11084 if (bp != null && bp.perm == p) { 11085 bp.perm = null; 11086 if (DEBUG_REMOVE && chatty) { 11087 if (r == null) { 11088 r = new StringBuilder(256); 11089 } else { 11090 r.append(' '); 11091 } 11092 r.append(p.info.name); 11093 } 11094 } 11095 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11096 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11097 if (appOpPkgs != null) { 11098 appOpPkgs.remove(pkg.packageName); 11099 } 11100 } 11101 } 11102 if (r != null) { 11103 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11104 } 11105 11106 N = pkg.requestedPermissions.size(); 11107 r = null; 11108 for (i=0; i<N; i++) { 11109 String perm = pkg.requestedPermissions.get(i); 11110 BasePermission bp = mSettings.mPermissions.get(perm); 11111 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11112 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11113 if (appOpPkgs != null) { 11114 appOpPkgs.remove(pkg.packageName); 11115 if (appOpPkgs.isEmpty()) { 11116 mAppOpPermissionPackages.remove(perm); 11117 } 11118 } 11119 } 11120 } 11121 if (r != null) { 11122 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11123 } 11124 11125 N = pkg.instrumentation.size(); 11126 r = null; 11127 for (i=0; i<N; i++) { 11128 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11129 mInstrumentation.remove(a.getComponentName()); 11130 if (DEBUG_REMOVE && chatty) { 11131 if (r == null) { 11132 r = new StringBuilder(256); 11133 } else { 11134 r.append(' '); 11135 } 11136 r.append(a.info.name); 11137 } 11138 } 11139 if (r != null) { 11140 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11141 } 11142 11143 r = null; 11144 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11145 // Only system apps can hold shared libraries. 11146 if (pkg.libraryNames != null) { 11147 for (i = 0; i < pkg.libraryNames.size(); i++) { 11148 String name = pkg.libraryNames.get(i); 11149 if (removeSharedLibraryLPw(name, 0)) { 11150 if (DEBUG_REMOVE && chatty) { 11151 if (r == null) { 11152 r = new StringBuilder(256); 11153 } else { 11154 r.append(' '); 11155 } 11156 r.append(name); 11157 } 11158 } 11159 } 11160 } 11161 } 11162 11163 r = null; 11164 11165 // Any package can hold static shared libraries. 11166 if (pkg.staticSharedLibName != null) { 11167 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11168 if (DEBUG_REMOVE && chatty) { 11169 if (r == null) { 11170 r = new StringBuilder(256); 11171 } else { 11172 r.append(' '); 11173 } 11174 r.append(pkg.staticSharedLibName); 11175 } 11176 } 11177 } 11178 11179 if (r != null) { 11180 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11181 } 11182 } 11183 11184 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11185 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11186 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11187 return true; 11188 } 11189 } 11190 return false; 11191 } 11192 11193 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11194 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11195 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11196 11197 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11198 // Update the parent permissions 11199 updatePermissionsLPw(pkg.packageName, pkg, flags); 11200 // Update the child permissions 11201 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11202 for (int i = 0; i < childCount; i++) { 11203 PackageParser.Package childPkg = pkg.childPackages.get(i); 11204 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11205 } 11206 } 11207 11208 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11209 int flags) { 11210 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11211 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11212 } 11213 11214 private void updatePermissionsLPw(String changingPkg, 11215 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11216 // Make sure there are no dangling permission trees. 11217 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11218 while (it.hasNext()) { 11219 final BasePermission bp = it.next(); 11220 if (bp.packageSetting == null) { 11221 // We may not yet have parsed the package, so just see if 11222 // we still know about its settings. 11223 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11224 } 11225 if (bp.packageSetting == null) { 11226 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11227 + " from package " + bp.sourcePackage); 11228 it.remove(); 11229 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11230 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11231 Slog.i(TAG, "Removing old permission tree: " + bp.name 11232 + " from package " + bp.sourcePackage); 11233 flags |= UPDATE_PERMISSIONS_ALL; 11234 it.remove(); 11235 } 11236 } 11237 } 11238 11239 // Make sure all dynamic permissions have been assigned to a package, 11240 // and make sure there are no dangling permissions. 11241 it = mSettings.mPermissions.values().iterator(); 11242 while (it.hasNext()) { 11243 final BasePermission bp = it.next(); 11244 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11245 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11246 + bp.name + " pkg=" + bp.sourcePackage 11247 + " info=" + bp.pendingInfo); 11248 if (bp.packageSetting == null && bp.pendingInfo != null) { 11249 final BasePermission tree = findPermissionTreeLP(bp.name); 11250 if (tree != null && tree.perm != null) { 11251 bp.packageSetting = tree.packageSetting; 11252 bp.perm = new PackageParser.Permission(tree.perm.owner, 11253 new PermissionInfo(bp.pendingInfo)); 11254 bp.perm.info.packageName = tree.perm.info.packageName; 11255 bp.perm.info.name = bp.name; 11256 bp.uid = tree.uid; 11257 } 11258 } 11259 } 11260 if (bp.packageSetting == null) { 11261 // We may not yet have parsed the package, so just see if 11262 // we still know about its settings. 11263 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11264 } 11265 if (bp.packageSetting == null) { 11266 Slog.w(TAG, "Removing dangling permission: " + bp.name 11267 + " from package " + bp.sourcePackage); 11268 it.remove(); 11269 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11270 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11271 Slog.i(TAG, "Removing old permission: " + bp.name 11272 + " from package " + bp.sourcePackage); 11273 flags |= UPDATE_PERMISSIONS_ALL; 11274 it.remove(); 11275 } 11276 } 11277 } 11278 11279 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11280 // Now update the permissions for all packages, in particular 11281 // replace the granted permissions of the system packages. 11282 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11283 for (PackageParser.Package pkg : mPackages.values()) { 11284 if (pkg != pkgInfo) { 11285 // Only replace for packages on requested volume 11286 final String volumeUuid = getVolumeUuidForPackage(pkg); 11287 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11288 && Objects.equals(replaceVolumeUuid, volumeUuid); 11289 grantPermissionsLPw(pkg, replace, changingPkg); 11290 } 11291 } 11292 } 11293 11294 if (pkgInfo != null) { 11295 // Only replace for packages on requested volume 11296 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11297 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11298 && Objects.equals(replaceVolumeUuid, volumeUuid); 11299 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11300 } 11301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11302 } 11303 11304 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11305 String packageOfInterest) { 11306 // IMPORTANT: There are two types of permissions: install and runtime. 11307 // Install time permissions are granted when the app is installed to 11308 // all device users and users added in the future. Runtime permissions 11309 // are granted at runtime explicitly to specific users. Normal and signature 11310 // protected permissions are install time permissions. Dangerous permissions 11311 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11312 // otherwise they are runtime permissions. This function does not manage 11313 // runtime permissions except for the case an app targeting Lollipop MR1 11314 // being upgraded to target a newer SDK, in which case dangerous permissions 11315 // are transformed from install time to runtime ones. 11316 11317 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11318 if (ps == null) { 11319 return; 11320 } 11321 11322 PermissionsState permissionsState = ps.getPermissionsState(); 11323 PermissionsState origPermissions = permissionsState; 11324 11325 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11326 11327 boolean runtimePermissionsRevoked = false; 11328 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11329 11330 boolean changedInstallPermission = false; 11331 11332 if (replace) { 11333 ps.installPermissionsFixed = false; 11334 if (!ps.isSharedUser()) { 11335 origPermissions = new PermissionsState(permissionsState); 11336 permissionsState.reset(); 11337 } else { 11338 // We need to know only about runtime permission changes since the 11339 // calling code always writes the install permissions state but 11340 // the runtime ones are written only if changed. The only cases of 11341 // changed runtime permissions here are promotion of an install to 11342 // runtime and revocation of a runtime from a shared user. 11343 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11344 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11345 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11346 runtimePermissionsRevoked = true; 11347 } 11348 } 11349 } 11350 11351 permissionsState.setGlobalGids(mGlobalGids); 11352 11353 final int N = pkg.requestedPermissions.size(); 11354 for (int i=0; i<N; i++) { 11355 final String name = pkg.requestedPermissions.get(i); 11356 final BasePermission bp = mSettings.mPermissions.get(name); 11357 11358 if (DEBUG_INSTALL) { 11359 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11360 } 11361 11362 if (bp == null || bp.packageSetting == null) { 11363 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11364 Slog.w(TAG, "Unknown permission " + name 11365 + " in package " + pkg.packageName); 11366 } 11367 continue; 11368 } 11369 11370 11371 // Limit ephemeral apps to ephemeral allowed permissions. 11372 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11373 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11374 + pkg.packageName); 11375 continue; 11376 } 11377 11378 final String perm = bp.name; 11379 boolean allowedSig = false; 11380 int grant = GRANT_DENIED; 11381 11382 // Keep track of app op permissions. 11383 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11384 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11385 if (pkgs == null) { 11386 pkgs = new ArraySet<>(); 11387 mAppOpPermissionPackages.put(bp.name, pkgs); 11388 } 11389 pkgs.add(pkg.packageName); 11390 } 11391 11392 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11393 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11394 >= Build.VERSION_CODES.M; 11395 switch (level) { 11396 case PermissionInfo.PROTECTION_NORMAL: { 11397 // For all apps normal permissions are install time ones. 11398 grant = GRANT_INSTALL; 11399 } break; 11400 11401 case PermissionInfo.PROTECTION_DANGEROUS: { 11402 // If a permission review is required for legacy apps we represent 11403 // their permissions as always granted runtime ones since we need 11404 // to keep the review required permission flag per user while an 11405 // install permission's state is shared across all users. 11406 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11407 // For legacy apps dangerous permissions are install time ones. 11408 grant = GRANT_INSTALL; 11409 } else if (origPermissions.hasInstallPermission(bp.name)) { 11410 // For legacy apps that became modern, install becomes runtime. 11411 grant = GRANT_UPGRADE; 11412 } else if (mPromoteSystemApps 11413 && isSystemApp(ps) 11414 && mExistingSystemPackages.contains(ps.name)) { 11415 // For legacy system apps, install becomes runtime. 11416 // We cannot check hasInstallPermission() for system apps since those 11417 // permissions were granted implicitly and not persisted pre-M. 11418 grant = GRANT_UPGRADE; 11419 } else { 11420 // For modern apps keep runtime permissions unchanged. 11421 grant = GRANT_RUNTIME; 11422 } 11423 } break; 11424 11425 case PermissionInfo.PROTECTION_SIGNATURE: { 11426 // For all apps signature permissions are install time ones. 11427 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11428 if (allowedSig) { 11429 grant = GRANT_INSTALL; 11430 } 11431 } break; 11432 } 11433 11434 if (DEBUG_INSTALL) { 11435 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11436 } 11437 11438 if (grant != GRANT_DENIED) { 11439 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11440 // If this is an existing, non-system package, then 11441 // we can't add any new permissions to it. 11442 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11443 // Except... if this is a permission that was added 11444 // to the platform (note: need to only do this when 11445 // updating the platform). 11446 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11447 grant = GRANT_DENIED; 11448 } 11449 } 11450 } 11451 11452 switch (grant) { 11453 case GRANT_INSTALL: { 11454 // Revoke this as runtime permission to handle the case of 11455 // a runtime permission being downgraded to an install one. 11456 // Also in permission review mode we keep dangerous permissions 11457 // for legacy apps 11458 for (int userId : UserManagerService.getInstance().getUserIds()) { 11459 if (origPermissions.getRuntimePermissionState( 11460 bp.name, userId) != null) { 11461 // Revoke the runtime permission and clear the flags. 11462 origPermissions.revokeRuntimePermission(bp, userId); 11463 origPermissions.updatePermissionFlags(bp, userId, 11464 PackageManager.MASK_PERMISSION_FLAGS, 0); 11465 // If we revoked a permission permission, we have to write. 11466 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11467 changedRuntimePermissionUserIds, userId); 11468 } 11469 } 11470 // Grant an install permission. 11471 if (permissionsState.grantInstallPermission(bp) != 11472 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11473 changedInstallPermission = true; 11474 } 11475 } break; 11476 11477 case GRANT_RUNTIME: { 11478 // Grant previously granted runtime permissions. 11479 for (int userId : UserManagerService.getInstance().getUserIds()) { 11480 PermissionState permissionState = origPermissions 11481 .getRuntimePermissionState(bp.name, userId); 11482 int flags = permissionState != null 11483 ? permissionState.getFlags() : 0; 11484 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11485 // Don't propagate the permission in a permission review mode if 11486 // the former was revoked, i.e. marked to not propagate on upgrade. 11487 // Note that in a permission review mode install permissions are 11488 // represented as constantly granted runtime ones since we need to 11489 // keep a per user state associated with the permission. Also the 11490 // revoke on upgrade flag is no longer applicable and is reset. 11491 final boolean revokeOnUpgrade = (flags & PackageManager 11492 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11493 if (revokeOnUpgrade) { 11494 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11495 // Since we changed the flags, we have to write. 11496 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11497 changedRuntimePermissionUserIds, userId); 11498 } 11499 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11500 if (permissionsState.grantRuntimePermission(bp, userId) == 11501 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11502 // If we cannot put the permission as it was, 11503 // we have to write. 11504 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11505 changedRuntimePermissionUserIds, userId); 11506 } 11507 } 11508 11509 // If the app supports runtime permissions no need for a review. 11510 if (mPermissionReviewRequired 11511 && appSupportsRuntimePermissions 11512 && (flags & PackageManager 11513 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11514 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11515 // Since we changed the flags, we have to write. 11516 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11517 changedRuntimePermissionUserIds, userId); 11518 } 11519 } else if (mPermissionReviewRequired 11520 && !appSupportsRuntimePermissions) { 11521 // For legacy apps that need a permission review, every new 11522 // runtime permission is granted but it is pending a review. 11523 // We also need to review only platform defined runtime 11524 // permissions as these are the only ones the platform knows 11525 // how to disable the API to simulate revocation as legacy 11526 // apps don't expect to run with revoked permissions. 11527 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11528 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11529 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11530 // We changed the flags, hence have to write. 11531 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11532 changedRuntimePermissionUserIds, userId); 11533 } 11534 } 11535 if (permissionsState.grantRuntimePermission(bp, userId) 11536 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11537 // We changed the permission, hence have to write. 11538 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11539 changedRuntimePermissionUserIds, userId); 11540 } 11541 } 11542 // Propagate the permission flags. 11543 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11544 } 11545 } break; 11546 11547 case GRANT_UPGRADE: { 11548 // Grant runtime permissions for a previously held install permission. 11549 PermissionState permissionState = origPermissions 11550 .getInstallPermissionState(bp.name); 11551 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11552 11553 if (origPermissions.revokeInstallPermission(bp) 11554 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11555 // We will be transferring the permission flags, so clear them. 11556 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11557 PackageManager.MASK_PERMISSION_FLAGS, 0); 11558 changedInstallPermission = true; 11559 } 11560 11561 // If the permission is not to be promoted to runtime we ignore it and 11562 // also its other flags as they are not applicable to install permissions. 11563 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11564 for (int userId : currentUserIds) { 11565 if (permissionsState.grantRuntimePermission(bp, userId) != 11566 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11567 // Transfer the permission flags. 11568 permissionsState.updatePermissionFlags(bp, userId, 11569 flags, flags); 11570 // If we granted the permission, we have to write. 11571 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11572 changedRuntimePermissionUserIds, userId); 11573 } 11574 } 11575 } 11576 } break; 11577 11578 default: { 11579 if (packageOfInterest == null 11580 || packageOfInterest.equals(pkg.packageName)) { 11581 Slog.w(TAG, "Not granting permission " + perm 11582 + " to package " + pkg.packageName 11583 + " because it was previously installed without"); 11584 } 11585 } break; 11586 } 11587 } else { 11588 if (permissionsState.revokeInstallPermission(bp) != 11589 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11590 // Also drop the permission flags. 11591 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11592 PackageManager.MASK_PERMISSION_FLAGS, 0); 11593 changedInstallPermission = true; 11594 Slog.i(TAG, "Un-granting permission " + perm 11595 + " from package " + pkg.packageName 11596 + " (protectionLevel=" + bp.protectionLevel 11597 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11598 + ")"); 11599 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11600 // Don't print warning for app op permissions, since it is fine for them 11601 // not to be granted, there is a UI for the user to decide. 11602 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11603 Slog.w(TAG, "Not granting permission " + perm 11604 + " to package " + pkg.packageName 11605 + " (protectionLevel=" + bp.protectionLevel 11606 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11607 + ")"); 11608 } 11609 } 11610 } 11611 } 11612 11613 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11614 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11615 // This is the first that we have heard about this package, so the 11616 // permissions we have now selected are fixed until explicitly 11617 // changed. 11618 ps.installPermissionsFixed = true; 11619 } 11620 11621 // Persist the runtime permissions state for users with changes. If permissions 11622 // were revoked because no app in the shared user declares them we have to 11623 // write synchronously to avoid losing runtime permissions state. 11624 for (int userId : changedRuntimePermissionUserIds) { 11625 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11626 } 11627 } 11628 11629 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11630 boolean allowed = false; 11631 final int NP = PackageParser.NEW_PERMISSIONS.length; 11632 for (int ip=0; ip<NP; ip++) { 11633 final PackageParser.NewPermissionInfo npi 11634 = PackageParser.NEW_PERMISSIONS[ip]; 11635 if (npi.name.equals(perm) 11636 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11637 allowed = true; 11638 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11639 + pkg.packageName); 11640 break; 11641 } 11642 } 11643 return allowed; 11644 } 11645 11646 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11647 BasePermission bp, PermissionsState origPermissions) { 11648 boolean privilegedPermission = (bp.protectionLevel 11649 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11650 boolean privappPermissionsDisable = 11651 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11652 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11653 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11654 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11655 && !platformPackage && platformPermission) { 11656 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11657 .getPrivAppPermissions(pkg.packageName); 11658 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11659 if (!whitelisted) { 11660 Slog.w(TAG, "Privileged permission " + perm + " for package " 11661 + pkg.packageName + " - not in privapp-permissions whitelist"); 11662 if (!mSystemReady) { 11663 if (mPrivappPermissionsViolations == null) { 11664 mPrivappPermissionsViolations = new ArraySet<>(); 11665 } 11666 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11667 } 11668 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11669 return false; 11670 } 11671 } 11672 } 11673 boolean allowed = (compareSignatures( 11674 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11675 == PackageManager.SIGNATURE_MATCH) 11676 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11677 == PackageManager.SIGNATURE_MATCH); 11678 if (!allowed && privilegedPermission) { 11679 if (isSystemApp(pkg)) { 11680 // For updated system applications, a system permission 11681 // is granted only if it had been defined by the original application. 11682 if (pkg.isUpdatedSystemApp()) { 11683 final PackageSetting sysPs = mSettings 11684 .getDisabledSystemPkgLPr(pkg.packageName); 11685 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11686 // If the original was granted this permission, we take 11687 // that grant decision as read and propagate it to the 11688 // update. 11689 if (sysPs.isPrivileged()) { 11690 allowed = true; 11691 } 11692 } else { 11693 // The system apk may have been updated with an older 11694 // version of the one on the data partition, but which 11695 // granted a new system permission that it didn't have 11696 // before. In this case we do want to allow the app to 11697 // now get the new permission if the ancestral apk is 11698 // privileged to get it. 11699 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11700 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11701 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11702 allowed = true; 11703 break; 11704 } 11705 } 11706 } 11707 // Also if a privileged parent package on the system image or any of 11708 // its children requested a privileged permission, the updated child 11709 // packages can also get the permission. 11710 if (pkg.parentPackage != null) { 11711 final PackageSetting disabledSysParentPs = mSettings 11712 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11713 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11714 && disabledSysParentPs.isPrivileged()) { 11715 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11716 allowed = true; 11717 } else if (disabledSysParentPs.pkg.childPackages != null) { 11718 final int count = disabledSysParentPs.pkg.childPackages.size(); 11719 for (int i = 0; i < count; i++) { 11720 PackageParser.Package disabledSysChildPkg = 11721 disabledSysParentPs.pkg.childPackages.get(i); 11722 if (isPackageRequestingPermission(disabledSysChildPkg, 11723 perm)) { 11724 allowed = true; 11725 break; 11726 } 11727 } 11728 } 11729 } 11730 } 11731 } 11732 } else { 11733 allowed = isPrivilegedApp(pkg); 11734 } 11735 } 11736 } 11737 if (!allowed) { 11738 if (!allowed && (bp.protectionLevel 11739 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11740 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11741 // If this was a previously normal/dangerous permission that got moved 11742 // to a system permission as part of the runtime permission redesign, then 11743 // we still want to blindly grant it to old apps. 11744 allowed = true; 11745 } 11746 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11747 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11748 // If this permission is to be granted to the system installer and 11749 // this app is an installer, then it gets the permission. 11750 allowed = true; 11751 } 11752 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11753 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11754 // If this permission is to be granted to the system verifier and 11755 // this app is a verifier, then it gets the permission. 11756 allowed = true; 11757 } 11758 if (!allowed && (bp.protectionLevel 11759 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11760 && isSystemApp(pkg)) { 11761 // Any pre-installed system app is allowed to get this permission. 11762 allowed = true; 11763 } 11764 if (!allowed && (bp.protectionLevel 11765 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11766 // For development permissions, a development permission 11767 // is granted only if it was already granted. 11768 allowed = origPermissions.hasInstallPermission(perm); 11769 } 11770 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11771 && pkg.packageName.equals(mSetupWizardPackage)) { 11772 // If this permission is to be granted to the system setup wizard and 11773 // this app is a setup wizard, then it gets the permission. 11774 allowed = true; 11775 } 11776 } 11777 return allowed; 11778 } 11779 11780 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11781 final int permCount = pkg.requestedPermissions.size(); 11782 for (int j = 0; j < permCount; j++) { 11783 String requestedPermission = pkg.requestedPermissions.get(j); 11784 if (permission.equals(requestedPermission)) { 11785 return true; 11786 } 11787 } 11788 return false; 11789 } 11790 11791 final class ActivityIntentResolver 11792 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11793 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11794 boolean defaultOnly, int userId) { 11795 if (!sUserManager.exists(userId)) return null; 11796 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11797 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11798 } 11799 11800 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11801 int userId) { 11802 if (!sUserManager.exists(userId)) return null; 11803 mFlags = flags; 11804 return super.queryIntent(intent, resolvedType, 11805 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11806 userId); 11807 } 11808 11809 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11810 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11811 if (!sUserManager.exists(userId)) return null; 11812 if (packageActivities == null) { 11813 return null; 11814 } 11815 mFlags = flags; 11816 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11817 final int N = packageActivities.size(); 11818 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11819 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11820 11821 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11822 for (int i = 0; i < N; ++i) { 11823 intentFilters = packageActivities.get(i).intents; 11824 if (intentFilters != null && intentFilters.size() > 0) { 11825 PackageParser.ActivityIntentInfo[] array = 11826 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11827 intentFilters.toArray(array); 11828 listCut.add(array); 11829 } 11830 } 11831 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11832 } 11833 11834 /** 11835 * Finds a privileged activity that matches the specified activity names. 11836 */ 11837 private PackageParser.Activity findMatchingActivity( 11838 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11839 for (PackageParser.Activity sysActivity : activityList) { 11840 if (sysActivity.info.name.equals(activityInfo.name)) { 11841 return sysActivity; 11842 } 11843 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11844 return sysActivity; 11845 } 11846 if (sysActivity.info.targetActivity != null) { 11847 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11848 return sysActivity; 11849 } 11850 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11851 return sysActivity; 11852 } 11853 } 11854 } 11855 return null; 11856 } 11857 11858 public class IterGenerator<E> { 11859 public Iterator<E> generate(ActivityIntentInfo info) { 11860 return null; 11861 } 11862 } 11863 11864 public class ActionIterGenerator extends IterGenerator<String> { 11865 @Override 11866 public Iterator<String> generate(ActivityIntentInfo info) { 11867 return info.actionsIterator(); 11868 } 11869 } 11870 11871 public class CategoriesIterGenerator extends IterGenerator<String> { 11872 @Override 11873 public Iterator<String> generate(ActivityIntentInfo info) { 11874 return info.categoriesIterator(); 11875 } 11876 } 11877 11878 public class SchemesIterGenerator extends IterGenerator<String> { 11879 @Override 11880 public Iterator<String> generate(ActivityIntentInfo info) { 11881 return info.schemesIterator(); 11882 } 11883 } 11884 11885 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11886 @Override 11887 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11888 return info.authoritiesIterator(); 11889 } 11890 } 11891 11892 /** 11893 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11894 * MODIFIED. Do not pass in a list that should not be changed. 11895 */ 11896 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11897 IterGenerator<T> generator, Iterator<T> searchIterator) { 11898 // loop through the set of actions; every one must be found in the intent filter 11899 while (searchIterator.hasNext()) { 11900 // we must have at least one filter in the list to consider a match 11901 if (intentList.size() == 0) { 11902 break; 11903 } 11904 11905 final T searchAction = searchIterator.next(); 11906 11907 // loop through the set of intent filters 11908 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11909 while (intentIter.hasNext()) { 11910 final ActivityIntentInfo intentInfo = intentIter.next(); 11911 boolean selectionFound = false; 11912 11913 // loop through the intent filter's selection criteria; at least one 11914 // of them must match the searched criteria 11915 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11916 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11917 final T intentSelection = intentSelectionIter.next(); 11918 if (intentSelection != null && intentSelection.equals(searchAction)) { 11919 selectionFound = true; 11920 break; 11921 } 11922 } 11923 11924 // the selection criteria wasn't found in this filter's set; this filter 11925 // is not a potential match 11926 if (!selectionFound) { 11927 intentIter.remove(); 11928 } 11929 } 11930 } 11931 } 11932 11933 private boolean isProtectedAction(ActivityIntentInfo filter) { 11934 final Iterator<String> actionsIter = filter.actionsIterator(); 11935 while (actionsIter != null && actionsIter.hasNext()) { 11936 final String filterAction = actionsIter.next(); 11937 if (PROTECTED_ACTIONS.contains(filterAction)) { 11938 return true; 11939 } 11940 } 11941 return false; 11942 } 11943 11944 /** 11945 * Adjusts the priority of the given intent filter according to policy. 11946 * <p> 11947 * <ul> 11948 * <li>The priority for non privileged applications is capped to '0'</li> 11949 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11950 * <li>The priority for unbundled updates to privileged applications is capped to the 11951 * priority defined on the system partition</li> 11952 * </ul> 11953 * <p> 11954 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11955 * allowed to obtain any priority on any action. 11956 */ 11957 private void adjustPriority( 11958 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11959 // nothing to do; priority is fine as-is 11960 if (intent.getPriority() <= 0) { 11961 return; 11962 } 11963 11964 final ActivityInfo activityInfo = intent.activity.info; 11965 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11966 11967 final boolean privilegedApp = 11968 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11969 if (!privilegedApp) { 11970 // non-privileged applications can never define a priority >0 11971 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11972 + " package: " + applicationInfo.packageName 11973 + " activity: " + intent.activity.className 11974 + " origPrio: " + intent.getPriority()); 11975 intent.setPriority(0); 11976 return; 11977 } 11978 11979 if (systemActivities == null) { 11980 // the system package is not disabled; we're parsing the system partition 11981 if (isProtectedAction(intent)) { 11982 if (mDeferProtectedFilters) { 11983 // We can't deal with these just yet. No component should ever obtain a 11984 // >0 priority for a protected actions, with ONE exception -- the setup 11985 // wizard. The setup wizard, however, cannot be known until we're able to 11986 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11987 // until all intent filters have been processed. Chicken, meet egg. 11988 // Let the filter temporarily have a high priority and rectify the 11989 // priorities after all system packages have been scanned. 11990 mProtectedFilters.add(intent); 11991 if (DEBUG_FILTERS) { 11992 Slog.i(TAG, "Protected action; save for later;" 11993 + " package: " + applicationInfo.packageName 11994 + " activity: " + intent.activity.className 11995 + " origPrio: " + intent.getPriority()); 11996 } 11997 return; 11998 } else { 11999 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12000 Slog.i(TAG, "No setup wizard;" 12001 + " All protected intents capped to priority 0"); 12002 } 12003 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12004 if (DEBUG_FILTERS) { 12005 Slog.i(TAG, "Found setup wizard;" 12006 + " allow priority " + intent.getPriority() + ";" 12007 + " package: " + intent.activity.info.packageName 12008 + " activity: " + intent.activity.className 12009 + " priority: " + intent.getPriority()); 12010 } 12011 // setup wizard gets whatever it wants 12012 return; 12013 } 12014 Slog.w(TAG, "Protected action; cap priority to 0;" 12015 + " package: " + intent.activity.info.packageName 12016 + " activity: " + intent.activity.className 12017 + " origPrio: " + intent.getPriority()); 12018 intent.setPriority(0); 12019 return; 12020 } 12021 } 12022 // privileged apps on the system image get whatever priority they request 12023 return; 12024 } 12025 12026 // privileged app unbundled update ... try to find the same activity 12027 final PackageParser.Activity foundActivity = 12028 findMatchingActivity(systemActivities, activityInfo); 12029 if (foundActivity == null) { 12030 // this is a new activity; it cannot obtain >0 priority 12031 if (DEBUG_FILTERS) { 12032 Slog.i(TAG, "New activity; cap priority to 0;" 12033 + " package: " + applicationInfo.packageName 12034 + " activity: " + intent.activity.className 12035 + " origPrio: " + intent.getPriority()); 12036 } 12037 intent.setPriority(0); 12038 return; 12039 } 12040 12041 // found activity, now check for filter equivalence 12042 12043 // a shallow copy is enough; we modify the list, not its contents 12044 final List<ActivityIntentInfo> intentListCopy = 12045 new ArrayList<>(foundActivity.intents); 12046 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12047 12048 // find matching action subsets 12049 final Iterator<String> actionsIterator = intent.actionsIterator(); 12050 if (actionsIterator != null) { 12051 getIntentListSubset( 12052 intentListCopy, new ActionIterGenerator(), actionsIterator); 12053 if (intentListCopy.size() == 0) { 12054 // no more intents to match; we're not equivalent 12055 if (DEBUG_FILTERS) { 12056 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12057 + " package: " + applicationInfo.packageName 12058 + " activity: " + intent.activity.className 12059 + " origPrio: " + intent.getPriority()); 12060 } 12061 intent.setPriority(0); 12062 return; 12063 } 12064 } 12065 12066 // find matching category subsets 12067 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12068 if (categoriesIterator != null) { 12069 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12070 categoriesIterator); 12071 if (intentListCopy.size() == 0) { 12072 // no more intents to match; we're not equivalent 12073 if (DEBUG_FILTERS) { 12074 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12075 + " package: " + applicationInfo.packageName 12076 + " activity: " + intent.activity.className 12077 + " origPrio: " + intent.getPriority()); 12078 } 12079 intent.setPriority(0); 12080 return; 12081 } 12082 } 12083 12084 // find matching schemes subsets 12085 final Iterator<String> schemesIterator = intent.schemesIterator(); 12086 if (schemesIterator != null) { 12087 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12088 schemesIterator); 12089 if (intentListCopy.size() == 0) { 12090 // no more intents to match; we're not equivalent 12091 if (DEBUG_FILTERS) { 12092 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12093 + " package: " + applicationInfo.packageName 12094 + " activity: " + intent.activity.className 12095 + " origPrio: " + intent.getPriority()); 12096 } 12097 intent.setPriority(0); 12098 return; 12099 } 12100 } 12101 12102 // find matching authorities subsets 12103 final Iterator<IntentFilter.AuthorityEntry> 12104 authoritiesIterator = intent.authoritiesIterator(); 12105 if (authoritiesIterator != null) { 12106 getIntentListSubset(intentListCopy, 12107 new AuthoritiesIterGenerator(), 12108 authoritiesIterator); 12109 if (intentListCopy.size() == 0) { 12110 // no more intents to match; we're not equivalent 12111 if (DEBUG_FILTERS) { 12112 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12113 + " package: " + applicationInfo.packageName 12114 + " activity: " + intent.activity.className 12115 + " origPrio: " + intent.getPriority()); 12116 } 12117 intent.setPriority(0); 12118 return; 12119 } 12120 } 12121 12122 // we found matching filter(s); app gets the max priority of all intents 12123 int cappedPriority = 0; 12124 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12125 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12126 } 12127 if (intent.getPriority() > cappedPriority) { 12128 if (DEBUG_FILTERS) { 12129 Slog.i(TAG, "Found matching filter(s);" 12130 + " cap priority to " + cappedPriority + ";" 12131 + " package: " + applicationInfo.packageName 12132 + " activity: " + intent.activity.className 12133 + " origPrio: " + intent.getPriority()); 12134 } 12135 intent.setPriority(cappedPriority); 12136 return; 12137 } 12138 // all this for nothing; the requested priority was <= what was on the system 12139 } 12140 12141 public final void addActivity(PackageParser.Activity a, String type) { 12142 mActivities.put(a.getComponentName(), a); 12143 if (DEBUG_SHOW_INFO) 12144 Log.v( 12145 TAG, " " + type + " " + 12146 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12147 if (DEBUG_SHOW_INFO) 12148 Log.v(TAG, " Class=" + a.info.name); 12149 final int NI = a.intents.size(); 12150 for (int j=0; j<NI; j++) { 12151 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12152 if ("activity".equals(type)) { 12153 final PackageSetting ps = 12154 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12155 final List<PackageParser.Activity> systemActivities = 12156 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12157 adjustPriority(systemActivities, intent); 12158 } 12159 if (DEBUG_SHOW_INFO) { 12160 Log.v(TAG, " IntentFilter:"); 12161 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12162 } 12163 if (!intent.debugCheck()) { 12164 Log.w(TAG, "==> For Activity " + a.info.name); 12165 } 12166 addFilter(intent); 12167 } 12168 } 12169 12170 public final void removeActivity(PackageParser.Activity a, String type) { 12171 mActivities.remove(a.getComponentName()); 12172 if (DEBUG_SHOW_INFO) { 12173 Log.v(TAG, " " + type + " " 12174 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12175 : a.info.name) + ":"); 12176 Log.v(TAG, " Class=" + a.info.name); 12177 } 12178 final int NI = a.intents.size(); 12179 for (int j=0; j<NI; j++) { 12180 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12181 if (DEBUG_SHOW_INFO) { 12182 Log.v(TAG, " IntentFilter:"); 12183 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12184 } 12185 removeFilter(intent); 12186 } 12187 } 12188 12189 @Override 12190 protected boolean allowFilterResult( 12191 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12192 ActivityInfo filterAi = filter.activity.info; 12193 for (int i=dest.size()-1; i>=0; i--) { 12194 ActivityInfo destAi = dest.get(i).activityInfo; 12195 if (destAi.name == filterAi.name 12196 && destAi.packageName == filterAi.packageName) { 12197 return false; 12198 } 12199 } 12200 return true; 12201 } 12202 12203 @Override 12204 protected ActivityIntentInfo[] newArray(int size) { 12205 return new ActivityIntentInfo[size]; 12206 } 12207 12208 @Override 12209 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12210 if (!sUserManager.exists(userId)) return true; 12211 PackageParser.Package p = filter.activity.owner; 12212 if (p != null) { 12213 PackageSetting ps = (PackageSetting)p.mExtras; 12214 if (ps != null) { 12215 // System apps are never considered stopped for purposes of 12216 // filtering, because there may be no way for the user to 12217 // actually re-launch them. 12218 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12219 && ps.getStopped(userId); 12220 } 12221 } 12222 return false; 12223 } 12224 12225 @Override 12226 protected boolean isPackageForFilter(String packageName, 12227 PackageParser.ActivityIntentInfo info) { 12228 return packageName.equals(info.activity.owner.packageName); 12229 } 12230 12231 @Override 12232 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12233 int match, int userId) { 12234 if (!sUserManager.exists(userId)) return null; 12235 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12236 return null; 12237 } 12238 final PackageParser.Activity activity = info.activity; 12239 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12240 if (ps == null) { 12241 return null; 12242 } 12243 final PackageUserState userState = ps.readUserState(userId); 12244 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12245 userState, userId); 12246 if (ai == null) { 12247 return null; 12248 } 12249 final boolean matchVisibleToInstantApp = 12250 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12251 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12252 // throw out filters that aren't visible to ephemeral apps 12253 if (matchVisibleToInstantApp 12254 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12255 return null; 12256 } 12257 // throw out ephemeral filters if we're not explicitly requesting them 12258 if (!isInstantApp && userState.instantApp) { 12259 return null; 12260 } 12261 final ResolveInfo res = new ResolveInfo(); 12262 res.activityInfo = ai; 12263 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12264 res.filter = info; 12265 } 12266 if (info != null) { 12267 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12268 } 12269 res.priority = info.getPriority(); 12270 res.preferredOrder = activity.owner.mPreferredOrder; 12271 //System.out.println("Result: " + res.activityInfo.className + 12272 // " = " + res.priority); 12273 res.match = match; 12274 res.isDefault = info.hasDefault; 12275 res.labelRes = info.labelRes; 12276 res.nonLocalizedLabel = info.nonLocalizedLabel; 12277 if (userNeedsBadging(userId)) { 12278 res.noResourceId = true; 12279 } else { 12280 res.icon = info.icon; 12281 } 12282 res.iconResourceId = info.icon; 12283 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12284 return res; 12285 } 12286 12287 @Override 12288 protected void sortResults(List<ResolveInfo> results) { 12289 Collections.sort(results, mResolvePrioritySorter); 12290 } 12291 12292 @Override 12293 protected void dumpFilter(PrintWriter out, String prefix, 12294 PackageParser.ActivityIntentInfo filter) { 12295 out.print(prefix); out.print( 12296 Integer.toHexString(System.identityHashCode(filter.activity))); 12297 out.print(' '); 12298 filter.activity.printComponentShortName(out); 12299 out.print(" filter "); 12300 out.println(Integer.toHexString(System.identityHashCode(filter))); 12301 } 12302 12303 @Override 12304 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12305 return filter.activity; 12306 } 12307 12308 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12309 PackageParser.Activity activity = (PackageParser.Activity)label; 12310 out.print(prefix); out.print( 12311 Integer.toHexString(System.identityHashCode(activity))); 12312 out.print(' '); 12313 activity.printComponentShortName(out); 12314 if (count > 1) { 12315 out.print(" ("); out.print(count); out.print(" filters)"); 12316 } 12317 out.println(); 12318 } 12319 12320 // Keys are String (activity class name), values are Activity. 12321 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12322 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12323 private int mFlags; 12324 } 12325 12326 private final class ServiceIntentResolver 12327 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12328 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12329 boolean defaultOnly, int userId) { 12330 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12331 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12332 } 12333 12334 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12335 int userId) { 12336 if (!sUserManager.exists(userId)) return null; 12337 mFlags = flags; 12338 return super.queryIntent(intent, resolvedType, 12339 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12340 userId); 12341 } 12342 12343 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12344 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12345 if (!sUserManager.exists(userId)) return null; 12346 if (packageServices == null) { 12347 return null; 12348 } 12349 mFlags = flags; 12350 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12351 final int N = packageServices.size(); 12352 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12353 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12354 12355 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12356 for (int i = 0; i < N; ++i) { 12357 intentFilters = packageServices.get(i).intents; 12358 if (intentFilters != null && intentFilters.size() > 0) { 12359 PackageParser.ServiceIntentInfo[] array = 12360 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12361 intentFilters.toArray(array); 12362 listCut.add(array); 12363 } 12364 } 12365 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12366 } 12367 12368 public final void addService(PackageParser.Service s) { 12369 mServices.put(s.getComponentName(), s); 12370 if (DEBUG_SHOW_INFO) { 12371 Log.v(TAG, " " 12372 + (s.info.nonLocalizedLabel != null 12373 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12374 Log.v(TAG, " Class=" + s.info.name); 12375 } 12376 final int NI = s.intents.size(); 12377 int j; 12378 for (j=0; j<NI; j++) { 12379 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12380 if (DEBUG_SHOW_INFO) { 12381 Log.v(TAG, " IntentFilter:"); 12382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12383 } 12384 if (!intent.debugCheck()) { 12385 Log.w(TAG, "==> For Service " + s.info.name); 12386 } 12387 addFilter(intent); 12388 } 12389 } 12390 12391 public final void removeService(PackageParser.Service s) { 12392 mServices.remove(s.getComponentName()); 12393 if (DEBUG_SHOW_INFO) { 12394 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12395 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12396 Log.v(TAG, " Class=" + s.info.name); 12397 } 12398 final int NI = s.intents.size(); 12399 int j; 12400 for (j=0; j<NI; j++) { 12401 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12402 if (DEBUG_SHOW_INFO) { 12403 Log.v(TAG, " IntentFilter:"); 12404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12405 } 12406 removeFilter(intent); 12407 } 12408 } 12409 12410 @Override 12411 protected boolean allowFilterResult( 12412 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12413 ServiceInfo filterSi = filter.service.info; 12414 for (int i=dest.size()-1; i>=0; i--) { 12415 ServiceInfo destAi = dest.get(i).serviceInfo; 12416 if (destAi.name == filterSi.name 12417 && destAi.packageName == filterSi.packageName) { 12418 return false; 12419 } 12420 } 12421 return true; 12422 } 12423 12424 @Override 12425 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12426 return new PackageParser.ServiceIntentInfo[size]; 12427 } 12428 12429 @Override 12430 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12431 if (!sUserManager.exists(userId)) return true; 12432 PackageParser.Package p = filter.service.owner; 12433 if (p != null) { 12434 PackageSetting ps = (PackageSetting)p.mExtras; 12435 if (ps != null) { 12436 // System apps are never considered stopped for purposes of 12437 // filtering, because there may be no way for the user to 12438 // actually re-launch them. 12439 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12440 && ps.getStopped(userId); 12441 } 12442 } 12443 return false; 12444 } 12445 12446 @Override 12447 protected boolean isPackageForFilter(String packageName, 12448 PackageParser.ServiceIntentInfo info) { 12449 return packageName.equals(info.service.owner.packageName); 12450 } 12451 12452 @Override 12453 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12454 int match, int userId) { 12455 if (!sUserManager.exists(userId)) return null; 12456 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12457 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12458 return null; 12459 } 12460 final PackageParser.Service service = info.service; 12461 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12462 if (ps == null) { 12463 return null; 12464 } 12465 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12466 ps.readUserState(userId), userId); 12467 if (si == null) { 12468 return null; 12469 } 12470 final ResolveInfo res = new ResolveInfo(); 12471 res.serviceInfo = si; 12472 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12473 res.filter = filter; 12474 } 12475 res.priority = info.getPriority(); 12476 res.preferredOrder = service.owner.mPreferredOrder; 12477 res.match = match; 12478 res.isDefault = info.hasDefault; 12479 res.labelRes = info.labelRes; 12480 res.nonLocalizedLabel = info.nonLocalizedLabel; 12481 res.icon = info.icon; 12482 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12483 return res; 12484 } 12485 12486 @Override 12487 protected void sortResults(List<ResolveInfo> results) { 12488 Collections.sort(results, mResolvePrioritySorter); 12489 } 12490 12491 @Override 12492 protected void dumpFilter(PrintWriter out, String prefix, 12493 PackageParser.ServiceIntentInfo filter) { 12494 out.print(prefix); out.print( 12495 Integer.toHexString(System.identityHashCode(filter.service))); 12496 out.print(' '); 12497 filter.service.printComponentShortName(out); 12498 out.print(" filter "); 12499 out.println(Integer.toHexString(System.identityHashCode(filter))); 12500 } 12501 12502 @Override 12503 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12504 return filter.service; 12505 } 12506 12507 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12508 PackageParser.Service service = (PackageParser.Service)label; 12509 out.print(prefix); out.print( 12510 Integer.toHexString(System.identityHashCode(service))); 12511 out.print(' '); 12512 service.printComponentShortName(out); 12513 if (count > 1) { 12514 out.print(" ("); out.print(count); out.print(" filters)"); 12515 } 12516 out.println(); 12517 } 12518 12519// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12520// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12521// final List<ResolveInfo> retList = Lists.newArrayList(); 12522// while (i.hasNext()) { 12523// final ResolveInfo resolveInfo = (ResolveInfo) i; 12524// if (isEnabledLP(resolveInfo.serviceInfo)) { 12525// retList.add(resolveInfo); 12526// } 12527// } 12528// return retList; 12529// } 12530 12531 // Keys are String (activity class name), values are Activity. 12532 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12533 = new ArrayMap<ComponentName, PackageParser.Service>(); 12534 private int mFlags; 12535 } 12536 12537 private final class ProviderIntentResolver 12538 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12539 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12540 boolean defaultOnly, int userId) { 12541 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12542 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12543 } 12544 12545 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12546 int userId) { 12547 if (!sUserManager.exists(userId)) 12548 return null; 12549 mFlags = flags; 12550 return super.queryIntent(intent, resolvedType, 12551 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12552 userId); 12553 } 12554 12555 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12556 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12557 if (!sUserManager.exists(userId)) 12558 return null; 12559 if (packageProviders == null) { 12560 return null; 12561 } 12562 mFlags = flags; 12563 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12564 final int N = packageProviders.size(); 12565 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12566 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12567 12568 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12569 for (int i = 0; i < N; ++i) { 12570 intentFilters = packageProviders.get(i).intents; 12571 if (intentFilters != null && intentFilters.size() > 0) { 12572 PackageParser.ProviderIntentInfo[] array = 12573 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12574 intentFilters.toArray(array); 12575 listCut.add(array); 12576 } 12577 } 12578 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12579 } 12580 12581 public final void addProvider(PackageParser.Provider p) { 12582 if (mProviders.containsKey(p.getComponentName())) { 12583 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12584 return; 12585 } 12586 12587 mProviders.put(p.getComponentName(), p); 12588 if (DEBUG_SHOW_INFO) { 12589 Log.v(TAG, " " 12590 + (p.info.nonLocalizedLabel != null 12591 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12592 Log.v(TAG, " Class=" + p.info.name); 12593 } 12594 final int NI = p.intents.size(); 12595 int j; 12596 for (j = 0; j < NI; j++) { 12597 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12598 if (DEBUG_SHOW_INFO) { 12599 Log.v(TAG, " IntentFilter:"); 12600 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12601 } 12602 if (!intent.debugCheck()) { 12603 Log.w(TAG, "==> For Provider " + p.info.name); 12604 } 12605 addFilter(intent); 12606 } 12607 } 12608 12609 public final void removeProvider(PackageParser.Provider p) { 12610 mProviders.remove(p.getComponentName()); 12611 if (DEBUG_SHOW_INFO) { 12612 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12613 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12614 Log.v(TAG, " Class=" + p.info.name); 12615 } 12616 final int NI = p.intents.size(); 12617 int j; 12618 for (j = 0; j < NI; j++) { 12619 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12620 if (DEBUG_SHOW_INFO) { 12621 Log.v(TAG, " IntentFilter:"); 12622 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12623 } 12624 removeFilter(intent); 12625 } 12626 } 12627 12628 @Override 12629 protected boolean allowFilterResult( 12630 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12631 ProviderInfo filterPi = filter.provider.info; 12632 for (int i = dest.size() - 1; i >= 0; i--) { 12633 ProviderInfo destPi = dest.get(i).providerInfo; 12634 if (destPi.name == filterPi.name 12635 && destPi.packageName == filterPi.packageName) { 12636 return false; 12637 } 12638 } 12639 return true; 12640 } 12641 12642 @Override 12643 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12644 return new PackageParser.ProviderIntentInfo[size]; 12645 } 12646 12647 @Override 12648 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12649 if (!sUserManager.exists(userId)) 12650 return true; 12651 PackageParser.Package p = filter.provider.owner; 12652 if (p != null) { 12653 PackageSetting ps = (PackageSetting) p.mExtras; 12654 if (ps != null) { 12655 // System apps are never considered stopped for purposes of 12656 // filtering, because there may be no way for the user to 12657 // actually re-launch them. 12658 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12659 && ps.getStopped(userId); 12660 } 12661 } 12662 return false; 12663 } 12664 12665 @Override 12666 protected boolean isPackageForFilter(String packageName, 12667 PackageParser.ProviderIntentInfo info) { 12668 return packageName.equals(info.provider.owner.packageName); 12669 } 12670 12671 @Override 12672 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12673 int match, int userId) { 12674 if (!sUserManager.exists(userId)) 12675 return null; 12676 final PackageParser.ProviderIntentInfo info = filter; 12677 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12678 return null; 12679 } 12680 final PackageParser.Provider provider = info.provider; 12681 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12682 if (ps == null) { 12683 return null; 12684 } 12685 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12686 ps.readUserState(userId), userId); 12687 if (pi == null) { 12688 return null; 12689 } 12690 final ResolveInfo res = new ResolveInfo(); 12691 res.providerInfo = pi; 12692 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12693 res.filter = filter; 12694 } 12695 res.priority = info.getPriority(); 12696 res.preferredOrder = provider.owner.mPreferredOrder; 12697 res.match = match; 12698 res.isDefault = info.hasDefault; 12699 res.labelRes = info.labelRes; 12700 res.nonLocalizedLabel = info.nonLocalizedLabel; 12701 res.icon = info.icon; 12702 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12703 return res; 12704 } 12705 12706 @Override 12707 protected void sortResults(List<ResolveInfo> results) { 12708 Collections.sort(results, mResolvePrioritySorter); 12709 } 12710 12711 @Override 12712 protected void dumpFilter(PrintWriter out, String prefix, 12713 PackageParser.ProviderIntentInfo filter) { 12714 out.print(prefix); 12715 out.print( 12716 Integer.toHexString(System.identityHashCode(filter.provider))); 12717 out.print(' '); 12718 filter.provider.printComponentShortName(out); 12719 out.print(" filter "); 12720 out.println(Integer.toHexString(System.identityHashCode(filter))); 12721 } 12722 12723 @Override 12724 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12725 return filter.provider; 12726 } 12727 12728 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12729 PackageParser.Provider provider = (PackageParser.Provider)label; 12730 out.print(prefix); out.print( 12731 Integer.toHexString(System.identityHashCode(provider))); 12732 out.print(' '); 12733 provider.printComponentShortName(out); 12734 if (count > 1) { 12735 out.print(" ("); out.print(count); out.print(" filters)"); 12736 } 12737 out.println(); 12738 } 12739 12740 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12741 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12742 private int mFlags; 12743 } 12744 12745 static final class EphemeralIntentResolver 12746 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12747 /** 12748 * The result that has the highest defined order. Ordering applies on a 12749 * per-package basis. Mapping is from package name to Pair of order and 12750 * EphemeralResolveInfo. 12751 * <p> 12752 * NOTE: This is implemented as a field variable for convenience and efficiency. 12753 * By having a field variable, we're able to track filter ordering as soon as 12754 * a non-zero order is defined. Otherwise, multiple loops across the result set 12755 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12756 * this needs to be contained entirely within {@link #filterResults()}. 12757 */ 12758 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12759 12760 @Override 12761 protected AuxiliaryResolveInfo[] newArray(int size) { 12762 return new AuxiliaryResolveInfo[size]; 12763 } 12764 12765 @Override 12766 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12767 return true; 12768 } 12769 12770 @Override 12771 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12772 int userId) { 12773 if (!sUserManager.exists(userId)) { 12774 return null; 12775 } 12776 final String packageName = responseObj.resolveInfo.getPackageName(); 12777 final Integer order = responseObj.getOrder(); 12778 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12779 mOrderResult.get(packageName); 12780 // ordering is enabled and this item's order isn't high enough 12781 if (lastOrderResult != null && lastOrderResult.first >= order) { 12782 return null; 12783 } 12784 final EphemeralResolveInfo res = responseObj.resolveInfo; 12785 if (order > 0) { 12786 // non-zero order, enable ordering 12787 mOrderResult.put(packageName, new Pair<>(order, res)); 12788 } 12789 return responseObj; 12790 } 12791 12792 @Override 12793 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12794 // only do work if ordering is enabled [most of the time it won't be] 12795 if (mOrderResult.size() == 0) { 12796 return; 12797 } 12798 int resultSize = results.size(); 12799 for (int i = 0; i < resultSize; i++) { 12800 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12801 final String packageName = info.getPackageName(); 12802 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12803 if (savedInfo == null) { 12804 // package doesn't having ordering 12805 continue; 12806 } 12807 if (savedInfo.second == info) { 12808 // circled back to the highest ordered item; remove from order list 12809 mOrderResult.remove(savedInfo); 12810 if (mOrderResult.size() == 0) { 12811 // no more ordered items 12812 break; 12813 } 12814 continue; 12815 } 12816 // item has a worse order, remove it from the result list 12817 results.remove(i); 12818 resultSize--; 12819 i--; 12820 } 12821 } 12822 } 12823 12824 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12825 new Comparator<ResolveInfo>() { 12826 public int compare(ResolveInfo r1, ResolveInfo r2) { 12827 int v1 = r1.priority; 12828 int v2 = r2.priority; 12829 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12830 if (v1 != v2) { 12831 return (v1 > v2) ? -1 : 1; 12832 } 12833 v1 = r1.preferredOrder; 12834 v2 = r2.preferredOrder; 12835 if (v1 != v2) { 12836 return (v1 > v2) ? -1 : 1; 12837 } 12838 if (r1.isDefault != r2.isDefault) { 12839 return r1.isDefault ? -1 : 1; 12840 } 12841 v1 = r1.match; 12842 v2 = r2.match; 12843 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12844 if (v1 != v2) { 12845 return (v1 > v2) ? -1 : 1; 12846 } 12847 if (r1.system != r2.system) { 12848 return r1.system ? -1 : 1; 12849 } 12850 if (r1.activityInfo != null) { 12851 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12852 } 12853 if (r1.serviceInfo != null) { 12854 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12855 } 12856 if (r1.providerInfo != null) { 12857 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12858 } 12859 return 0; 12860 } 12861 }; 12862 12863 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12864 new Comparator<ProviderInfo>() { 12865 public int compare(ProviderInfo p1, ProviderInfo p2) { 12866 final int v1 = p1.initOrder; 12867 final int v2 = p2.initOrder; 12868 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12869 } 12870 }; 12871 12872 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12873 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12874 final int[] userIds) { 12875 mHandler.post(new Runnable() { 12876 @Override 12877 public void run() { 12878 try { 12879 final IActivityManager am = ActivityManager.getService(); 12880 if (am == null) return; 12881 final int[] resolvedUserIds; 12882 if (userIds == null) { 12883 resolvedUserIds = am.getRunningUserIds(); 12884 } else { 12885 resolvedUserIds = userIds; 12886 } 12887 for (int id : resolvedUserIds) { 12888 final Intent intent = new Intent(action, 12889 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12890 if (extras != null) { 12891 intent.putExtras(extras); 12892 } 12893 if (targetPkg != null) { 12894 intent.setPackage(targetPkg); 12895 } 12896 // Modify the UID when posting to other users 12897 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12898 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12899 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12900 intent.putExtra(Intent.EXTRA_UID, uid); 12901 } 12902 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12903 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12904 if (DEBUG_BROADCASTS) { 12905 RuntimeException here = new RuntimeException("here"); 12906 here.fillInStackTrace(); 12907 Slog.d(TAG, "Sending to user " + id + ": " 12908 + intent.toShortString(false, true, false, false) 12909 + " " + intent.getExtras(), here); 12910 } 12911 am.broadcastIntent(null, intent, null, finishedReceiver, 12912 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12913 null, finishedReceiver != null, false, id); 12914 } 12915 } catch (RemoteException ex) { 12916 } 12917 } 12918 }); 12919 } 12920 12921 /** 12922 * Check if the external storage media is available. This is true if there 12923 * is a mounted external storage medium or if the external storage is 12924 * emulated. 12925 */ 12926 private boolean isExternalMediaAvailable() { 12927 return mMediaMounted || Environment.isExternalStorageEmulated(); 12928 } 12929 12930 @Override 12931 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12932 // writer 12933 synchronized (mPackages) { 12934 if (!isExternalMediaAvailable()) { 12935 // If the external storage is no longer mounted at this point, 12936 // the caller may not have been able to delete all of this 12937 // packages files and can not delete any more. Bail. 12938 return null; 12939 } 12940 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12941 if (lastPackage != null) { 12942 pkgs.remove(lastPackage); 12943 } 12944 if (pkgs.size() > 0) { 12945 return pkgs.get(0); 12946 } 12947 } 12948 return null; 12949 } 12950 12951 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12952 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12953 userId, andCode ? 1 : 0, packageName); 12954 if (mSystemReady) { 12955 msg.sendToTarget(); 12956 } else { 12957 if (mPostSystemReadyMessages == null) { 12958 mPostSystemReadyMessages = new ArrayList<>(); 12959 } 12960 mPostSystemReadyMessages.add(msg); 12961 } 12962 } 12963 12964 void startCleaningPackages() { 12965 // reader 12966 if (!isExternalMediaAvailable()) { 12967 return; 12968 } 12969 synchronized (mPackages) { 12970 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12971 return; 12972 } 12973 } 12974 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12975 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12976 IActivityManager am = ActivityManager.getService(); 12977 if (am != null) { 12978 try { 12979 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12980 UserHandle.USER_SYSTEM); 12981 } catch (RemoteException e) { 12982 } 12983 } 12984 } 12985 12986 @Override 12987 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12988 int installFlags, String installerPackageName, int userId) { 12989 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12990 12991 final int callingUid = Binder.getCallingUid(); 12992 enforceCrossUserPermission(callingUid, userId, 12993 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12994 12995 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12996 try { 12997 if (observer != null) { 12998 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12999 } 13000 } catch (RemoteException re) { 13001 } 13002 return; 13003 } 13004 13005 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13006 installFlags |= PackageManager.INSTALL_FROM_ADB; 13007 13008 } else { 13009 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13010 // about installerPackageName. 13011 13012 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13013 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13014 } 13015 13016 UserHandle user; 13017 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13018 user = UserHandle.ALL; 13019 } else { 13020 user = new UserHandle(userId); 13021 } 13022 13023 // Only system components can circumvent runtime permissions when installing. 13024 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13025 && mContext.checkCallingOrSelfPermission(Manifest.permission 13026 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13027 throw new SecurityException("You need the " 13028 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13029 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13030 } 13031 13032 final File originFile = new File(originPath); 13033 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13034 13035 final Message msg = mHandler.obtainMessage(INIT_COPY); 13036 final VerificationInfo verificationInfo = new VerificationInfo( 13037 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13038 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13039 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13040 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13041 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13042 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13043 msg.obj = params; 13044 13045 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13046 System.identityHashCode(msg.obj)); 13047 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13048 System.identityHashCode(msg.obj)); 13049 13050 mHandler.sendMessage(msg); 13051 } 13052 13053 13054 /** 13055 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13056 * it is acting on behalf on an enterprise or the user). 13057 * 13058 * Note that the ordering of the conditionals in this method is important. The checks we perform 13059 * are as follows, in this order: 13060 * 13061 * 1) If the install is being performed by a system app, we can trust the app to have set the 13062 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13063 * what it is. 13064 * 2) If the install is being performed by a device or profile owner app, the install reason 13065 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13066 * set the install reason correctly. If the app targets an older SDK version where install 13067 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13068 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13069 * 3) In all other cases, the install is being performed by a regular app that is neither part 13070 * of the system nor a device or profile owner. We have no reason to believe that this app is 13071 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13072 * set to enterprise policy and if so, change it to unknown instead. 13073 */ 13074 private int fixUpInstallReason(String installerPackageName, int installerUid, 13075 int installReason) { 13076 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13077 == PERMISSION_GRANTED) { 13078 // If the install is being performed by a system app, we trust that app to have set the 13079 // install reason correctly. 13080 return installReason; 13081 } 13082 13083 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13084 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13085 if (dpm != null) { 13086 ComponentName owner = null; 13087 try { 13088 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13089 if (owner == null) { 13090 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13091 } 13092 } catch (RemoteException e) { 13093 } 13094 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13095 // If the install is being performed by a device or profile owner, the install 13096 // reason should be enterprise policy. 13097 return PackageManager.INSTALL_REASON_POLICY; 13098 } 13099 } 13100 13101 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13102 // If the install is being performed by a regular app (i.e. neither system app nor 13103 // device or profile owner), we have no reason to believe that the app is acting on 13104 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13105 // change it to unknown instead. 13106 return PackageManager.INSTALL_REASON_UNKNOWN; 13107 } 13108 13109 // If the install is being performed by a regular app and the install reason was set to any 13110 // value but enterprise policy, leave the install reason unchanged. 13111 return installReason; 13112 } 13113 13114 void installStage(String packageName, File stagedDir, String stagedCid, 13115 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13116 String installerPackageName, int installerUid, UserHandle user, 13117 Certificate[][] certificates) { 13118 if (DEBUG_EPHEMERAL) { 13119 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13120 Slog.d(TAG, "Ephemeral install of " + packageName); 13121 } 13122 } 13123 final VerificationInfo verificationInfo = new VerificationInfo( 13124 sessionParams.originatingUri, sessionParams.referrerUri, 13125 sessionParams.originatingUid, installerUid); 13126 13127 final OriginInfo origin; 13128 if (stagedDir != null) { 13129 origin = OriginInfo.fromStagedFile(stagedDir); 13130 } else { 13131 origin = OriginInfo.fromStagedContainer(stagedCid); 13132 } 13133 13134 final Message msg = mHandler.obtainMessage(INIT_COPY); 13135 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13136 sessionParams.installReason); 13137 final InstallParams params = new InstallParams(origin, null, observer, 13138 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13139 verificationInfo, user, sessionParams.abiOverride, 13140 sessionParams.grantedRuntimePermissions, certificates, installReason); 13141 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13142 msg.obj = params; 13143 13144 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13145 System.identityHashCode(msg.obj)); 13146 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13147 System.identityHashCode(msg.obj)); 13148 13149 mHandler.sendMessage(msg); 13150 } 13151 13152 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13153 int userId) { 13154 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13155 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13156 } 13157 13158 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13159 int appId, int... userIds) { 13160 if (ArrayUtils.isEmpty(userIds)) { 13161 return; 13162 } 13163 Bundle extras = new Bundle(1); 13164 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13165 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13166 13167 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13168 packageName, extras, 0, null, null, userIds); 13169 if (isSystem) { 13170 mHandler.post(() -> { 13171 for (int userId : userIds) { 13172 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13173 } 13174 } 13175 ); 13176 } 13177 } 13178 13179 /** 13180 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13181 * automatically without needing an explicit launch. 13182 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13183 */ 13184 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13185 // If user is not running, the app didn't miss any broadcast 13186 if (!mUserManagerInternal.isUserRunning(userId)) { 13187 return; 13188 } 13189 final IActivityManager am = ActivityManager.getService(); 13190 try { 13191 // Deliver LOCKED_BOOT_COMPLETED first 13192 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13193 .setPackage(packageName); 13194 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13195 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13196 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13197 13198 // Deliver BOOT_COMPLETED only if user is unlocked 13199 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13200 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13201 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13202 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13203 } 13204 } catch (RemoteException e) { 13205 throw e.rethrowFromSystemServer(); 13206 } 13207 } 13208 13209 @Override 13210 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13211 int userId) { 13212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13213 PackageSetting pkgSetting; 13214 final int uid = Binder.getCallingUid(); 13215 enforceCrossUserPermission(uid, userId, 13216 true /* requireFullPermission */, true /* checkShell */, 13217 "setApplicationHiddenSetting for user " + userId); 13218 13219 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13220 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13221 return false; 13222 } 13223 13224 long callingId = Binder.clearCallingIdentity(); 13225 try { 13226 boolean sendAdded = false; 13227 boolean sendRemoved = false; 13228 // writer 13229 synchronized (mPackages) { 13230 pkgSetting = mSettings.mPackages.get(packageName); 13231 if (pkgSetting == null) { 13232 return false; 13233 } 13234 // Do not allow "android" is being disabled 13235 if ("android".equals(packageName)) { 13236 Slog.w(TAG, "Cannot hide package: android"); 13237 return false; 13238 } 13239 // Cannot hide static shared libs as they are considered 13240 // a part of the using app (emulating static linking). Also 13241 // static libs are installed always on internal storage. 13242 PackageParser.Package pkg = mPackages.get(packageName); 13243 if (pkg != null && pkg.staticSharedLibName != null) { 13244 Slog.w(TAG, "Cannot hide package: " + packageName 13245 + " providing static shared library: " 13246 + pkg.staticSharedLibName); 13247 return false; 13248 } 13249 // Only allow protected packages to hide themselves. 13250 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13251 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13252 Slog.w(TAG, "Not hiding protected package: " + packageName); 13253 return false; 13254 } 13255 13256 if (pkgSetting.getHidden(userId) != hidden) { 13257 pkgSetting.setHidden(hidden, userId); 13258 mSettings.writePackageRestrictionsLPr(userId); 13259 if (hidden) { 13260 sendRemoved = true; 13261 } else { 13262 sendAdded = true; 13263 } 13264 } 13265 } 13266 if (sendAdded) { 13267 sendPackageAddedForUser(packageName, pkgSetting, userId); 13268 return true; 13269 } 13270 if (sendRemoved) { 13271 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13272 "hiding pkg"); 13273 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13274 return true; 13275 } 13276 } finally { 13277 Binder.restoreCallingIdentity(callingId); 13278 } 13279 return false; 13280 } 13281 13282 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13283 int userId) { 13284 final PackageRemovedInfo info = new PackageRemovedInfo(); 13285 info.removedPackage = packageName; 13286 info.removedUsers = new int[] {userId}; 13287 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13288 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13289 } 13290 13291 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13292 if (pkgList.length > 0) { 13293 Bundle extras = new Bundle(1); 13294 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13295 13296 sendPackageBroadcast( 13297 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13298 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13299 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13300 new int[] {userId}); 13301 } 13302 } 13303 13304 /** 13305 * Returns true if application is not found or there was an error. Otherwise it returns 13306 * the hidden state of the package for the given user. 13307 */ 13308 @Override 13309 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13311 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13312 true /* requireFullPermission */, false /* checkShell */, 13313 "getApplicationHidden for user " + userId); 13314 PackageSetting pkgSetting; 13315 long callingId = Binder.clearCallingIdentity(); 13316 try { 13317 // writer 13318 synchronized (mPackages) { 13319 pkgSetting = mSettings.mPackages.get(packageName); 13320 if (pkgSetting == null) { 13321 return true; 13322 } 13323 return pkgSetting.getHidden(userId); 13324 } 13325 } finally { 13326 Binder.restoreCallingIdentity(callingId); 13327 } 13328 } 13329 13330 /** 13331 * @hide 13332 */ 13333 @Override 13334 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13335 int installReason) { 13336 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13337 null); 13338 PackageSetting pkgSetting; 13339 final int uid = Binder.getCallingUid(); 13340 enforceCrossUserPermission(uid, userId, 13341 true /* requireFullPermission */, true /* checkShell */, 13342 "installExistingPackage for user " + userId); 13343 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13344 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13345 } 13346 13347 long callingId = Binder.clearCallingIdentity(); 13348 try { 13349 boolean installed = false; 13350 final boolean instantApp = 13351 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13352 final boolean fullApp = 13353 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13354 13355 // writer 13356 synchronized (mPackages) { 13357 pkgSetting = mSettings.mPackages.get(packageName); 13358 if (pkgSetting == null) { 13359 return PackageManager.INSTALL_FAILED_INVALID_URI; 13360 } 13361 if (!pkgSetting.getInstalled(userId)) { 13362 pkgSetting.setInstalled(true, userId); 13363 pkgSetting.setHidden(false, userId); 13364 pkgSetting.setInstallReason(installReason, userId); 13365 mSettings.writePackageRestrictionsLPr(userId); 13366 mSettings.writeKernelMappingLPr(pkgSetting); 13367 installed = true; 13368 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13369 // upgrade app from instant to full; we don't allow app downgrade 13370 installed = true; 13371 } 13372 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13373 } 13374 13375 if (installed) { 13376 if (pkgSetting.pkg != null) { 13377 synchronized (mInstallLock) { 13378 // We don't need to freeze for a brand new install 13379 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13380 } 13381 } 13382 sendPackageAddedForUser(packageName, pkgSetting, userId); 13383 synchronized (mPackages) { 13384 updateSequenceNumberLP(packageName, new int[]{ userId }); 13385 } 13386 } 13387 } finally { 13388 Binder.restoreCallingIdentity(callingId); 13389 } 13390 13391 return PackageManager.INSTALL_SUCCEEDED; 13392 } 13393 13394 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13395 boolean instantApp, boolean fullApp) { 13396 // no state specified; do nothing 13397 if (!instantApp && !fullApp) { 13398 return; 13399 } 13400 if (userId != UserHandle.USER_ALL) { 13401 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13402 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13403 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13404 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13405 } 13406 } else { 13407 for (int currentUserId : sUserManager.getUserIds()) { 13408 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13409 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13410 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13411 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13412 } 13413 } 13414 } 13415 } 13416 13417 boolean isUserRestricted(int userId, String restrictionKey) { 13418 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13419 if (restrictions.getBoolean(restrictionKey, false)) { 13420 Log.w(TAG, "User is restricted: " + restrictionKey); 13421 return true; 13422 } 13423 return false; 13424 } 13425 13426 @Override 13427 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13428 int userId) { 13429 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13430 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13431 true /* requireFullPermission */, true /* checkShell */, 13432 "setPackagesSuspended for user " + userId); 13433 13434 if (ArrayUtils.isEmpty(packageNames)) { 13435 return packageNames; 13436 } 13437 13438 // List of package names for whom the suspended state has changed. 13439 List<String> changedPackages = new ArrayList<>(packageNames.length); 13440 // List of package names for whom the suspended state is not set as requested in this 13441 // method. 13442 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13443 long callingId = Binder.clearCallingIdentity(); 13444 try { 13445 for (int i = 0; i < packageNames.length; i++) { 13446 String packageName = packageNames[i]; 13447 boolean changed = false; 13448 final int appId; 13449 synchronized (mPackages) { 13450 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13451 if (pkgSetting == null) { 13452 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13453 + "\". Skipping suspending/un-suspending."); 13454 unactionedPackages.add(packageName); 13455 continue; 13456 } 13457 appId = pkgSetting.appId; 13458 if (pkgSetting.getSuspended(userId) != suspended) { 13459 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13460 unactionedPackages.add(packageName); 13461 continue; 13462 } 13463 pkgSetting.setSuspended(suspended, userId); 13464 mSettings.writePackageRestrictionsLPr(userId); 13465 changed = true; 13466 changedPackages.add(packageName); 13467 } 13468 } 13469 13470 if (changed && suspended) { 13471 killApplication(packageName, UserHandle.getUid(userId, appId), 13472 "suspending package"); 13473 } 13474 } 13475 } finally { 13476 Binder.restoreCallingIdentity(callingId); 13477 } 13478 13479 if (!changedPackages.isEmpty()) { 13480 sendPackagesSuspendedForUser(changedPackages.toArray( 13481 new String[changedPackages.size()]), userId, suspended); 13482 } 13483 13484 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13485 } 13486 13487 @Override 13488 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13490 true /* requireFullPermission */, false /* checkShell */, 13491 "isPackageSuspendedForUser for user " + userId); 13492 synchronized (mPackages) { 13493 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13494 if (pkgSetting == null) { 13495 throw new IllegalArgumentException("Unknown target package: " + packageName); 13496 } 13497 return pkgSetting.getSuspended(userId); 13498 } 13499 } 13500 13501 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13502 if (isPackageDeviceAdmin(packageName, userId)) { 13503 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13504 + "\": has an active device admin"); 13505 return false; 13506 } 13507 13508 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13509 if (packageName.equals(activeLauncherPackageName)) { 13510 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13511 + "\": contains the active launcher"); 13512 return false; 13513 } 13514 13515 if (packageName.equals(mRequiredInstallerPackage)) { 13516 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13517 + "\": required for package installation"); 13518 return false; 13519 } 13520 13521 if (packageName.equals(mRequiredUninstallerPackage)) { 13522 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13523 + "\": required for package uninstallation"); 13524 return false; 13525 } 13526 13527 if (packageName.equals(mRequiredVerifierPackage)) { 13528 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13529 + "\": required for package verification"); 13530 return false; 13531 } 13532 13533 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13534 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13535 + "\": is the default dialer"); 13536 return false; 13537 } 13538 13539 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13540 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13541 + "\": protected package"); 13542 return false; 13543 } 13544 13545 // Cannot suspend static shared libs as they are considered 13546 // a part of the using app (emulating static linking). Also 13547 // static libs are installed always on internal storage. 13548 PackageParser.Package pkg = mPackages.get(packageName); 13549 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13550 Slog.w(TAG, "Cannot suspend package: " + packageName 13551 + " providing static shared library: " 13552 + pkg.staticSharedLibName); 13553 return false; 13554 } 13555 13556 return true; 13557 } 13558 13559 private String getActiveLauncherPackageName(int userId) { 13560 Intent intent = new Intent(Intent.ACTION_MAIN); 13561 intent.addCategory(Intent.CATEGORY_HOME); 13562 ResolveInfo resolveInfo = resolveIntent( 13563 intent, 13564 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13565 PackageManager.MATCH_DEFAULT_ONLY, 13566 userId); 13567 13568 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13569 } 13570 13571 private String getDefaultDialerPackageName(int userId) { 13572 synchronized (mPackages) { 13573 return mSettings.getDefaultDialerPackageNameLPw(userId); 13574 } 13575 } 13576 13577 @Override 13578 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13579 mContext.enforceCallingOrSelfPermission( 13580 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13581 "Only package verification agents can verify applications"); 13582 13583 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13584 final PackageVerificationResponse response = new PackageVerificationResponse( 13585 verificationCode, Binder.getCallingUid()); 13586 msg.arg1 = id; 13587 msg.obj = response; 13588 mHandler.sendMessage(msg); 13589 } 13590 13591 @Override 13592 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13593 long millisecondsToDelay) { 13594 mContext.enforceCallingOrSelfPermission( 13595 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13596 "Only package verification agents can extend verification timeouts"); 13597 13598 final PackageVerificationState state = mPendingVerification.get(id); 13599 final PackageVerificationResponse response = new PackageVerificationResponse( 13600 verificationCodeAtTimeout, Binder.getCallingUid()); 13601 13602 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13603 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13604 } 13605 if (millisecondsToDelay < 0) { 13606 millisecondsToDelay = 0; 13607 } 13608 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13609 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13610 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13611 } 13612 13613 if ((state != null) && !state.timeoutExtended()) { 13614 state.extendTimeout(); 13615 13616 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13617 msg.arg1 = id; 13618 msg.obj = response; 13619 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13620 } 13621 } 13622 13623 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13624 int verificationCode, UserHandle user) { 13625 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13626 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13627 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13628 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13629 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13630 13631 mContext.sendBroadcastAsUser(intent, user, 13632 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13633 } 13634 13635 private ComponentName matchComponentForVerifier(String packageName, 13636 List<ResolveInfo> receivers) { 13637 ActivityInfo targetReceiver = null; 13638 13639 final int NR = receivers.size(); 13640 for (int i = 0; i < NR; i++) { 13641 final ResolveInfo info = receivers.get(i); 13642 if (info.activityInfo == null) { 13643 continue; 13644 } 13645 13646 if (packageName.equals(info.activityInfo.packageName)) { 13647 targetReceiver = info.activityInfo; 13648 break; 13649 } 13650 } 13651 13652 if (targetReceiver == null) { 13653 return null; 13654 } 13655 13656 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13657 } 13658 13659 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13660 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13661 if (pkgInfo.verifiers.length == 0) { 13662 return null; 13663 } 13664 13665 final int N = pkgInfo.verifiers.length; 13666 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13667 for (int i = 0; i < N; i++) { 13668 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13669 13670 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13671 receivers); 13672 if (comp == null) { 13673 continue; 13674 } 13675 13676 final int verifierUid = getUidForVerifier(verifierInfo); 13677 if (verifierUid == -1) { 13678 continue; 13679 } 13680 13681 if (DEBUG_VERIFY) { 13682 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13683 + " with the correct signature"); 13684 } 13685 sufficientVerifiers.add(comp); 13686 verificationState.addSufficientVerifier(verifierUid); 13687 } 13688 13689 return sufficientVerifiers; 13690 } 13691 13692 private int getUidForVerifier(VerifierInfo verifierInfo) { 13693 synchronized (mPackages) { 13694 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13695 if (pkg == null) { 13696 return -1; 13697 } else if (pkg.mSignatures.length != 1) { 13698 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13699 + " has more than one signature; ignoring"); 13700 return -1; 13701 } 13702 13703 /* 13704 * If the public key of the package's signature does not match 13705 * our expected public key, then this is a different package and 13706 * we should skip. 13707 */ 13708 13709 final byte[] expectedPublicKey; 13710 try { 13711 final Signature verifierSig = pkg.mSignatures[0]; 13712 final PublicKey publicKey = verifierSig.getPublicKey(); 13713 expectedPublicKey = publicKey.getEncoded(); 13714 } catch (CertificateException e) { 13715 return -1; 13716 } 13717 13718 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13719 13720 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13721 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13722 + " does not have the expected public key; ignoring"); 13723 return -1; 13724 } 13725 13726 return pkg.applicationInfo.uid; 13727 } 13728 } 13729 13730 @Override 13731 public void finishPackageInstall(int token, boolean didLaunch) { 13732 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13733 13734 if (DEBUG_INSTALL) { 13735 Slog.v(TAG, "BM finishing package install for " + token); 13736 } 13737 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13738 13739 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13740 mHandler.sendMessage(msg); 13741 } 13742 13743 /** 13744 * Get the verification agent timeout. 13745 * 13746 * @return verification timeout in milliseconds 13747 */ 13748 private long getVerificationTimeout() { 13749 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13750 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13751 DEFAULT_VERIFICATION_TIMEOUT); 13752 } 13753 13754 /** 13755 * Get the default verification agent response code. 13756 * 13757 * @return default verification response code 13758 */ 13759 private int getDefaultVerificationResponse() { 13760 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13761 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13762 DEFAULT_VERIFICATION_RESPONSE); 13763 } 13764 13765 /** 13766 * Check whether or not package verification has been enabled. 13767 * 13768 * @return true if verification should be performed 13769 */ 13770 private boolean isVerificationEnabled(int userId, int installFlags) { 13771 if (!DEFAULT_VERIFY_ENABLE) { 13772 return false; 13773 } 13774 // Ephemeral apps don't get the full verification treatment 13775 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13776 if (DEBUG_EPHEMERAL) { 13777 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13778 } 13779 return false; 13780 } 13781 13782 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13783 13784 // Check if installing from ADB 13785 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13786 // Do not run verification in a test harness environment 13787 if (ActivityManager.isRunningInTestHarness()) { 13788 return false; 13789 } 13790 if (ensureVerifyAppsEnabled) { 13791 return true; 13792 } 13793 // Check if the developer does not want package verification for ADB installs 13794 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13795 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13796 return false; 13797 } 13798 } 13799 13800 if (ensureVerifyAppsEnabled) { 13801 return true; 13802 } 13803 13804 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13805 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13806 } 13807 13808 @Override 13809 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13810 throws RemoteException { 13811 mContext.enforceCallingOrSelfPermission( 13812 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13813 "Only intentfilter verification agents can verify applications"); 13814 13815 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13816 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13817 Binder.getCallingUid(), verificationCode, failedDomains); 13818 msg.arg1 = id; 13819 msg.obj = response; 13820 mHandler.sendMessage(msg); 13821 } 13822 13823 @Override 13824 public int getIntentVerificationStatus(String packageName, int userId) { 13825 synchronized (mPackages) { 13826 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13827 } 13828 } 13829 13830 @Override 13831 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13832 mContext.enforceCallingOrSelfPermission( 13833 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13834 13835 boolean result = false; 13836 synchronized (mPackages) { 13837 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13838 } 13839 if (result) { 13840 scheduleWritePackageRestrictionsLocked(userId); 13841 } 13842 return result; 13843 } 13844 13845 @Override 13846 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13847 String packageName) { 13848 synchronized (mPackages) { 13849 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13850 } 13851 } 13852 13853 @Override 13854 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13855 if (TextUtils.isEmpty(packageName)) { 13856 return ParceledListSlice.emptyList(); 13857 } 13858 synchronized (mPackages) { 13859 PackageParser.Package pkg = mPackages.get(packageName); 13860 if (pkg == null || pkg.activities == null) { 13861 return ParceledListSlice.emptyList(); 13862 } 13863 final int count = pkg.activities.size(); 13864 ArrayList<IntentFilter> result = new ArrayList<>(); 13865 for (int n=0; n<count; n++) { 13866 PackageParser.Activity activity = pkg.activities.get(n); 13867 if (activity.intents != null && activity.intents.size() > 0) { 13868 result.addAll(activity.intents); 13869 } 13870 } 13871 return new ParceledListSlice<>(result); 13872 } 13873 } 13874 13875 @Override 13876 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13877 mContext.enforceCallingOrSelfPermission( 13878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13879 13880 synchronized (mPackages) { 13881 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13882 if (packageName != null) { 13883 result |= updateIntentVerificationStatus(packageName, 13884 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13885 userId); 13886 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13887 packageName, userId); 13888 } 13889 return result; 13890 } 13891 } 13892 13893 @Override 13894 public String getDefaultBrowserPackageName(int userId) { 13895 synchronized (mPackages) { 13896 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13897 } 13898 } 13899 13900 /** 13901 * Get the "allow unknown sources" setting. 13902 * 13903 * @return the current "allow unknown sources" setting 13904 */ 13905 private int getUnknownSourcesSettings() { 13906 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13907 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13908 -1); 13909 } 13910 13911 @Override 13912 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13913 final int uid = Binder.getCallingUid(); 13914 // writer 13915 synchronized (mPackages) { 13916 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13917 if (targetPackageSetting == null) { 13918 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13919 } 13920 13921 PackageSetting installerPackageSetting; 13922 if (installerPackageName != null) { 13923 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13924 if (installerPackageSetting == null) { 13925 throw new IllegalArgumentException("Unknown installer package: " 13926 + installerPackageName); 13927 } 13928 } else { 13929 installerPackageSetting = null; 13930 } 13931 13932 Signature[] callerSignature; 13933 Object obj = mSettings.getUserIdLPr(uid); 13934 if (obj != null) { 13935 if (obj instanceof SharedUserSetting) { 13936 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13937 } else if (obj instanceof PackageSetting) { 13938 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13939 } else { 13940 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13941 } 13942 } else { 13943 throw new SecurityException("Unknown calling UID: " + uid); 13944 } 13945 13946 // Verify: can't set installerPackageName to a package that is 13947 // not signed with the same cert as the caller. 13948 if (installerPackageSetting != null) { 13949 if (compareSignatures(callerSignature, 13950 installerPackageSetting.signatures.mSignatures) 13951 != PackageManager.SIGNATURE_MATCH) { 13952 throw new SecurityException( 13953 "Caller does not have same cert as new installer package " 13954 + installerPackageName); 13955 } 13956 } 13957 13958 // Verify: if target already has an installer package, it must 13959 // be signed with the same cert as the caller. 13960 if (targetPackageSetting.installerPackageName != null) { 13961 PackageSetting setting = mSettings.mPackages.get( 13962 targetPackageSetting.installerPackageName); 13963 // If the currently set package isn't valid, then it's always 13964 // okay to change it. 13965 if (setting != null) { 13966 if (compareSignatures(callerSignature, 13967 setting.signatures.mSignatures) 13968 != PackageManager.SIGNATURE_MATCH) { 13969 throw new SecurityException( 13970 "Caller does not have same cert as old installer package " 13971 + targetPackageSetting.installerPackageName); 13972 } 13973 } 13974 } 13975 13976 // Okay! 13977 targetPackageSetting.installerPackageName = installerPackageName; 13978 if (installerPackageName != null) { 13979 mSettings.mInstallerPackages.add(installerPackageName); 13980 } 13981 scheduleWriteSettingsLocked(); 13982 } 13983 } 13984 13985 @Override 13986 public void setApplicationCategoryHint(String packageName, int categoryHint, 13987 String callerPackageName) { 13988 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13989 callerPackageName); 13990 synchronized (mPackages) { 13991 PackageSetting ps = mSettings.mPackages.get(packageName); 13992 if (ps == null) { 13993 throw new IllegalArgumentException("Unknown target package " + packageName); 13994 } 13995 13996 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13997 throw new IllegalArgumentException("Calling package " + callerPackageName 13998 + " is not installer for " + packageName); 13999 } 14000 14001 if (ps.categoryHint != categoryHint) { 14002 ps.categoryHint = categoryHint; 14003 scheduleWriteSettingsLocked(); 14004 } 14005 } 14006 } 14007 14008 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14009 // Queue up an async operation since the package installation may take a little while. 14010 mHandler.post(new Runnable() { 14011 public void run() { 14012 mHandler.removeCallbacks(this); 14013 // Result object to be returned 14014 PackageInstalledInfo res = new PackageInstalledInfo(); 14015 res.setReturnCode(currentStatus); 14016 res.uid = -1; 14017 res.pkg = null; 14018 res.removedInfo = null; 14019 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14020 args.doPreInstall(res.returnCode); 14021 synchronized (mInstallLock) { 14022 installPackageTracedLI(args, res); 14023 } 14024 args.doPostInstall(res.returnCode, res.uid); 14025 } 14026 14027 // A restore should be performed at this point if (a) the install 14028 // succeeded, (b) the operation is not an update, and (c) the new 14029 // package has not opted out of backup participation. 14030 final boolean update = res.removedInfo != null 14031 && res.removedInfo.removedPackage != null; 14032 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14033 boolean doRestore = !update 14034 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14035 14036 // Set up the post-install work request bookkeeping. This will be used 14037 // and cleaned up by the post-install event handling regardless of whether 14038 // there's a restore pass performed. Token values are >= 1. 14039 int token; 14040 if (mNextInstallToken < 0) mNextInstallToken = 1; 14041 token = mNextInstallToken++; 14042 14043 PostInstallData data = new PostInstallData(args, res); 14044 mRunningInstalls.put(token, data); 14045 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14046 14047 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14048 // Pass responsibility to the Backup Manager. It will perform a 14049 // restore if appropriate, then pass responsibility back to the 14050 // Package Manager to run the post-install observer callbacks 14051 // and broadcasts. 14052 IBackupManager bm = IBackupManager.Stub.asInterface( 14053 ServiceManager.getService(Context.BACKUP_SERVICE)); 14054 if (bm != null) { 14055 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14056 + " to BM for possible restore"); 14057 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14058 try { 14059 // TODO: http://b/22388012 14060 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14061 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14062 } else { 14063 doRestore = false; 14064 } 14065 } catch (RemoteException e) { 14066 // can't happen; the backup manager is local 14067 } catch (Exception e) { 14068 Slog.e(TAG, "Exception trying to enqueue restore", e); 14069 doRestore = false; 14070 } 14071 } else { 14072 Slog.e(TAG, "Backup Manager not found!"); 14073 doRestore = false; 14074 } 14075 } 14076 14077 if (!doRestore) { 14078 // No restore possible, or the Backup Manager was mysteriously not 14079 // available -- just fire the post-install work request directly. 14080 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14081 14082 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14083 14084 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14085 mHandler.sendMessage(msg); 14086 } 14087 } 14088 }); 14089 } 14090 14091 /** 14092 * Callback from PackageSettings whenever an app is first transitioned out of the 14093 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14094 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14095 * here whether the app is the target of an ongoing install, and only send the 14096 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14097 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14098 * handling. 14099 */ 14100 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14101 // Serialize this with the rest of the install-process message chain. In the 14102 // restore-at-install case, this Runnable will necessarily run before the 14103 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14104 // are coherent. In the non-restore case, the app has already completed install 14105 // and been launched through some other means, so it is not in a problematic 14106 // state for observers to see the FIRST_LAUNCH signal. 14107 mHandler.post(new Runnable() { 14108 @Override 14109 public void run() { 14110 for (int i = 0; i < mRunningInstalls.size(); i++) { 14111 final PostInstallData data = mRunningInstalls.valueAt(i); 14112 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14113 continue; 14114 } 14115 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14116 // right package; but is it for the right user? 14117 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14118 if (userId == data.res.newUsers[uIndex]) { 14119 if (DEBUG_BACKUP) { 14120 Slog.i(TAG, "Package " + pkgName 14121 + " being restored so deferring FIRST_LAUNCH"); 14122 } 14123 return; 14124 } 14125 } 14126 } 14127 } 14128 // didn't find it, so not being restored 14129 if (DEBUG_BACKUP) { 14130 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14131 } 14132 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14133 } 14134 }); 14135 } 14136 14137 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14138 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14139 installerPkg, null, userIds); 14140 } 14141 14142 private abstract class HandlerParams { 14143 private static final int MAX_RETRIES = 4; 14144 14145 /** 14146 * Number of times startCopy() has been attempted and had a non-fatal 14147 * error. 14148 */ 14149 private int mRetries = 0; 14150 14151 /** User handle for the user requesting the information or installation. */ 14152 private final UserHandle mUser; 14153 String traceMethod; 14154 int traceCookie; 14155 14156 HandlerParams(UserHandle user) { 14157 mUser = user; 14158 } 14159 14160 UserHandle getUser() { 14161 return mUser; 14162 } 14163 14164 HandlerParams setTraceMethod(String traceMethod) { 14165 this.traceMethod = traceMethod; 14166 return this; 14167 } 14168 14169 HandlerParams setTraceCookie(int traceCookie) { 14170 this.traceCookie = traceCookie; 14171 return this; 14172 } 14173 14174 final boolean startCopy() { 14175 boolean res; 14176 try { 14177 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14178 14179 if (++mRetries > MAX_RETRIES) { 14180 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14181 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14182 handleServiceError(); 14183 return false; 14184 } else { 14185 handleStartCopy(); 14186 res = true; 14187 } 14188 } catch (RemoteException e) { 14189 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14190 mHandler.sendEmptyMessage(MCS_RECONNECT); 14191 res = false; 14192 } 14193 handleReturnCode(); 14194 return res; 14195 } 14196 14197 final void serviceError() { 14198 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14199 handleServiceError(); 14200 handleReturnCode(); 14201 } 14202 14203 abstract void handleStartCopy() throws RemoteException; 14204 abstract void handleServiceError(); 14205 abstract void handleReturnCode(); 14206 } 14207 14208 class MeasureParams extends HandlerParams { 14209 private final PackageStats mStats; 14210 private boolean mSuccess; 14211 14212 private final IPackageStatsObserver mObserver; 14213 14214 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14215 super(new UserHandle(stats.userHandle)); 14216 mObserver = observer; 14217 mStats = stats; 14218 } 14219 14220 @Override 14221 public String toString() { 14222 return "MeasureParams{" 14223 + Integer.toHexString(System.identityHashCode(this)) 14224 + " " + mStats.packageName + "}"; 14225 } 14226 14227 @Override 14228 void handleStartCopy() throws RemoteException { 14229 synchronized (mInstallLock) { 14230 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14231 } 14232 14233 if (mSuccess) { 14234 boolean mounted = false; 14235 try { 14236 final String status = Environment.getExternalStorageState(); 14237 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14238 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14239 } catch (Exception e) { 14240 } 14241 14242 if (mounted) { 14243 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14244 14245 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14246 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14247 14248 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14249 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14250 14251 // Always subtract cache size, since it's a subdirectory 14252 mStats.externalDataSize -= mStats.externalCacheSize; 14253 14254 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14255 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14256 14257 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14258 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14259 } 14260 } 14261 } 14262 14263 @Override 14264 void handleReturnCode() { 14265 if (mObserver != null) { 14266 try { 14267 mObserver.onGetStatsCompleted(mStats, mSuccess); 14268 } catch (RemoteException e) { 14269 Slog.i(TAG, "Observer no longer exists."); 14270 } 14271 } 14272 } 14273 14274 @Override 14275 void handleServiceError() { 14276 Slog.e(TAG, "Could not measure application " + mStats.packageName 14277 + " external storage"); 14278 } 14279 } 14280 14281 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14282 throws RemoteException { 14283 long result = 0; 14284 for (File path : paths) { 14285 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14286 } 14287 return result; 14288 } 14289 14290 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14291 for (File path : paths) { 14292 try { 14293 mcs.clearDirectory(path.getAbsolutePath()); 14294 } catch (RemoteException e) { 14295 } 14296 } 14297 } 14298 14299 static class OriginInfo { 14300 /** 14301 * Location where install is coming from, before it has been 14302 * copied/renamed into place. This could be a single monolithic APK 14303 * file, or a cluster directory. This location may be untrusted. 14304 */ 14305 final File file; 14306 final String cid; 14307 14308 /** 14309 * Flag indicating that {@link #file} or {@link #cid} has already been 14310 * staged, meaning downstream users don't need to defensively copy the 14311 * contents. 14312 */ 14313 final boolean staged; 14314 14315 /** 14316 * Flag indicating that {@link #file} or {@link #cid} is an already 14317 * installed app that is being moved. 14318 */ 14319 final boolean existing; 14320 14321 final String resolvedPath; 14322 final File resolvedFile; 14323 14324 static OriginInfo fromNothing() { 14325 return new OriginInfo(null, null, false, false); 14326 } 14327 14328 static OriginInfo fromUntrustedFile(File file) { 14329 return new OriginInfo(file, null, false, false); 14330 } 14331 14332 static OriginInfo fromExistingFile(File file) { 14333 return new OriginInfo(file, null, false, true); 14334 } 14335 14336 static OriginInfo fromStagedFile(File file) { 14337 return new OriginInfo(file, null, true, false); 14338 } 14339 14340 static OriginInfo fromStagedContainer(String cid) { 14341 return new OriginInfo(null, cid, true, false); 14342 } 14343 14344 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14345 this.file = file; 14346 this.cid = cid; 14347 this.staged = staged; 14348 this.existing = existing; 14349 14350 if (cid != null) { 14351 resolvedPath = PackageHelper.getSdDir(cid); 14352 resolvedFile = new File(resolvedPath); 14353 } else if (file != null) { 14354 resolvedPath = file.getAbsolutePath(); 14355 resolvedFile = file; 14356 } else { 14357 resolvedPath = null; 14358 resolvedFile = null; 14359 } 14360 } 14361 } 14362 14363 static class MoveInfo { 14364 final int moveId; 14365 final String fromUuid; 14366 final String toUuid; 14367 final String packageName; 14368 final String dataAppName; 14369 final int appId; 14370 final String seinfo; 14371 final int targetSdkVersion; 14372 14373 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14374 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14375 this.moveId = moveId; 14376 this.fromUuid = fromUuid; 14377 this.toUuid = toUuid; 14378 this.packageName = packageName; 14379 this.dataAppName = dataAppName; 14380 this.appId = appId; 14381 this.seinfo = seinfo; 14382 this.targetSdkVersion = targetSdkVersion; 14383 } 14384 } 14385 14386 static class VerificationInfo { 14387 /** A constant used to indicate that a uid value is not present. */ 14388 public static final int NO_UID = -1; 14389 14390 /** URI referencing where the package was downloaded from. */ 14391 final Uri originatingUri; 14392 14393 /** HTTP referrer URI associated with the originatingURI. */ 14394 final Uri referrer; 14395 14396 /** UID of the application that the install request originated from. */ 14397 final int originatingUid; 14398 14399 /** UID of application requesting the install */ 14400 final int installerUid; 14401 14402 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14403 this.originatingUri = originatingUri; 14404 this.referrer = referrer; 14405 this.originatingUid = originatingUid; 14406 this.installerUid = installerUid; 14407 } 14408 } 14409 14410 class InstallParams extends HandlerParams { 14411 final OriginInfo origin; 14412 final MoveInfo move; 14413 final IPackageInstallObserver2 observer; 14414 int installFlags; 14415 final String installerPackageName; 14416 final String volumeUuid; 14417 private InstallArgs mArgs; 14418 private int mRet; 14419 final String packageAbiOverride; 14420 final String[] grantedRuntimePermissions; 14421 final VerificationInfo verificationInfo; 14422 final Certificate[][] certificates; 14423 final int installReason; 14424 14425 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14426 int installFlags, String installerPackageName, String volumeUuid, 14427 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14428 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14429 super(user); 14430 this.origin = origin; 14431 this.move = move; 14432 this.observer = observer; 14433 this.installFlags = installFlags; 14434 this.installerPackageName = installerPackageName; 14435 this.volumeUuid = volumeUuid; 14436 this.verificationInfo = verificationInfo; 14437 this.packageAbiOverride = packageAbiOverride; 14438 this.grantedRuntimePermissions = grantedPermissions; 14439 this.certificates = certificates; 14440 this.installReason = installReason; 14441 } 14442 14443 @Override 14444 public String toString() { 14445 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14446 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14447 } 14448 14449 private int installLocationPolicy(PackageInfoLite pkgLite) { 14450 String packageName = pkgLite.packageName; 14451 int installLocation = pkgLite.installLocation; 14452 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14453 // reader 14454 synchronized (mPackages) { 14455 // Currently installed package which the new package is attempting to replace or 14456 // null if no such package is installed. 14457 PackageParser.Package installedPkg = mPackages.get(packageName); 14458 // Package which currently owns the data which the new package will own if installed. 14459 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14460 // will be null whereas dataOwnerPkg will contain information about the package 14461 // which was uninstalled while keeping its data. 14462 PackageParser.Package dataOwnerPkg = installedPkg; 14463 if (dataOwnerPkg == null) { 14464 PackageSetting ps = mSettings.mPackages.get(packageName); 14465 if (ps != null) { 14466 dataOwnerPkg = ps.pkg; 14467 } 14468 } 14469 14470 if (dataOwnerPkg != null) { 14471 // If installed, the package will get access to data left on the device by its 14472 // predecessor. As a security measure, this is permited only if this is not a 14473 // version downgrade or if the predecessor package is marked as debuggable and 14474 // a downgrade is explicitly requested. 14475 // 14476 // On debuggable platform builds, downgrades are permitted even for 14477 // non-debuggable packages to make testing easier. Debuggable platform builds do 14478 // not offer security guarantees and thus it's OK to disable some security 14479 // mechanisms to make debugging/testing easier on those builds. However, even on 14480 // debuggable builds downgrades of packages are permitted only if requested via 14481 // installFlags. This is because we aim to keep the behavior of debuggable 14482 // platform builds as close as possible to the behavior of non-debuggable 14483 // platform builds. 14484 final boolean downgradeRequested = 14485 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14486 final boolean packageDebuggable = 14487 (dataOwnerPkg.applicationInfo.flags 14488 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14489 final boolean downgradePermitted = 14490 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14491 if (!downgradePermitted) { 14492 try { 14493 checkDowngrade(dataOwnerPkg, pkgLite); 14494 } catch (PackageManagerException e) { 14495 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14496 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14497 } 14498 } 14499 } 14500 14501 if (installedPkg != null) { 14502 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14503 // Check for updated system application. 14504 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14505 if (onSd) { 14506 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14507 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14508 } 14509 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14510 } else { 14511 if (onSd) { 14512 // Install flag overrides everything. 14513 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14514 } 14515 // If current upgrade specifies particular preference 14516 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14517 // Application explicitly specified internal. 14518 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14519 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14520 // App explictly prefers external. Let policy decide 14521 } else { 14522 // Prefer previous location 14523 if (isExternal(installedPkg)) { 14524 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14525 } 14526 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14527 } 14528 } 14529 } else { 14530 // Invalid install. Return error code 14531 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14532 } 14533 } 14534 } 14535 // All the special cases have been taken care of. 14536 // Return result based on recommended install location. 14537 if (onSd) { 14538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14539 } 14540 return pkgLite.recommendedInstallLocation; 14541 } 14542 14543 /* 14544 * Invoke remote method to get package information and install 14545 * location values. Override install location based on default 14546 * policy if needed and then create install arguments based 14547 * on the install location. 14548 */ 14549 public void handleStartCopy() throws RemoteException { 14550 int ret = PackageManager.INSTALL_SUCCEEDED; 14551 14552 // If we're already staged, we've firmly committed to an install location 14553 if (origin.staged) { 14554 if (origin.file != null) { 14555 installFlags |= PackageManager.INSTALL_INTERNAL; 14556 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14557 } else if (origin.cid != null) { 14558 installFlags |= PackageManager.INSTALL_EXTERNAL; 14559 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14560 } else { 14561 throw new IllegalStateException("Invalid stage location"); 14562 } 14563 } 14564 14565 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14566 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14567 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14568 PackageInfoLite pkgLite = null; 14569 14570 if (onInt && onSd) { 14571 // Check if both bits are set. 14572 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14573 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14574 } else if (onSd && ephemeral) { 14575 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14576 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14577 } else { 14578 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14579 packageAbiOverride); 14580 14581 if (DEBUG_EPHEMERAL && ephemeral) { 14582 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14583 } 14584 14585 /* 14586 * If we have too little free space, try to free cache 14587 * before giving up. 14588 */ 14589 if (!origin.staged && pkgLite.recommendedInstallLocation 14590 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14591 // TODO: focus freeing disk space on the target device 14592 final StorageManager storage = StorageManager.from(mContext); 14593 final long lowThreshold = storage.getStorageLowBytes( 14594 Environment.getDataDirectory()); 14595 14596 final long sizeBytes = mContainerService.calculateInstalledSize( 14597 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14598 14599 try { 14600 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14601 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14602 installFlags, packageAbiOverride); 14603 } catch (InstallerException e) { 14604 Slog.w(TAG, "Failed to free cache", e); 14605 } 14606 14607 /* 14608 * The cache free must have deleted the file we 14609 * downloaded to install. 14610 * 14611 * TODO: fix the "freeCache" call to not delete 14612 * the file we care about. 14613 */ 14614 if (pkgLite.recommendedInstallLocation 14615 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14616 pkgLite.recommendedInstallLocation 14617 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14618 } 14619 } 14620 } 14621 14622 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14623 int loc = pkgLite.recommendedInstallLocation; 14624 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14625 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14626 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14627 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14629 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14631 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14632 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14633 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14634 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14635 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14636 } else { 14637 // Override with defaults if needed. 14638 loc = installLocationPolicy(pkgLite); 14639 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14640 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14641 } else if (!onSd && !onInt) { 14642 // Override install location with flags 14643 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14644 // Set the flag to install on external media. 14645 installFlags |= PackageManager.INSTALL_EXTERNAL; 14646 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14647 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14648 if (DEBUG_EPHEMERAL) { 14649 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14650 } 14651 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14652 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14653 |PackageManager.INSTALL_INTERNAL); 14654 } else { 14655 // Make sure the flag for installing on external 14656 // media is unset 14657 installFlags |= PackageManager.INSTALL_INTERNAL; 14658 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14659 } 14660 } 14661 } 14662 } 14663 14664 final InstallArgs args = createInstallArgs(this); 14665 mArgs = args; 14666 14667 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14668 // TODO: http://b/22976637 14669 // Apps installed for "all" users use the device owner to verify the app 14670 UserHandle verifierUser = getUser(); 14671 if (verifierUser == UserHandle.ALL) { 14672 verifierUser = UserHandle.SYSTEM; 14673 } 14674 14675 /* 14676 * Determine if we have any installed package verifiers. If we 14677 * do, then we'll defer to them to verify the packages. 14678 */ 14679 final int requiredUid = mRequiredVerifierPackage == null ? -1 14680 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14681 verifierUser.getIdentifier()); 14682 if (!origin.existing && requiredUid != -1 14683 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14684 final Intent verification = new Intent( 14685 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14686 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14687 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14688 PACKAGE_MIME_TYPE); 14689 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14690 14691 // Query all live verifiers based on current user state 14692 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14693 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14694 14695 if (DEBUG_VERIFY) { 14696 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14697 + verification.toString() + " with " + pkgLite.verifiers.length 14698 + " optional verifiers"); 14699 } 14700 14701 final int verificationId = mPendingVerificationToken++; 14702 14703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14704 14705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14706 installerPackageName); 14707 14708 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14709 installFlags); 14710 14711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14712 pkgLite.packageName); 14713 14714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14715 pkgLite.versionCode); 14716 14717 if (verificationInfo != null) { 14718 if (verificationInfo.originatingUri != null) { 14719 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14720 verificationInfo.originatingUri); 14721 } 14722 if (verificationInfo.referrer != null) { 14723 verification.putExtra(Intent.EXTRA_REFERRER, 14724 verificationInfo.referrer); 14725 } 14726 if (verificationInfo.originatingUid >= 0) { 14727 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14728 verificationInfo.originatingUid); 14729 } 14730 if (verificationInfo.installerUid >= 0) { 14731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14732 verificationInfo.installerUid); 14733 } 14734 } 14735 14736 final PackageVerificationState verificationState = new PackageVerificationState( 14737 requiredUid, args); 14738 14739 mPendingVerification.append(verificationId, verificationState); 14740 14741 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14742 receivers, verificationState); 14743 14744 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14745 final long idleDuration = getVerificationTimeout(); 14746 14747 /* 14748 * If any sufficient verifiers were listed in the package 14749 * manifest, attempt to ask them. 14750 */ 14751 if (sufficientVerifiers != null) { 14752 final int N = sufficientVerifiers.size(); 14753 if (N == 0) { 14754 Slog.i(TAG, "Additional verifiers required, but none installed."); 14755 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14756 } else { 14757 for (int i = 0; i < N; i++) { 14758 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14759 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14760 verifierComponent.getPackageName(), idleDuration, 14761 verifierUser.getIdentifier(), false, "package verifier"); 14762 14763 final Intent sufficientIntent = new Intent(verification); 14764 sufficientIntent.setComponent(verifierComponent); 14765 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14766 } 14767 } 14768 } 14769 14770 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14771 mRequiredVerifierPackage, receivers); 14772 if (ret == PackageManager.INSTALL_SUCCEEDED 14773 && mRequiredVerifierPackage != null) { 14774 Trace.asyncTraceBegin( 14775 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14776 /* 14777 * Send the intent to the required verification agent, 14778 * but only start the verification timeout after the 14779 * target BroadcastReceivers have run. 14780 */ 14781 verification.setComponent(requiredVerifierComponent); 14782 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14783 requiredVerifierComponent.getPackageName(), idleDuration, 14784 verifierUser.getIdentifier(), false, "package verifier"); 14785 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14786 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14787 new BroadcastReceiver() { 14788 @Override 14789 public void onReceive(Context context, Intent intent) { 14790 final Message msg = mHandler 14791 .obtainMessage(CHECK_PENDING_VERIFICATION); 14792 msg.arg1 = verificationId; 14793 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14794 } 14795 }, null, 0, null, null); 14796 14797 /* 14798 * We don't want the copy to proceed until verification 14799 * succeeds, so null out this field. 14800 */ 14801 mArgs = null; 14802 } 14803 } else { 14804 /* 14805 * No package verification is enabled, so immediately start 14806 * the remote call to initiate copy using temporary file. 14807 */ 14808 ret = args.copyApk(mContainerService, true); 14809 } 14810 } 14811 14812 mRet = ret; 14813 } 14814 14815 @Override 14816 void handleReturnCode() { 14817 // If mArgs is null, then MCS couldn't be reached. When it 14818 // reconnects, it will try again to install. At that point, this 14819 // will succeed. 14820 if (mArgs != null) { 14821 processPendingInstall(mArgs, mRet); 14822 } 14823 } 14824 14825 @Override 14826 void handleServiceError() { 14827 mArgs = createInstallArgs(this); 14828 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14829 } 14830 14831 public boolean isForwardLocked() { 14832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14833 } 14834 } 14835 14836 /** 14837 * Used during creation of InstallArgs 14838 * 14839 * @param installFlags package installation flags 14840 * @return true if should be installed on external storage 14841 */ 14842 private static boolean installOnExternalAsec(int installFlags) { 14843 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14844 return false; 14845 } 14846 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14847 return true; 14848 } 14849 return false; 14850 } 14851 14852 /** 14853 * Used during creation of InstallArgs 14854 * 14855 * @param installFlags package installation flags 14856 * @return true if should be installed as forward locked 14857 */ 14858 private static boolean installForwardLocked(int installFlags) { 14859 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14860 } 14861 14862 private InstallArgs createInstallArgs(InstallParams params) { 14863 if (params.move != null) { 14864 return new MoveInstallArgs(params); 14865 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14866 return new AsecInstallArgs(params); 14867 } else { 14868 return new FileInstallArgs(params); 14869 } 14870 } 14871 14872 /** 14873 * Create args that describe an existing installed package. Typically used 14874 * when cleaning up old installs, or used as a move source. 14875 */ 14876 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14877 String resourcePath, String[] instructionSets) { 14878 final boolean isInAsec; 14879 if (installOnExternalAsec(installFlags)) { 14880 /* Apps on SD card are always in ASEC containers. */ 14881 isInAsec = true; 14882 } else if (installForwardLocked(installFlags) 14883 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14884 /* 14885 * Forward-locked apps are only in ASEC containers if they're the 14886 * new style 14887 */ 14888 isInAsec = true; 14889 } else { 14890 isInAsec = false; 14891 } 14892 14893 if (isInAsec) { 14894 return new AsecInstallArgs(codePath, instructionSets, 14895 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14896 } else { 14897 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14898 } 14899 } 14900 14901 static abstract class InstallArgs { 14902 /** @see InstallParams#origin */ 14903 final OriginInfo origin; 14904 /** @see InstallParams#move */ 14905 final MoveInfo move; 14906 14907 final IPackageInstallObserver2 observer; 14908 // Always refers to PackageManager flags only 14909 final int installFlags; 14910 final String installerPackageName; 14911 final String volumeUuid; 14912 final UserHandle user; 14913 final String abiOverride; 14914 final String[] installGrantPermissions; 14915 /** If non-null, drop an async trace when the install completes */ 14916 final String traceMethod; 14917 final int traceCookie; 14918 final Certificate[][] certificates; 14919 final int installReason; 14920 14921 // The list of instruction sets supported by this app. This is currently 14922 // only used during the rmdex() phase to clean up resources. We can get rid of this 14923 // if we move dex files under the common app path. 14924 /* nullable */ String[] instructionSets; 14925 14926 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14927 int installFlags, String installerPackageName, String volumeUuid, 14928 UserHandle user, String[] instructionSets, 14929 String abiOverride, String[] installGrantPermissions, 14930 String traceMethod, int traceCookie, Certificate[][] certificates, 14931 int installReason) { 14932 this.origin = origin; 14933 this.move = move; 14934 this.installFlags = installFlags; 14935 this.observer = observer; 14936 this.installerPackageName = installerPackageName; 14937 this.volumeUuid = volumeUuid; 14938 this.user = user; 14939 this.instructionSets = instructionSets; 14940 this.abiOverride = abiOverride; 14941 this.installGrantPermissions = installGrantPermissions; 14942 this.traceMethod = traceMethod; 14943 this.traceCookie = traceCookie; 14944 this.certificates = certificates; 14945 this.installReason = installReason; 14946 } 14947 14948 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14949 abstract int doPreInstall(int status); 14950 14951 /** 14952 * Rename package into final resting place. All paths on the given 14953 * scanned package should be updated to reflect the rename. 14954 */ 14955 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14956 abstract int doPostInstall(int status, int uid); 14957 14958 /** @see PackageSettingBase#codePathString */ 14959 abstract String getCodePath(); 14960 /** @see PackageSettingBase#resourcePathString */ 14961 abstract String getResourcePath(); 14962 14963 // Need installer lock especially for dex file removal. 14964 abstract void cleanUpResourcesLI(); 14965 abstract boolean doPostDeleteLI(boolean delete); 14966 14967 /** 14968 * Called before the source arguments are copied. This is used mostly 14969 * for MoveParams when it needs to read the source file to put it in the 14970 * destination. 14971 */ 14972 int doPreCopy() { 14973 return PackageManager.INSTALL_SUCCEEDED; 14974 } 14975 14976 /** 14977 * Called after the source arguments are copied. This is used mostly for 14978 * MoveParams when it needs to read the source file to put it in the 14979 * destination. 14980 */ 14981 int doPostCopy(int uid) { 14982 return PackageManager.INSTALL_SUCCEEDED; 14983 } 14984 14985 protected boolean isFwdLocked() { 14986 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14987 } 14988 14989 protected boolean isExternalAsec() { 14990 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14991 } 14992 14993 protected boolean isEphemeral() { 14994 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14995 } 14996 14997 UserHandle getUser() { 14998 return user; 14999 } 15000 } 15001 15002 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15003 if (!allCodePaths.isEmpty()) { 15004 if (instructionSets == null) { 15005 throw new IllegalStateException("instructionSet == null"); 15006 } 15007 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15008 for (String codePath : allCodePaths) { 15009 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15010 try { 15011 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15012 } catch (InstallerException ignored) { 15013 } 15014 } 15015 } 15016 } 15017 } 15018 15019 /** 15020 * Logic to handle installation of non-ASEC applications, including copying 15021 * and renaming logic. 15022 */ 15023 class FileInstallArgs extends InstallArgs { 15024 private File codeFile; 15025 private File resourceFile; 15026 15027 // Example topology: 15028 // /data/app/com.example/base.apk 15029 // /data/app/com.example/split_foo.apk 15030 // /data/app/com.example/lib/arm/libfoo.so 15031 // /data/app/com.example/lib/arm64/libfoo.so 15032 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15033 15034 /** New install */ 15035 FileInstallArgs(InstallParams params) { 15036 super(params.origin, params.move, params.observer, params.installFlags, 15037 params.installerPackageName, params.volumeUuid, 15038 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15039 params.grantedRuntimePermissions, 15040 params.traceMethod, params.traceCookie, params.certificates, 15041 params.installReason); 15042 if (isFwdLocked()) { 15043 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15044 } 15045 } 15046 15047 /** Existing install */ 15048 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15049 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15050 null, null, null, 0, null /*certificates*/, 15051 PackageManager.INSTALL_REASON_UNKNOWN); 15052 this.codeFile = (codePath != null) ? new File(codePath) : null; 15053 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15054 } 15055 15056 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15057 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15058 try { 15059 return doCopyApk(imcs, temp); 15060 } finally { 15061 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15062 } 15063 } 15064 15065 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15066 if (origin.staged) { 15067 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15068 codeFile = origin.file; 15069 resourceFile = origin.file; 15070 return PackageManager.INSTALL_SUCCEEDED; 15071 } 15072 15073 try { 15074 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15075 final File tempDir = 15076 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15077 codeFile = tempDir; 15078 resourceFile = tempDir; 15079 } catch (IOException e) { 15080 Slog.w(TAG, "Failed to create copy file: " + e); 15081 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15082 } 15083 15084 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15085 @Override 15086 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15087 if (!FileUtils.isValidExtFilename(name)) { 15088 throw new IllegalArgumentException("Invalid filename: " + name); 15089 } 15090 try { 15091 final File file = new File(codeFile, name); 15092 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15093 O_RDWR | O_CREAT, 0644); 15094 Os.chmod(file.getAbsolutePath(), 0644); 15095 return new ParcelFileDescriptor(fd); 15096 } catch (ErrnoException e) { 15097 throw new RemoteException("Failed to open: " + e.getMessage()); 15098 } 15099 } 15100 }; 15101 15102 int ret = PackageManager.INSTALL_SUCCEEDED; 15103 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15104 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15105 Slog.e(TAG, "Failed to copy package"); 15106 return ret; 15107 } 15108 15109 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15110 NativeLibraryHelper.Handle handle = null; 15111 try { 15112 handle = NativeLibraryHelper.Handle.create(codeFile); 15113 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15114 abiOverride); 15115 } catch (IOException e) { 15116 Slog.e(TAG, "Copying native libraries failed", e); 15117 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15118 } finally { 15119 IoUtils.closeQuietly(handle); 15120 } 15121 15122 return ret; 15123 } 15124 15125 int doPreInstall(int status) { 15126 if (status != PackageManager.INSTALL_SUCCEEDED) { 15127 cleanUp(); 15128 } 15129 return status; 15130 } 15131 15132 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15133 if (status != PackageManager.INSTALL_SUCCEEDED) { 15134 cleanUp(); 15135 return false; 15136 } 15137 15138 final File targetDir = codeFile.getParentFile(); 15139 final File beforeCodeFile = codeFile; 15140 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15141 15142 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15143 try { 15144 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15145 } catch (ErrnoException e) { 15146 Slog.w(TAG, "Failed to rename", e); 15147 return false; 15148 } 15149 15150 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15151 Slog.w(TAG, "Failed to restorecon"); 15152 return false; 15153 } 15154 15155 // Reflect the rename internally 15156 codeFile = afterCodeFile; 15157 resourceFile = afterCodeFile; 15158 15159 // Reflect the rename in scanned details 15160 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15161 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15162 afterCodeFile, pkg.baseCodePath)); 15163 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15164 afterCodeFile, pkg.splitCodePaths)); 15165 15166 // Reflect the rename in app info 15167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15168 pkg.setApplicationInfoCodePath(pkg.codePath); 15169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15171 pkg.setApplicationInfoResourcePath(pkg.codePath); 15172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15174 15175 return true; 15176 } 15177 15178 int doPostInstall(int status, int uid) { 15179 if (status != PackageManager.INSTALL_SUCCEEDED) { 15180 cleanUp(); 15181 } 15182 return status; 15183 } 15184 15185 @Override 15186 String getCodePath() { 15187 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15188 } 15189 15190 @Override 15191 String getResourcePath() { 15192 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15193 } 15194 15195 private boolean cleanUp() { 15196 if (codeFile == null || !codeFile.exists()) { 15197 return false; 15198 } 15199 15200 removeCodePathLI(codeFile); 15201 15202 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15203 resourceFile.delete(); 15204 } 15205 15206 return true; 15207 } 15208 15209 void cleanUpResourcesLI() { 15210 // Try enumerating all code paths before deleting 15211 List<String> allCodePaths = Collections.EMPTY_LIST; 15212 if (codeFile != null && codeFile.exists()) { 15213 try { 15214 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15215 allCodePaths = pkg.getAllCodePaths(); 15216 } catch (PackageParserException e) { 15217 // Ignored; we tried our best 15218 } 15219 } 15220 15221 cleanUp(); 15222 removeDexFiles(allCodePaths, instructionSets); 15223 } 15224 15225 boolean doPostDeleteLI(boolean delete) { 15226 // XXX err, shouldn't we respect the delete flag? 15227 cleanUpResourcesLI(); 15228 return true; 15229 } 15230 } 15231 15232 private boolean isAsecExternal(String cid) { 15233 final String asecPath = PackageHelper.getSdFilesystem(cid); 15234 return !asecPath.startsWith(mAsecInternalPath); 15235 } 15236 15237 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15238 PackageManagerException { 15239 if (copyRet < 0) { 15240 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15241 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15242 throw new PackageManagerException(copyRet, message); 15243 } 15244 } 15245 } 15246 15247 /** 15248 * Extract the StorageManagerService "container ID" from the full code path of an 15249 * .apk. 15250 */ 15251 static String cidFromCodePath(String fullCodePath) { 15252 int eidx = fullCodePath.lastIndexOf("/"); 15253 String subStr1 = fullCodePath.substring(0, eidx); 15254 int sidx = subStr1.lastIndexOf("/"); 15255 return subStr1.substring(sidx+1, eidx); 15256 } 15257 15258 /** 15259 * Logic to handle installation of ASEC applications, including copying and 15260 * renaming logic. 15261 */ 15262 class AsecInstallArgs extends InstallArgs { 15263 static final String RES_FILE_NAME = "pkg.apk"; 15264 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15265 15266 String cid; 15267 String packagePath; 15268 String resourcePath; 15269 15270 /** New install */ 15271 AsecInstallArgs(InstallParams params) { 15272 super(params.origin, params.move, params.observer, params.installFlags, 15273 params.installerPackageName, params.volumeUuid, 15274 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15275 params.grantedRuntimePermissions, 15276 params.traceMethod, params.traceCookie, params.certificates, 15277 params.installReason); 15278 } 15279 15280 /** Existing install */ 15281 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15282 boolean isExternal, boolean isForwardLocked) { 15283 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15284 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15285 instructionSets, null, null, null, 0, null /*certificates*/, 15286 PackageManager.INSTALL_REASON_UNKNOWN); 15287 // Hackily pretend we're still looking at a full code path 15288 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15289 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15290 } 15291 15292 // Extract cid from fullCodePath 15293 int eidx = fullCodePath.lastIndexOf("/"); 15294 String subStr1 = fullCodePath.substring(0, eidx); 15295 int sidx = subStr1.lastIndexOf("/"); 15296 cid = subStr1.substring(sidx+1, eidx); 15297 setMountPath(subStr1); 15298 } 15299 15300 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15301 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15302 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15303 instructionSets, null, null, null, 0, null /*certificates*/, 15304 PackageManager.INSTALL_REASON_UNKNOWN); 15305 this.cid = cid; 15306 setMountPath(PackageHelper.getSdDir(cid)); 15307 } 15308 15309 void createCopyFile() { 15310 cid = mInstallerService.allocateExternalStageCidLegacy(); 15311 } 15312 15313 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15314 if (origin.staged && origin.cid != null) { 15315 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15316 cid = origin.cid; 15317 setMountPath(PackageHelper.getSdDir(cid)); 15318 return PackageManager.INSTALL_SUCCEEDED; 15319 } 15320 15321 if (temp) { 15322 createCopyFile(); 15323 } else { 15324 /* 15325 * Pre-emptively destroy the container since it's destroyed if 15326 * copying fails due to it existing anyway. 15327 */ 15328 PackageHelper.destroySdDir(cid); 15329 } 15330 15331 final String newMountPath = imcs.copyPackageToContainer( 15332 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15333 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15334 15335 if (newMountPath != null) { 15336 setMountPath(newMountPath); 15337 return PackageManager.INSTALL_SUCCEEDED; 15338 } else { 15339 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15340 } 15341 } 15342 15343 @Override 15344 String getCodePath() { 15345 return packagePath; 15346 } 15347 15348 @Override 15349 String getResourcePath() { 15350 return resourcePath; 15351 } 15352 15353 int doPreInstall(int status) { 15354 if (status != PackageManager.INSTALL_SUCCEEDED) { 15355 // Destroy container 15356 PackageHelper.destroySdDir(cid); 15357 } else { 15358 boolean mounted = PackageHelper.isContainerMounted(cid); 15359 if (!mounted) { 15360 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15361 Process.SYSTEM_UID); 15362 if (newMountPath != null) { 15363 setMountPath(newMountPath); 15364 } else { 15365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15366 } 15367 } 15368 } 15369 return status; 15370 } 15371 15372 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15373 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15374 String newMountPath = null; 15375 if (PackageHelper.isContainerMounted(cid)) { 15376 // Unmount the container 15377 if (!PackageHelper.unMountSdDir(cid)) { 15378 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15379 return false; 15380 } 15381 } 15382 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15383 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15384 " which might be stale. Will try to clean up."); 15385 // Clean up the stale container and proceed to recreate. 15386 if (!PackageHelper.destroySdDir(newCacheId)) { 15387 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15388 return false; 15389 } 15390 // Successfully cleaned up stale container. Try to rename again. 15391 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15392 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15393 + " inspite of cleaning it up."); 15394 return false; 15395 } 15396 } 15397 if (!PackageHelper.isContainerMounted(newCacheId)) { 15398 Slog.w(TAG, "Mounting container " + newCacheId); 15399 newMountPath = PackageHelper.mountSdDir(newCacheId, 15400 getEncryptKey(), Process.SYSTEM_UID); 15401 } else { 15402 newMountPath = PackageHelper.getSdDir(newCacheId); 15403 } 15404 if (newMountPath == null) { 15405 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15406 return false; 15407 } 15408 Log.i(TAG, "Succesfully renamed " + cid + 15409 " to " + newCacheId + 15410 " at new path: " + newMountPath); 15411 cid = newCacheId; 15412 15413 final File beforeCodeFile = new File(packagePath); 15414 setMountPath(newMountPath); 15415 final File afterCodeFile = new File(packagePath); 15416 15417 // Reflect the rename in scanned details 15418 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15419 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15420 afterCodeFile, pkg.baseCodePath)); 15421 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15422 afterCodeFile, pkg.splitCodePaths)); 15423 15424 // Reflect the rename in app info 15425 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15426 pkg.setApplicationInfoCodePath(pkg.codePath); 15427 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15428 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15429 pkg.setApplicationInfoResourcePath(pkg.codePath); 15430 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15431 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15432 15433 return true; 15434 } 15435 15436 private void setMountPath(String mountPath) { 15437 final File mountFile = new File(mountPath); 15438 15439 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15440 if (monolithicFile.exists()) { 15441 packagePath = monolithicFile.getAbsolutePath(); 15442 if (isFwdLocked()) { 15443 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15444 } else { 15445 resourcePath = packagePath; 15446 } 15447 } else { 15448 packagePath = mountFile.getAbsolutePath(); 15449 resourcePath = packagePath; 15450 } 15451 } 15452 15453 int doPostInstall(int status, int uid) { 15454 if (status != PackageManager.INSTALL_SUCCEEDED) { 15455 cleanUp(); 15456 } else { 15457 final int groupOwner; 15458 final String protectedFile; 15459 if (isFwdLocked()) { 15460 groupOwner = UserHandle.getSharedAppGid(uid); 15461 protectedFile = RES_FILE_NAME; 15462 } else { 15463 groupOwner = -1; 15464 protectedFile = null; 15465 } 15466 15467 if (uid < Process.FIRST_APPLICATION_UID 15468 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15469 Slog.e(TAG, "Failed to finalize " + cid); 15470 PackageHelper.destroySdDir(cid); 15471 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15472 } 15473 15474 boolean mounted = PackageHelper.isContainerMounted(cid); 15475 if (!mounted) { 15476 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15477 } 15478 } 15479 return status; 15480 } 15481 15482 private void cleanUp() { 15483 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15484 15485 // Destroy secure container 15486 PackageHelper.destroySdDir(cid); 15487 } 15488 15489 private List<String> getAllCodePaths() { 15490 final File codeFile = new File(getCodePath()); 15491 if (codeFile != null && codeFile.exists()) { 15492 try { 15493 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15494 return pkg.getAllCodePaths(); 15495 } catch (PackageParserException e) { 15496 // Ignored; we tried our best 15497 } 15498 } 15499 return Collections.EMPTY_LIST; 15500 } 15501 15502 void cleanUpResourcesLI() { 15503 // Enumerate all code paths before deleting 15504 cleanUpResourcesLI(getAllCodePaths()); 15505 } 15506 15507 private void cleanUpResourcesLI(List<String> allCodePaths) { 15508 cleanUp(); 15509 removeDexFiles(allCodePaths, instructionSets); 15510 } 15511 15512 String getPackageName() { 15513 return getAsecPackageName(cid); 15514 } 15515 15516 boolean doPostDeleteLI(boolean delete) { 15517 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15518 final List<String> allCodePaths = getAllCodePaths(); 15519 boolean mounted = PackageHelper.isContainerMounted(cid); 15520 if (mounted) { 15521 // Unmount first 15522 if (PackageHelper.unMountSdDir(cid)) { 15523 mounted = false; 15524 } 15525 } 15526 if (!mounted && delete) { 15527 cleanUpResourcesLI(allCodePaths); 15528 } 15529 return !mounted; 15530 } 15531 15532 @Override 15533 int doPreCopy() { 15534 if (isFwdLocked()) { 15535 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15536 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15537 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15538 } 15539 } 15540 15541 return PackageManager.INSTALL_SUCCEEDED; 15542 } 15543 15544 @Override 15545 int doPostCopy(int uid) { 15546 if (isFwdLocked()) { 15547 if (uid < Process.FIRST_APPLICATION_UID 15548 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15549 RES_FILE_NAME)) { 15550 Slog.e(TAG, "Failed to finalize " + cid); 15551 PackageHelper.destroySdDir(cid); 15552 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15553 } 15554 } 15555 15556 return PackageManager.INSTALL_SUCCEEDED; 15557 } 15558 } 15559 15560 /** 15561 * Logic to handle movement of existing installed applications. 15562 */ 15563 class MoveInstallArgs extends InstallArgs { 15564 private File codeFile; 15565 private File resourceFile; 15566 15567 /** New install */ 15568 MoveInstallArgs(InstallParams params) { 15569 super(params.origin, params.move, params.observer, params.installFlags, 15570 params.installerPackageName, params.volumeUuid, 15571 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15572 params.grantedRuntimePermissions, 15573 params.traceMethod, params.traceCookie, params.certificates, 15574 params.installReason); 15575 } 15576 15577 int copyApk(IMediaContainerService imcs, boolean temp) { 15578 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15579 + move.fromUuid + " to " + move.toUuid); 15580 synchronized (mInstaller) { 15581 try { 15582 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15583 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15584 } catch (InstallerException e) { 15585 Slog.w(TAG, "Failed to move app", e); 15586 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15587 } 15588 } 15589 15590 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15591 resourceFile = codeFile; 15592 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15593 15594 return PackageManager.INSTALL_SUCCEEDED; 15595 } 15596 15597 int doPreInstall(int status) { 15598 if (status != PackageManager.INSTALL_SUCCEEDED) { 15599 cleanUp(move.toUuid); 15600 } 15601 return status; 15602 } 15603 15604 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15605 if (status != PackageManager.INSTALL_SUCCEEDED) { 15606 cleanUp(move.toUuid); 15607 return false; 15608 } 15609 15610 // Reflect the move in app info 15611 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15612 pkg.setApplicationInfoCodePath(pkg.codePath); 15613 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15614 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15615 pkg.setApplicationInfoResourcePath(pkg.codePath); 15616 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15617 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15618 15619 return true; 15620 } 15621 15622 int doPostInstall(int status, int uid) { 15623 if (status == PackageManager.INSTALL_SUCCEEDED) { 15624 cleanUp(move.fromUuid); 15625 } else { 15626 cleanUp(move.toUuid); 15627 } 15628 return status; 15629 } 15630 15631 @Override 15632 String getCodePath() { 15633 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15634 } 15635 15636 @Override 15637 String getResourcePath() { 15638 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15639 } 15640 15641 private boolean cleanUp(String volumeUuid) { 15642 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15643 move.dataAppName); 15644 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15645 final int[] userIds = sUserManager.getUserIds(); 15646 synchronized (mInstallLock) { 15647 // Clean up both app data and code 15648 // All package moves are frozen until finished 15649 for (int userId : userIds) { 15650 try { 15651 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15652 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15653 } catch (InstallerException e) { 15654 Slog.w(TAG, String.valueOf(e)); 15655 } 15656 } 15657 removeCodePathLI(codeFile); 15658 } 15659 return true; 15660 } 15661 15662 void cleanUpResourcesLI() { 15663 throw new UnsupportedOperationException(); 15664 } 15665 15666 boolean doPostDeleteLI(boolean delete) { 15667 throw new UnsupportedOperationException(); 15668 } 15669 } 15670 15671 static String getAsecPackageName(String packageCid) { 15672 int idx = packageCid.lastIndexOf("-"); 15673 if (idx == -1) { 15674 return packageCid; 15675 } 15676 return packageCid.substring(0, idx); 15677 } 15678 15679 // Utility method used to create code paths based on package name and available index. 15680 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15681 String idxStr = ""; 15682 int idx = 1; 15683 // Fall back to default value of idx=1 if prefix is not 15684 // part of oldCodePath 15685 if (oldCodePath != null) { 15686 String subStr = oldCodePath; 15687 // Drop the suffix right away 15688 if (suffix != null && subStr.endsWith(suffix)) { 15689 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15690 } 15691 // If oldCodePath already contains prefix find out the 15692 // ending index to either increment or decrement. 15693 int sidx = subStr.lastIndexOf(prefix); 15694 if (sidx != -1) { 15695 subStr = subStr.substring(sidx + prefix.length()); 15696 if (subStr != null) { 15697 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15698 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15699 } 15700 try { 15701 idx = Integer.parseInt(subStr); 15702 if (idx <= 1) { 15703 idx++; 15704 } else { 15705 idx--; 15706 } 15707 } catch(NumberFormatException e) { 15708 } 15709 } 15710 } 15711 } 15712 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15713 return prefix + idxStr; 15714 } 15715 15716 private File getNextCodePath(File targetDir, String packageName) { 15717 File result; 15718 SecureRandom random = new SecureRandom(); 15719 byte[] bytes = new byte[16]; 15720 do { 15721 random.nextBytes(bytes); 15722 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15723 result = new File(targetDir, packageName + "-" + suffix); 15724 } while (result.exists()); 15725 return result; 15726 } 15727 15728 // Utility method that returns the relative package path with respect 15729 // to the installation directory. Like say for /data/data/com.test-1.apk 15730 // string com.test-1 is returned. 15731 static String deriveCodePathName(String codePath) { 15732 if (codePath == null) { 15733 return null; 15734 } 15735 final File codeFile = new File(codePath); 15736 final String name = codeFile.getName(); 15737 if (codeFile.isDirectory()) { 15738 return name; 15739 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15740 final int lastDot = name.lastIndexOf('.'); 15741 return name.substring(0, lastDot); 15742 } else { 15743 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15744 return null; 15745 } 15746 } 15747 15748 static class PackageInstalledInfo { 15749 String name; 15750 int uid; 15751 // The set of users that originally had this package installed. 15752 int[] origUsers; 15753 // The set of users that now have this package installed. 15754 int[] newUsers; 15755 PackageParser.Package pkg; 15756 int returnCode; 15757 String returnMsg; 15758 PackageRemovedInfo removedInfo; 15759 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15760 15761 public void setError(int code, String msg) { 15762 setReturnCode(code); 15763 setReturnMessage(msg); 15764 Slog.w(TAG, msg); 15765 } 15766 15767 public void setError(String msg, PackageParserException e) { 15768 setReturnCode(e.error); 15769 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15770 Slog.w(TAG, msg, e); 15771 } 15772 15773 public void setError(String msg, PackageManagerException e) { 15774 returnCode = e.error; 15775 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15776 Slog.w(TAG, msg, e); 15777 } 15778 15779 public void setReturnCode(int returnCode) { 15780 this.returnCode = returnCode; 15781 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15782 for (int i = 0; i < childCount; i++) { 15783 addedChildPackages.valueAt(i).returnCode = returnCode; 15784 } 15785 } 15786 15787 private void setReturnMessage(String returnMsg) { 15788 this.returnMsg = returnMsg; 15789 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15790 for (int i = 0; i < childCount; i++) { 15791 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15792 } 15793 } 15794 15795 // In some error cases we want to convey more info back to the observer 15796 String origPackage; 15797 String origPermission; 15798 } 15799 15800 /* 15801 * Install a non-existing package. 15802 */ 15803 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15804 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15805 PackageInstalledInfo res, int installReason) { 15806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15807 15808 // Remember this for later, in case we need to rollback this install 15809 String pkgName = pkg.packageName; 15810 15811 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15812 15813 synchronized(mPackages) { 15814 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15815 if (renamedPackage != null) { 15816 // A package with the same name is already installed, though 15817 // it has been renamed to an older name. The package we 15818 // are trying to install should be installed as an update to 15819 // the existing one, but that has not been requested, so bail. 15820 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15821 + " without first uninstalling package running as " 15822 + renamedPackage); 15823 return; 15824 } 15825 if (mPackages.containsKey(pkgName)) { 15826 // Don't allow installation over an existing package with the same name. 15827 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15828 + " without first uninstalling."); 15829 return; 15830 } 15831 } 15832 15833 try { 15834 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15835 System.currentTimeMillis(), user); 15836 15837 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15838 15839 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15840 prepareAppDataAfterInstallLIF(newPackage); 15841 15842 } else { 15843 // Remove package from internal structures, but keep around any 15844 // data that might have already existed 15845 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15846 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15847 } 15848 } catch (PackageManagerException e) { 15849 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15850 } 15851 15852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15853 } 15854 15855 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15856 // Can't rotate keys during boot or if sharedUser. 15857 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15858 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15859 return false; 15860 } 15861 // app is using upgradeKeySets; make sure all are valid 15862 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15863 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15864 for (int i = 0; i < upgradeKeySets.length; i++) { 15865 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15866 Slog.wtf(TAG, "Package " 15867 + (oldPs.name != null ? oldPs.name : "<null>") 15868 + " contains upgrade-key-set reference to unknown key-set: " 15869 + upgradeKeySets[i] 15870 + " reverting to signatures check."); 15871 return false; 15872 } 15873 } 15874 return true; 15875 } 15876 15877 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15878 // Upgrade keysets are being used. Determine if new package has a superset of the 15879 // required keys. 15880 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15881 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15882 for (int i = 0; i < upgradeKeySets.length; i++) { 15883 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15884 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15885 return true; 15886 } 15887 } 15888 return false; 15889 } 15890 15891 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15892 try (DigestInputStream digestStream = 15893 new DigestInputStream(new FileInputStream(file), digest)) { 15894 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15895 } 15896 } 15897 15898 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15899 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15900 int installReason) { 15901 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15902 15903 final PackageParser.Package oldPackage; 15904 final String pkgName = pkg.packageName; 15905 final int[] allUsers; 15906 final int[] installedUsers; 15907 15908 synchronized(mPackages) { 15909 oldPackage = mPackages.get(pkgName); 15910 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15911 15912 // don't allow upgrade to target a release SDK from a pre-release SDK 15913 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15914 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15915 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15916 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15917 if (oldTargetsPreRelease 15918 && !newTargetsPreRelease 15919 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15920 Slog.w(TAG, "Can't install package targeting released sdk"); 15921 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15922 return; 15923 } 15924 15925 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15926 15927 // don't allow an upgrade from full to ephemeral 15928 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15929 // can't downgrade from full to instant 15930 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15931 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15932 return; 15933 } 15934 15935 // verify signatures are valid 15936 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15937 if (!checkUpgradeKeySetLP(ps, pkg)) { 15938 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15939 "New package not signed by keys specified by upgrade-keysets: " 15940 + pkgName); 15941 return; 15942 } 15943 } else { 15944 // default to original signature matching 15945 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15946 != PackageManager.SIGNATURE_MATCH) { 15947 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15948 "New package has a different signature: " + pkgName); 15949 return; 15950 } 15951 } 15952 15953 // don't allow a system upgrade unless the upgrade hash matches 15954 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15955 byte[] digestBytes = null; 15956 try { 15957 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15958 updateDigest(digest, new File(pkg.baseCodePath)); 15959 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15960 for (String path : pkg.splitCodePaths) { 15961 updateDigest(digest, new File(path)); 15962 } 15963 } 15964 digestBytes = digest.digest(); 15965 } catch (NoSuchAlgorithmException | IOException e) { 15966 res.setError(INSTALL_FAILED_INVALID_APK, 15967 "Could not compute hash: " + pkgName); 15968 return; 15969 } 15970 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15971 res.setError(INSTALL_FAILED_INVALID_APK, 15972 "New package fails restrict-update check: " + pkgName); 15973 return; 15974 } 15975 // retain upgrade restriction 15976 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15977 } 15978 15979 // Check for shared user id changes 15980 String invalidPackageName = 15981 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15982 if (invalidPackageName != null) { 15983 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15984 "Package " + invalidPackageName + " tried to change user " 15985 + oldPackage.mSharedUserId); 15986 return; 15987 } 15988 15989 // In case of rollback, remember per-user/profile install state 15990 allUsers = sUserManager.getUserIds(); 15991 installedUsers = ps.queryInstalledUsers(allUsers, true); 15992 } 15993 15994 // Update what is removed 15995 res.removedInfo = new PackageRemovedInfo(); 15996 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15997 res.removedInfo.removedPackage = oldPackage.packageName; 15998 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15999 res.removedInfo.isUpdate = true; 16000 res.removedInfo.origUsers = installedUsers; 16001 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16002 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16003 for (int i = 0; i < installedUsers.length; i++) { 16004 final int userId = installedUsers[i]; 16005 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16006 } 16007 16008 final int childCount = (oldPackage.childPackages != null) 16009 ? oldPackage.childPackages.size() : 0; 16010 for (int i = 0; i < childCount; i++) { 16011 boolean childPackageUpdated = false; 16012 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16013 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16014 if (res.addedChildPackages != null) { 16015 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16016 if (childRes != null) { 16017 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16018 childRes.removedInfo.removedPackage = childPkg.packageName; 16019 childRes.removedInfo.isUpdate = true; 16020 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16021 childPackageUpdated = true; 16022 } 16023 } 16024 if (!childPackageUpdated) { 16025 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16026 childRemovedRes.removedPackage = childPkg.packageName; 16027 childRemovedRes.isUpdate = false; 16028 childRemovedRes.dataRemoved = true; 16029 synchronized (mPackages) { 16030 if (childPs != null) { 16031 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16032 } 16033 } 16034 if (res.removedInfo.removedChildPackages == null) { 16035 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16036 } 16037 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16038 } 16039 } 16040 16041 boolean sysPkg = (isSystemApp(oldPackage)); 16042 if (sysPkg) { 16043 // Set the system/privileged flags as needed 16044 final boolean privileged = 16045 (oldPackage.applicationInfo.privateFlags 16046 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16047 final int systemPolicyFlags = policyFlags 16048 | PackageParser.PARSE_IS_SYSTEM 16049 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16050 16051 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16052 user, allUsers, installerPackageName, res, installReason); 16053 } else { 16054 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16055 user, allUsers, installerPackageName, res, installReason); 16056 } 16057 } 16058 16059 public List<String> getPreviousCodePaths(String packageName) { 16060 final PackageSetting ps = mSettings.mPackages.get(packageName); 16061 final List<String> result = new ArrayList<String>(); 16062 if (ps != null && ps.oldCodePaths != null) { 16063 result.addAll(ps.oldCodePaths); 16064 } 16065 return result; 16066 } 16067 16068 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16069 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16070 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16071 int installReason) { 16072 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16073 + deletedPackage); 16074 16075 String pkgName = deletedPackage.packageName; 16076 boolean deletedPkg = true; 16077 boolean addedPkg = false; 16078 boolean updatedSettings = false; 16079 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16080 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16081 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16082 16083 final long origUpdateTime = (pkg.mExtras != null) 16084 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16085 16086 // First delete the existing package while retaining the data directory 16087 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16088 res.removedInfo, true, pkg)) { 16089 // If the existing package wasn't successfully deleted 16090 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16091 deletedPkg = false; 16092 } else { 16093 // Successfully deleted the old package; proceed with replace. 16094 16095 // If deleted package lived in a container, give users a chance to 16096 // relinquish resources before killing. 16097 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16098 if (DEBUG_INSTALL) { 16099 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16100 } 16101 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16102 final ArrayList<String> pkgList = new ArrayList<String>(1); 16103 pkgList.add(deletedPackage.applicationInfo.packageName); 16104 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16105 } 16106 16107 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16108 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16109 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16110 16111 try { 16112 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16113 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16114 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16115 installReason); 16116 16117 // Update the in-memory copy of the previous code paths. 16118 PackageSetting ps = mSettings.mPackages.get(pkgName); 16119 if (!killApp) { 16120 if (ps.oldCodePaths == null) { 16121 ps.oldCodePaths = new ArraySet<>(); 16122 } 16123 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16124 if (deletedPackage.splitCodePaths != null) { 16125 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16126 } 16127 } else { 16128 ps.oldCodePaths = null; 16129 } 16130 if (ps.childPackageNames != null) { 16131 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16132 final String childPkgName = ps.childPackageNames.get(i); 16133 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16134 childPs.oldCodePaths = ps.oldCodePaths; 16135 } 16136 } 16137 // set instant app status, but, only if it's explicitly specified 16138 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16139 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16140 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16141 prepareAppDataAfterInstallLIF(newPackage); 16142 addedPkg = true; 16143 } catch (PackageManagerException e) { 16144 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16145 } 16146 } 16147 16148 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16149 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16150 16151 // Revert all internal state mutations and added folders for the failed install 16152 if (addedPkg) { 16153 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16154 res.removedInfo, true, null); 16155 } 16156 16157 // Restore the old package 16158 if (deletedPkg) { 16159 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16160 File restoreFile = new File(deletedPackage.codePath); 16161 // Parse old package 16162 boolean oldExternal = isExternal(deletedPackage); 16163 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16164 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16165 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16166 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16167 try { 16168 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16169 null); 16170 } catch (PackageManagerException e) { 16171 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16172 + e.getMessage()); 16173 return; 16174 } 16175 16176 synchronized (mPackages) { 16177 // Ensure the installer package name up to date 16178 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16179 16180 // Update permissions for restored package 16181 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16182 16183 mSettings.writeLPr(); 16184 } 16185 16186 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16187 } 16188 } else { 16189 synchronized (mPackages) { 16190 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16191 if (ps != null) { 16192 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16193 if (res.removedInfo.removedChildPackages != null) { 16194 final int childCount = res.removedInfo.removedChildPackages.size(); 16195 // Iterate in reverse as we may modify the collection 16196 for (int i = childCount - 1; i >= 0; i--) { 16197 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16198 if (res.addedChildPackages.containsKey(childPackageName)) { 16199 res.removedInfo.removedChildPackages.removeAt(i); 16200 } else { 16201 PackageRemovedInfo childInfo = res.removedInfo 16202 .removedChildPackages.valueAt(i); 16203 childInfo.removedForAllUsers = mPackages.get( 16204 childInfo.removedPackage) == null; 16205 } 16206 } 16207 } 16208 } 16209 } 16210 } 16211 } 16212 16213 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16214 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16215 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16216 int installReason) { 16217 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16218 + ", old=" + deletedPackage); 16219 16220 final boolean disabledSystem; 16221 16222 // Remove existing system package 16223 removePackageLI(deletedPackage, true); 16224 16225 synchronized (mPackages) { 16226 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16227 } 16228 if (!disabledSystem) { 16229 // We didn't need to disable the .apk as a current system package, 16230 // which means we are replacing another update that is already 16231 // installed. We need to make sure to delete the older one's .apk. 16232 res.removedInfo.args = createInstallArgsForExisting(0, 16233 deletedPackage.applicationInfo.getCodePath(), 16234 deletedPackage.applicationInfo.getResourcePath(), 16235 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16236 } else { 16237 res.removedInfo.args = null; 16238 } 16239 16240 // Successfully disabled the old package. Now proceed with re-installation 16241 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16242 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16243 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16244 16245 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16246 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16247 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16248 16249 PackageParser.Package newPackage = null; 16250 try { 16251 // Add the package to the internal data structures 16252 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16253 16254 // Set the update and install times 16255 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16256 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16257 System.currentTimeMillis()); 16258 16259 // Update the package dynamic state if succeeded 16260 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16261 // Now that the install succeeded make sure we remove data 16262 // directories for any child package the update removed. 16263 final int deletedChildCount = (deletedPackage.childPackages != null) 16264 ? deletedPackage.childPackages.size() : 0; 16265 final int newChildCount = (newPackage.childPackages != null) 16266 ? newPackage.childPackages.size() : 0; 16267 for (int i = 0; i < deletedChildCount; i++) { 16268 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16269 boolean childPackageDeleted = true; 16270 for (int j = 0; j < newChildCount; j++) { 16271 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16272 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16273 childPackageDeleted = false; 16274 break; 16275 } 16276 } 16277 if (childPackageDeleted) { 16278 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16279 deletedChildPkg.packageName); 16280 if (ps != null && res.removedInfo.removedChildPackages != null) { 16281 PackageRemovedInfo removedChildRes = res.removedInfo 16282 .removedChildPackages.get(deletedChildPkg.packageName); 16283 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16284 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16285 } 16286 } 16287 } 16288 16289 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16290 installReason); 16291 prepareAppDataAfterInstallLIF(newPackage); 16292 } 16293 } catch (PackageManagerException e) { 16294 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16295 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16296 } 16297 16298 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16299 // Re installation failed. Restore old information 16300 // Remove new pkg information 16301 if (newPackage != null) { 16302 removeInstalledPackageLI(newPackage, true); 16303 } 16304 // Add back the old system package 16305 try { 16306 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16307 } catch (PackageManagerException e) { 16308 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16309 } 16310 16311 synchronized (mPackages) { 16312 if (disabledSystem) { 16313 enableSystemPackageLPw(deletedPackage); 16314 } 16315 16316 // Ensure the installer package name up to date 16317 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16318 16319 // Update permissions for restored package 16320 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16321 16322 mSettings.writeLPr(); 16323 } 16324 16325 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16326 + " after failed upgrade"); 16327 } 16328 } 16329 16330 /** 16331 * Checks whether the parent or any of the child packages have a change shared 16332 * user. For a package to be a valid update the shred users of the parent and 16333 * the children should match. We may later support changing child shared users. 16334 * @param oldPkg The updated package. 16335 * @param newPkg The update package. 16336 * @return The shared user that change between the versions. 16337 */ 16338 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16339 PackageParser.Package newPkg) { 16340 // Check parent shared user 16341 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16342 return newPkg.packageName; 16343 } 16344 // Check child shared users 16345 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16346 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16347 for (int i = 0; i < newChildCount; i++) { 16348 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16349 // If this child was present, did it have the same shared user? 16350 for (int j = 0; j < oldChildCount; j++) { 16351 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16352 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16353 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16354 return newChildPkg.packageName; 16355 } 16356 } 16357 } 16358 return null; 16359 } 16360 16361 private void removeNativeBinariesLI(PackageSetting ps) { 16362 // Remove the lib path for the parent package 16363 if (ps != null) { 16364 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16365 // Remove the lib path for the child packages 16366 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16367 for (int i = 0; i < childCount; i++) { 16368 PackageSetting childPs = null; 16369 synchronized (mPackages) { 16370 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16371 } 16372 if (childPs != null) { 16373 NativeLibraryHelper.removeNativeBinariesLI(childPs 16374 .legacyNativeLibraryPathString); 16375 } 16376 } 16377 } 16378 } 16379 16380 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16381 // Enable the parent package 16382 mSettings.enableSystemPackageLPw(pkg.packageName); 16383 // Enable the child packages 16384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16385 for (int i = 0; i < childCount; i++) { 16386 PackageParser.Package childPkg = pkg.childPackages.get(i); 16387 mSettings.enableSystemPackageLPw(childPkg.packageName); 16388 } 16389 } 16390 16391 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16392 PackageParser.Package newPkg) { 16393 // Disable the parent package (parent always replaced) 16394 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16395 // Disable the child packages 16396 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16397 for (int i = 0; i < childCount; i++) { 16398 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16399 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16400 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16401 } 16402 return disabled; 16403 } 16404 16405 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16406 String installerPackageName) { 16407 // Enable the parent package 16408 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16409 // Enable the child packages 16410 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16411 for (int i = 0; i < childCount; i++) { 16412 PackageParser.Package childPkg = pkg.childPackages.get(i); 16413 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16414 } 16415 } 16416 16417 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16418 // Collect all used permissions in the UID 16419 ArraySet<String> usedPermissions = new ArraySet<>(); 16420 final int packageCount = su.packages.size(); 16421 for (int i = 0; i < packageCount; i++) { 16422 PackageSetting ps = su.packages.valueAt(i); 16423 if (ps.pkg == null) { 16424 continue; 16425 } 16426 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16427 for (int j = 0; j < requestedPermCount; j++) { 16428 String permission = ps.pkg.requestedPermissions.get(j); 16429 BasePermission bp = mSettings.mPermissions.get(permission); 16430 if (bp != null) { 16431 usedPermissions.add(permission); 16432 } 16433 } 16434 } 16435 16436 PermissionsState permissionsState = su.getPermissionsState(); 16437 // Prune install permissions 16438 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16439 final int installPermCount = installPermStates.size(); 16440 for (int i = installPermCount - 1; i >= 0; i--) { 16441 PermissionState permissionState = installPermStates.get(i); 16442 if (!usedPermissions.contains(permissionState.getName())) { 16443 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16444 if (bp != null) { 16445 permissionsState.revokeInstallPermission(bp); 16446 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16447 PackageManager.MASK_PERMISSION_FLAGS, 0); 16448 } 16449 } 16450 } 16451 16452 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16453 16454 // Prune runtime permissions 16455 for (int userId : allUserIds) { 16456 List<PermissionState> runtimePermStates = permissionsState 16457 .getRuntimePermissionStates(userId); 16458 final int runtimePermCount = runtimePermStates.size(); 16459 for (int i = runtimePermCount - 1; i >= 0; i--) { 16460 PermissionState permissionState = runtimePermStates.get(i); 16461 if (!usedPermissions.contains(permissionState.getName())) { 16462 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16463 if (bp != null) { 16464 permissionsState.revokeRuntimePermission(bp, userId); 16465 permissionsState.updatePermissionFlags(bp, userId, 16466 PackageManager.MASK_PERMISSION_FLAGS, 0); 16467 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16468 runtimePermissionChangedUserIds, userId); 16469 } 16470 } 16471 } 16472 } 16473 16474 return runtimePermissionChangedUserIds; 16475 } 16476 16477 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16478 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16479 // Update the parent package setting 16480 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16481 res, user, installReason); 16482 // Update the child packages setting 16483 final int childCount = (newPackage.childPackages != null) 16484 ? newPackage.childPackages.size() : 0; 16485 for (int i = 0; i < childCount; i++) { 16486 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16487 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16488 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16489 childRes.origUsers, childRes, user, installReason); 16490 } 16491 } 16492 16493 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16494 String installerPackageName, int[] allUsers, int[] installedForUsers, 16495 PackageInstalledInfo res, UserHandle user, int installReason) { 16496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16497 16498 String pkgName = newPackage.packageName; 16499 synchronized (mPackages) { 16500 //write settings. the installStatus will be incomplete at this stage. 16501 //note that the new package setting would have already been 16502 //added to mPackages. It hasn't been persisted yet. 16503 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16504 // TODO: Remove this write? It's also written at the end of this method 16505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16506 mSettings.writeLPr(); 16507 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16508 } 16509 16510 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16511 synchronized (mPackages) { 16512 updatePermissionsLPw(newPackage.packageName, newPackage, 16513 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16514 ? UPDATE_PERMISSIONS_ALL : 0)); 16515 // For system-bundled packages, we assume that installing an upgraded version 16516 // of the package implies that the user actually wants to run that new code, 16517 // so we enable the package. 16518 PackageSetting ps = mSettings.mPackages.get(pkgName); 16519 final int userId = user.getIdentifier(); 16520 if (ps != null) { 16521 if (isSystemApp(newPackage)) { 16522 if (DEBUG_INSTALL) { 16523 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16524 } 16525 // Enable system package for requested users 16526 if (res.origUsers != null) { 16527 for (int origUserId : res.origUsers) { 16528 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16529 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16530 origUserId, installerPackageName); 16531 } 16532 } 16533 } 16534 // Also convey the prior install/uninstall state 16535 if (allUsers != null && installedForUsers != null) { 16536 for (int currentUserId : allUsers) { 16537 final boolean installed = ArrayUtils.contains( 16538 installedForUsers, currentUserId); 16539 if (DEBUG_INSTALL) { 16540 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16541 } 16542 ps.setInstalled(installed, currentUserId); 16543 } 16544 // these install state changes will be persisted in the 16545 // upcoming call to mSettings.writeLPr(). 16546 } 16547 } 16548 // It's implied that when a user requests installation, they want the app to be 16549 // installed and enabled. 16550 if (userId != UserHandle.USER_ALL) { 16551 ps.setInstalled(true, userId); 16552 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16553 } 16554 16555 // When replacing an existing package, preserve the original install reason for all 16556 // users that had the package installed before. 16557 final Set<Integer> previousUserIds = new ArraySet<>(); 16558 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16559 final int installReasonCount = res.removedInfo.installReasons.size(); 16560 for (int i = 0; i < installReasonCount; i++) { 16561 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16562 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16563 ps.setInstallReason(previousInstallReason, previousUserId); 16564 previousUserIds.add(previousUserId); 16565 } 16566 } 16567 16568 // Set install reason for users that are having the package newly installed. 16569 if (userId == UserHandle.USER_ALL) { 16570 for (int currentUserId : sUserManager.getUserIds()) { 16571 if (!previousUserIds.contains(currentUserId)) { 16572 ps.setInstallReason(installReason, currentUserId); 16573 } 16574 } 16575 } else if (!previousUserIds.contains(userId)) { 16576 ps.setInstallReason(installReason, userId); 16577 } 16578 mSettings.writeKernelMappingLPr(ps); 16579 } 16580 res.name = pkgName; 16581 res.uid = newPackage.applicationInfo.uid; 16582 res.pkg = newPackage; 16583 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16584 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16585 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16586 //to update install status 16587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16588 mSettings.writeLPr(); 16589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16590 } 16591 16592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16593 } 16594 16595 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16596 try { 16597 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16598 installPackageLI(args, res); 16599 } finally { 16600 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16601 } 16602 } 16603 16604 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16605 final int installFlags = args.installFlags; 16606 final String installerPackageName = args.installerPackageName; 16607 final String volumeUuid = args.volumeUuid; 16608 final File tmpPackageFile = new File(args.getCodePath()); 16609 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16610 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16611 || (args.volumeUuid != null)); 16612 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16613 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16614 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16615 boolean replace = false; 16616 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16617 if (args.move != null) { 16618 // moving a complete application; perform an initial scan on the new install location 16619 scanFlags |= SCAN_INITIAL; 16620 } 16621 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16622 scanFlags |= SCAN_DONT_KILL_APP; 16623 } 16624 if (instantApp) { 16625 scanFlags |= SCAN_AS_INSTANT_APP; 16626 } 16627 if (fullApp) { 16628 scanFlags |= SCAN_AS_FULL_APP; 16629 } 16630 16631 // Result object to be returned 16632 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16633 16634 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16635 16636 // Sanity check 16637 if (instantApp && (forwardLocked || onExternal)) { 16638 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16639 + " external=" + onExternal); 16640 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16641 return; 16642 } 16643 16644 // Retrieve PackageSettings and parse package 16645 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16646 | PackageParser.PARSE_ENFORCE_CODE 16647 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16648 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16649 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16650 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16651 PackageParser pp = new PackageParser(); 16652 pp.setSeparateProcesses(mSeparateProcesses); 16653 pp.setDisplayMetrics(mMetrics); 16654 16655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16656 final PackageParser.Package pkg; 16657 try { 16658 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16659 } catch (PackageParserException e) { 16660 res.setError("Failed parse during installPackageLI", e); 16661 return; 16662 } finally { 16663 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16664 } 16665 16666// // Ephemeral apps must have target SDK >= O. 16667// // TODO: Update conditional and error message when O gets locked down 16668// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16669// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16670// "Ephemeral apps must have target SDK version of at least O"); 16671// return; 16672// } 16673 16674 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16675 // Static shared libraries have synthetic package names 16676 renameStaticSharedLibraryPackage(pkg); 16677 16678 // No static shared libs on external storage 16679 if (onExternal) { 16680 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16681 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16682 "Packages declaring static-shared libs cannot be updated"); 16683 return; 16684 } 16685 } 16686 16687 // If we are installing a clustered package add results for the children 16688 if (pkg.childPackages != null) { 16689 synchronized (mPackages) { 16690 final int childCount = pkg.childPackages.size(); 16691 for (int i = 0; i < childCount; i++) { 16692 PackageParser.Package childPkg = pkg.childPackages.get(i); 16693 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16694 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16695 childRes.pkg = childPkg; 16696 childRes.name = childPkg.packageName; 16697 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16698 if (childPs != null) { 16699 childRes.origUsers = childPs.queryInstalledUsers( 16700 sUserManager.getUserIds(), true); 16701 } 16702 if ((mPackages.containsKey(childPkg.packageName))) { 16703 childRes.removedInfo = new PackageRemovedInfo(); 16704 childRes.removedInfo.removedPackage = childPkg.packageName; 16705 } 16706 if (res.addedChildPackages == null) { 16707 res.addedChildPackages = new ArrayMap<>(); 16708 } 16709 res.addedChildPackages.put(childPkg.packageName, childRes); 16710 } 16711 } 16712 } 16713 16714 // If package doesn't declare API override, mark that we have an install 16715 // time CPU ABI override. 16716 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16717 pkg.cpuAbiOverride = args.abiOverride; 16718 } 16719 16720 String pkgName = res.name = pkg.packageName; 16721 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16722 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16723 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16724 return; 16725 } 16726 } 16727 16728 try { 16729 // either use what we've been given or parse directly from the APK 16730 if (args.certificates != null) { 16731 try { 16732 PackageParser.populateCertificates(pkg, args.certificates); 16733 } catch (PackageParserException e) { 16734 // there was something wrong with the certificates we were given; 16735 // try to pull them from the APK 16736 PackageParser.collectCertificates(pkg, parseFlags); 16737 } 16738 } else { 16739 PackageParser.collectCertificates(pkg, parseFlags); 16740 } 16741 } catch (PackageParserException e) { 16742 res.setError("Failed collect during installPackageLI", e); 16743 return; 16744 } 16745 16746 // Get rid of all references to package scan path via parser. 16747 pp = null; 16748 String oldCodePath = null; 16749 boolean systemApp = false; 16750 synchronized (mPackages) { 16751 // Check if installing already existing package 16752 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16753 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16754 if (pkg.mOriginalPackages != null 16755 && pkg.mOriginalPackages.contains(oldName) 16756 && mPackages.containsKey(oldName)) { 16757 // This package is derived from an original package, 16758 // and this device has been updating from that original 16759 // name. We must continue using the original name, so 16760 // rename the new package here. 16761 pkg.setPackageName(oldName); 16762 pkgName = pkg.packageName; 16763 replace = true; 16764 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16765 + oldName + " pkgName=" + pkgName); 16766 } else if (mPackages.containsKey(pkgName)) { 16767 // This package, under its official name, already exists 16768 // on the device; we should replace it. 16769 replace = true; 16770 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16771 } 16772 16773 // Child packages are installed through the parent package 16774 if (pkg.parentPackage != null) { 16775 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16776 "Package " + pkg.packageName + " is child of package " 16777 + pkg.parentPackage.parentPackage + ". Child packages " 16778 + "can be updated only through the parent package."); 16779 return; 16780 } 16781 16782 if (replace) { 16783 // Prevent apps opting out from runtime permissions 16784 PackageParser.Package oldPackage = mPackages.get(pkgName); 16785 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16786 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16787 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16788 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16789 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16790 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16791 + " doesn't support runtime permissions but the old" 16792 + " target SDK " + oldTargetSdk + " does."); 16793 return; 16794 } 16795 16796 // Prevent installing of child packages 16797 if (oldPackage.parentPackage != null) { 16798 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16799 "Package " + pkg.packageName + " is child of package " 16800 + oldPackage.parentPackage + ". Child packages " 16801 + "can be updated only through the parent package."); 16802 return; 16803 } 16804 } 16805 } 16806 16807 PackageSetting ps = mSettings.mPackages.get(pkgName); 16808 if (ps != null) { 16809 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16810 16811 // Static shared libs have same package with different versions where 16812 // we internally use a synthetic package name to allow multiple versions 16813 // of the same package, therefore we need to compare signatures against 16814 // the package setting for the latest library version. 16815 PackageSetting signatureCheckPs = ps; 16816 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16817 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16818 if (libraryEntry != null) { 16819 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16820 } 16821 } 16822 16823 // Quick sanity check that we're signed correctly if updating; 16824 // we'll check this again later when scanning, but we want to 16825 // bail early here before tripping over redefined permissions. 16826 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16827 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16828 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16829 + pkg.packageName + " upgrade keys do not match the " 16830 + "previously installed version"); 16831 return; 16832 } 16833 } else { 16834 try { 16835 verifySignaturesLP(signatureCheckPs, pkg); 16836 } catch (PackageManagerException e) { 16837 res.setError(e.error, e.getMessage()); 16838 return; 16839 } 16840 } 16841 16842 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16843 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16844 systemApp = (ps.pkg.applicationInfo.flags & 16845 ApplicationInfo.FLAG_SYSTEM) != 0; 16846 } 16847 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16848 } 16849 16850 // Check whether the newly-scanned package wants to define an already-defined perm 16851 int N = pkg.permissions.size(); 16852 for (int i = N-1; i >= 0; i--) { 16853 PackageParser.Permission perm = pkg.permissions.get(i); 16854 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16855 if (bp != null) { 16856 // If the defining package is signed with our cert, it's okay. This 16857 // also includes the "updating the same package" case, of course. 16858 // "updating same package" could also involve key-rotation. 16859 final boolean sigsOk; 16860 if (bp.sourcePackage.equals(pkg.packageName) 16861 && (bp.packageSetting instanceof PackageSetting) 16862 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16863 scanFlags))) { 16864 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16865 } else { 16866 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16867 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16868 } 16869 if (!sigsOk) { 16870 // If the owning package is the system itself, we log but allow 16871 // install to proceed; we fail the install on all other permission 16872 // redefinitions. 16873 if (!bp.sourcePackage.equals("android")) { 16874 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16875 + pkg.packageName + " attempting to redeclare permission " 16876 + perm.info.name + " already owned by " + bp.sourcePackage); 16877 res.origPermission = perm.info.name; 16878 res.origPackage = bp.sourcePackage; 16879 return; 16880 } else { 16881 Slog.w(TAG, "Package " + pkg.packageName 16882 + " attempting to redeclare system permission " 16883 + perm.info.name + "; ignoring new declaration"); 16884 pkg.permissions.remove(i); 16885 } 16886 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16887 // Prevent apps to change protection level to dangerous from any other 16888 // type as this would allow a privilege escalation where an app adds a 16889 // normal/signature permission in other app's group and later redefines 16890 // it as dangerous leading to the group auto-grant. 16891 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16892 == PermissionInfo.PROTECTION_DANGEROUS) { 16893 if (bp != null && !bp.isRuntime()) { 16894 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16895 + "non-runtime permission " + perm.info.name 16896 + " to runtime; keeping old protection level"); 16897 perm.info.protectionLevel = bp.protectionLevel; 16898 } 16899 } 16900 } 16901 } 16902 } 16903 } 16904 16905 if (systemApp) { 16906 if (onExternal) { 16907 // Abort update; system app can't be replaced with app on sdcard 16908 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16909 "Cannot install updates to system apps on sdcard"); 16910 return; 16911 } else if (instantApp) { 16912 // Abort update; system app can't be replaced with an instant app 16913 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16914 "Cannot update a system app with an instant app"); 16915 return; 16916 } 16917 } 16918 16919 if (args.move != null) { 16920 // We did an in-place move, so dex is ready to roll 16921 scanFlags |= SCAN_NO_DEX; 16922 scanFlags |= SCAN_MOVE; 16923 16924 synchronized (mPackages) { 16925 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16926 if (ps == null) { 16927 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16928 "Missing settings for moved package " + pkgName); 16929 } 16930 16931 // We moved the entire application as-is, so bring over the 16932 // previously derived ABI information. 16933 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16934 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16935 } 16936 16937 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16938 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16939 scanFlags |= SCAN_NO_DEX; 16940 16941 try { 16942 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16943 args.abiOverride : pkg.cpuAbiOverride); 16944 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16945 true /*extractLibs*/, mAppLib32InstallDir); 16946 } catch (PackageManagerException pme) { 16947 Slog.e(TAG, "Error deriving application ABI", pme); 16948 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16949 return; 16950 } 16951 16952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16953 // Do not run PackageDexOptimizer through the local performDexOpt 16954 // method because `pkg` may not be in `mPackages` yet. 16955 // 16956 // Also, don't fail application installs if the dexopt step fails. 16957 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16958 null /* instructionSets */, false /* checkProfiles */, 16959 getCompilerFilterForReason(REASON_INSTALL), 16960 getOrCreateCompilerPackageStats(pkg)); 16961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16962 16963 // Notify BackgroundDexOptJobService that the package has been changed. 16964 // If this is an update of a package which used to fail to compile, 16965 // BDOS will remove it from its blacklist. 16966 // TODO: Layering violation 16967 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16968 } 16969 16970 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16971 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16972 return; 16973 } 16974 16975 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16976 16977 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16978 "installPackageLI")) { 16979 if (replace) { 16980 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16981 // Static libs have a synthetic package name containing the version 16982 // and cannot be updated as an update would get a new package name, 16983 // unless this is the exact same version code which is useful for 16984 // development. 16985 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16986 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16987 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16988 + "static-shared libs cannot be updated"); 16989 return; 16990 } 16991 } 16992 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16993 installerPackageName, res, args.installReason); 16994 } else { 16995 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16996 args.user, installerPackageName, volumeUuid, res, args.installReason); 16997 } 16998 } 16999 synchronized (mPackages) { 17000 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17001 if (ps != null) { 17002 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17003 } 17004 17005 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17006 for (int i = 0; i < childCount; i++) { 17007 PackageParser.Package childPkg = pkg.childPackages.get(i); 17008 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17009 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17010 if (childPs != null) { 17011 childRes.newUsers = childPs.queryInstalledUsers( 17012 sUserManager.getUserIds(), true); 17013 } 17014 } 17015 17016 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17017 updateSequenceNumberLP(pkgName, res.newUsers); 17018 } 17019 } 17020 } 17021 17022 private void startIntentFilterVerifications(int userId, boolean replacing, 17023 PackageParser.Package pkg) { 17024 if (mIntentFilterVerifierComponent == null) { 17025 Slog.w(TAG, "No IntentFilter verification will not be done as " 17026 + "there is no IntentFilterVerifier available!"); 17027 return; 17028 } 17029 17030 final int verifierUid = getPackageUid( 17031 mIntentFilterVerifierComponent.getPackageName(), 17032 MATCH_DEBUG_TRIAGED_MISSING, 17033 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17034 17035 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17036 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17037 mHandler.sendMessage(msg); 17038 17039 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17040 for (int i = 0; i < childCount; i++) { 17041 PackageParser.Package childPkg = pkg.childPackages.get(i); 17042 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17043 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17044 mHandler.sendMessage(msg); 17045 } 17046 } 17047 17048 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17049 PackageParser.Package pkg) { 17050 int size = pkg.activities.size(); 17051 if (size == 0) { 17052 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17053 "No activity, so no need to verify any IntentFilter!"); 17054 return; 17055 } 17056 17057 final boolean hasDomainURLs = hasDomainURLs(pkg); 17058 if (!hasDomainURLs) { 17059 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17060 "No domain URLs, so no need to verify any IntentFilter!"); 17061 return; 17062 } 17063 17064 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17065 + " if any IntentFilter from the " + size 17066 + " Activities needs verification ..."); 17067 17068 int count = 0; 17069 final String packageName = pkg.packageName; 17070 17071 synchronized (mPackages) { 17072 // If this is a new install and we see that we've already run verification for this 17073 // package, we have nothing to do: it means the state was restored from backup. 17074 if (!replacing) { 17075 IntentFilterVerificationInfo ivi = 17076 mSettings.getIntentFilterVerificationLPr(packageName); 17077 if (ivi != null) { 17078 if (DEBUG_DOMAIN_VERIFICATION) { 17079 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17080 + ivi.getStatusString()); 17081 } 17082 return; 17083 } 17084 } 17085 17086 // If any filters need to be verified, then all need to be. 17087 boolean needToVerify = false; 17088 for (PackageParser.Activity a : pkg.activities) { 17089 for (ActivityIntentInfo filter : a.intents) { 17090 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17091 if (DEBUG_DOMAIN_VERIFICATION) { 17092 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17093 } 17094 needToVerify = true; 17095 break; 17096 } 17097 } 17098 } 17099 17100 if (needToVerify) { 17101 final int verificationId = mIntentFilterVerificationToken++; 17102 for (PackageParser.Activity a : pkg.activities) { 17103 for (ActivityIntentInfo filter : a.intents) { 17104 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17105 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17106 "Verification needed for IntentFilter:" + filter.toString()); 17107 mIntentFilterVerifier.addOneIntentFilterVerification( 17108 verifierUid, userId, verificationId, filter, packageName); 17109 count++; 17110 } 17111 } 17112 } 17113 } 17114 } 17115 17116 if (count > 0) { 17117 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17118 + " IntentFilter verification" + (count > 1 ? "s" : "") 17119 + " for userId:" + userId); 17120 mIntentFilterVerifier.startVerifications(userId); 17121 } else { 17122 if (DEBUG_DOMAIN_VERIFICATION) { 17123 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17124 } 17125 } 17126 } 17127 17128 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17129 final ComponentName cn = filter.activity.getComponentName(); 17130 final String packageName = cn.getPackageName(); 17131 17132 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17133 packageName); 17134 if (ivi == null) { 17135 return true; 17136 } 17137 int status = ivi.getStatus(); 17138 switch (status) { 17139 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17140 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17141 return true; 17142 17143 default: 17144 // Nothing to do 17145 return false; 17146 } 17147 } 17148 17149 private static boolean isMultiArch(ApplicationInfo info) { 17150 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17151 } 17152 17153 private static boolean isExternal(PackageParser.Package pkg) { 17154 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17155 } 17156 17157 private static boolean isExternal(PackageSetting ps) { 17158 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17159 } 17160 17161 private static boolean isSystemApp(PackageParser.Package pkg) { 17162 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17163 } 17164 17165 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17166 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17167 } 17168 17169 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17170 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17171 } 17172 17173 private static boolean isSystemApp(PackageSetting ps) { 17174 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17175 } 17176 17177 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17178 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17179 } 17180 17181 private int packageFlagsToInstallFlags(PackageSetting ps) { 17182 int installFlags = 0; 17183 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17184 // This existing package was an external ASEC install when we have 17185 // the external flag without a UUID 17186 installFlags |= PackageManager.INSTALL_EXTERNAL; 17187 } 17188 if (ps.isForwardLocked()) { 17189 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17190 } 17191 return installFlags; 17192 } 17193 17194 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17195 if (isExternal(pkg)) { 17196 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17197 return StorageManager.UUID_PRIMARY_PHYSICAL; 17198 } else { 17199 return pkg.volumeUuid; 17200 } 17201 } else { 17202 return StorageManager.UUID_PRIVATE_INTERNAL; 17203 } 17204 } 17205 17206 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17207 if (isExternal(pkg)) { 17208 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17209 return mSettings.getExternalVersion(); 17210 } else { 17211 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17212 } 17213 } else { 17214 return mSettings.getInternalVersion(); 17215 } 17216 } 17217 17218 private void deleteTempPackageFiles() { 17219 final FilenameFilter filter = new FilenameFilter() { 17220 public boolean accept(File dir, String name) { 17221 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17222 } 17223 }; 17224 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17225 file.delete(); 17226 } 17227 } 17228 17229 @Override 17230 public void deletePackageAsUser(String packageName, int versionCode, 17231 IPackageDeleteObserver observer, int userId, int flags) { 17232 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17233 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17234 } 17235 17236 @Override 17237 public void deletePackageVersioned(VersionedPackage versionedPackage, 17238 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17239 mContext.enforceCallingOrSelfPermission( 17240 android.Manifest.permission.DELETE_PACKAGES, null); 17241 Preconditions.checkNotNull(versionedPackage); 17242 Preconditions.checkNotNull(observer); 17243 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17244 PackageManager.VERSION_CODE_HIGHEST, 17245 Integer.MAX_VALUE, "versionCode must be >= -1"); 17246 17247 final String packageName = versionedPackage.getPackageName(); 17248 // TODO: We will change version code to long, so in the new API it is long 17249 final int versionCode = (int) versionedPackage.getVersionCode(); 17250 final String internalPackageName; 17251 synchronized (mPackages) { 17252 // Normalize package name to handle renamed packages and static libs 17253 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17254 // TODO: We will change version code to long, so in the new API it is long 17255 (int) versionedPackage.getVersionCode()); 17256 } 17257 17258 final int uid = Binder.getCallingUid(); 17259 if (!isOrphaned(internalPackageName) 17260 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17261 try { 17262 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17263 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17264 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17265 observer.onUserActionRequired(intent); 17266 } catch (RemoteException re) { 17267 } 17268 return; 17269 } 17270 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17271 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17272 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17273 mContext.enforceCallingOrSelfPermission( 17274 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17275 "deletePackage for user " + userId); 17276 } 17277 17278 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17279 try { 17280 observer.onPackageDeleted(packageName, 17281 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17282 } catch (RemoteException re) { 17283 } 17284 return; 17285 } 17286 17287 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17288 try { 17289 observer.onPackageDeleted(packageName, 17290 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17291 } catch (RemoteException re) { 17292 } 17293 return; 17294 } 17295 17296 if (DEBUG_REMOVE) { 17297 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17298 + " deleteAllUsers: " + deleteAllUsers + " version=" 17299 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17300 ? "VERSION_CODE_HIGHEST" : versionCode)); 17301 } 17302 // Queue up an async operation since the package deletion may take a little while. 17303 mHandler.post(new Runnable() { 17304 public void run() { 17305 mHandler.removeCallbacks(this); 17306 int returnCode; 17307 if (!deleteAllUsers) { 17308 returnCode = deletePackageX(internalPackageName, versionCode, 17309 userId, deleteFlags); 17310 } else { 17311 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17312 internalPackageName, users); 17313 // If nobody is blocking uninstall, proceed with delete for all users 17314 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17315 returnCode = deletePackageX(internalPackageName, versionCode, 17316 userId, deleteFlags); 17317 } else { 17318 // Otherwise uninstall individually for users with blockUninstalls=false 17319 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17320 for (int userId : users) { 17321 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17322 returnCode = deletePackageX(internalPackageName, versionCode, 17323 userId, userFlags); 17324 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17325 Slog.w(TAG, "Package delete failed for user " + userId 17326 + ", returnCode " + returnCode); 17327 } 17328 } 17329 } 17330 // The app has only been marked uninstalled for certain users. 17331 // We still need to report that delete was blocked 17332 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17333 } 17334 } 17335 try { 17336 observer.onPackageDeleted(packageName, returnCode, null); 17337 } catch (RemoteException e) { 17338 Log.i(TAG, "Observer no longer exists."); 17339 } //end catch 17340 } //end run 17341 }); 17342 } 17343 17344 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17345 if (pkg.staticSharedLibName != null) { 17346 return pkg.manifestPackageName; 17347 } 17348 return pkg.packageName; 17349 } 17350 17351 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17352 // Handle renamed packages 17353 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17354 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17355 17356 // Is this a static library? 17357 SparseArray<SharedLibraryEntry> versionedLib = 17358 mStaticLibsByDeclaringPackage.get(packageName); 17359 if (versionedLib == null || versionedLib.size() <= 0) { 17360 return packageName; 17361 } 17362 17363 // Figure out which lib versions the caller can see 17364 SparseIntArray versionsCallerCanSee = null; 17365 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17366 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17367 && callingAppId != Process.ROOT_UID) { 17368 versionsCallerCanSee = new SparseIntArray(); 17369 String libName = versionedLib.valueAt(0).info.getName(); 17370 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17371 if (uidPackages != null) { 17372 for (String uidPackage : uidPackages) { 17373 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17374 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17375 if (libIdx >= 0) { 17376 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17377 versionsCallerCanSee.append(libVersion, libVersion); 17378 } 17379 } 17380 } 17381 } 17382 17383 // Caller can see nothing - done 17384 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17385 return packageName; 17386 } 17387 17388 // Find the version the caller can see and the app version code 17389 SharedLibraryEntry highestVersion = null; 17390 final int versionCount = versionedLib.size(); 17391 for (int i = 0; i < versionCount; i++) { 17392 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17393 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17394 libEntry.info.getVersion()) < 0) { 17395 continue; 17396 } 17397 // TODO: We will change version code to long, so in the new API it is long 17398 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17399 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17400 if (libVersionCode == versionCode) { 17401 return libEntry.apk; 17402 } 17403 } else if (highestVersion == null) { 17404 highestVersion = libEntry; 17405 } else if (libVersionCode > highestVersion.info 17406 .getDeclaringPackage().getVersionCode()) { 17407 highestVersion = libEntry; 17408 } 17409 } 17410 17411 if (highestVersion != null) { 17412 return highestVersion.apk; 17413 } 17414 17415 return packageName; 17416 } 17417 17418 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17419 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17420 || callingUid == Process.SYSTEM_UID) { 17421 return true; 17422 } 17423 final int callingUserId = UserHandle.getUserId(callingUid); 17424 // If the caller installed the pkgName, then allow it to silently uninstall. 17425 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17426 return true; 17427 } 17428 17429 // Allow package verifier to silently uninstall. 17430 if (mRequiredVerifierPackage != null && 17431 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17432 return true; 17433 } 17434 17435 // Allow package uninstaller to silently uninstall. 17436 if (mRequiredUninstallerPackage != null && 17437 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17438 return true; 17439 } 17440 17441 // Allow storage manager to silently uninstall. 17442 if (mStorageManagerPackage != null && 17443 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17444 return true; 17445 } 17446 return false; 17447 } 17448 17449 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17450 int[] result = EMPTY_INT_ARRAY; 17451 for (int userId : userIds) { 17452 if (getBlockUninstallForUser(packageName, userId)) { 17453 result = ArrayUtils.appendInt(result, userId); 17454 } 17455 } 17456 return result; 17457 } 17458 17459 @Override 17460 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17461 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17462 } 17463 17464 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17465 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17466 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17467 try { 17468 if (dpm != null) { 17469 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17470 /* callingUserOnly =*/ false); 17471 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17472 : deviceOwnerComponentName.getPackageName(); 17473 // Does the package contains the device owner? 17474 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17475 // this check is probably not needed, since DO should be registered as a device 17476 // admin on some user too. (Original bug for this: b/17657954) 17477 if (packageName.equals(deviceOwnerPackageName)) { 17478 return true; 17479 } 17480 // Does it contain a device admin for any user? 17481 int[] users; 17482 if (userId == UserHandle.USER_ALL) { 17483 users = sUserManager.getUserIds(); 17484 } else { 17485 users = new int[]{userId}; 17486 } 17487 for (int i = 0; i < users.length; ++i) { 17488 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17489 return true; 17490 } 17491 } 17492 } 17493 } catch (RemoteException e) { 17494 } 17495 return false; 17496 } 17497 17498 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17499 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17500 } 17501 17502 /** 17503 * This method is an internal method that could be get invoked either 17504 * to delete an installed package or to clean up a failed installation. 17505 * After deleting an installed package, a broadcast is sent to notify any 17506 * listeners that the package has been removed. For cleaning up a failed 17507 * installation, the broadcast is not necessary since the package's 17508 * installation wouldn't have sent the initial broadcast either 17509 * The key steps in deleting a package are 17510 * deleting the package information in internal structures like mPackages, 17511 * deleting the packages base directories through installd 17512 * updating mSettings to reflect current status 17513 * persisting settings for later use 17514 * sending a broadcast if necessary 17515 */ 17516 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17517 final PackageRemovedInfo info = new PackageRemovedInfo(); 17518 final boolean res; 17519 17520 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17521 ? UserHandle.USER_ALL : userId; 17522 17523 if (isPackageDeviceAdmin(packageName, removeUser)) { 17524 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17525 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17526 } 17527 17528 PackageSetting uninstalledPs = null; 17529 17530 // for the uninstall-updates case and restricted profiles, remember the per- 17531 // user handle installed state 17532 int[] allUsers; 17533 synchronized (mPackages) { 17534 uninstalledPs = mSettings.mPackages.get(packageName); 17535 if (uninstalledPs == null) { 17536 Slog.w(TAG, "Not removing non-existent package " + packageName); 17537 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17538 } 17539 17540 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17541 && uninstalledPs.versionCode != versionCode) { 17542 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17543 + uninstalledPs.versionCode + " != " + versionCode); 17544 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17545 } 17546 17547 // Static shared libs can be declared by any package, so let us not 17548 // allow removing a package if it provides a lib others depend on. 17549 PackageParser.Package pkg = mPackages.get(packageName); 17550 if (pkg != null && pkg.staticSharedLibName != null) { 17551 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17552 pkg.staticSharedLibVersion); 17553 if (libEntry != null) { 17554 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17555 libEntry.info, 0, userId); 17556 if (!ArrayUtils.isEmpty(libClientPackages)) { 17557 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17558 + " hosting lib " + libEntry.info.getName() + " version " 17559 + libEntry.info.getVersion() + " used by " + libClientPackages); 17560 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17561 } 17562 } 17563 } 17564 17565 allUsers = sUserManager.getUserIds(); 17566 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17567 } 17568 17569 final int freezeUser; 17570 if (isUpdatedSystemApp(uninstalledPs) 17571 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17572 // We're downgrading a system app, which will apply to all users, so 17573 // freeze them all during the downgrade 17574 freezeUser = UserHandle.USER_ALL; 17575 } else { 17576 freezeUser = removeUser; 17577 } 17578 17579 synchronized (mInstallLock) { 17580 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17581 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17582 deleteFlags, "deletePackageX")) { 17583 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17584 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17585 } 17586 synchronized (mPackages) { 17587 if (res) { 17588 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17589 info.removedUsers); 17590 updateSequenceNumberLP(packageName, info.removedUsers); 17591 } 17592 } 17593 } 17594 17595 if (res) { 17596 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17597 info.sendPackageRemovedBroadcasts(killApp); 17598 info.sendSystemPackageUpdatedBroadcasts(); 17599 info.sendSystemPackageAppearedBroadcasts(); 17600 } 17601 // Force a gc here. 17602 Runtime.getRuntime().gc(); 17603 // Delete the resources here after sending the broadcast to let 17604 // other processes clean up before deleting resources. 17605 if (info.args != null) { 17606 synchronized (mInstallLock) { 17607 info.args.doPostDeleteLI(true); 17608 } 17609 } 17610 17611 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17612 } 17613 17614 class PackageRemovedInfo { 17615 String removedPackage; 17616 int uid = -1; 17617 int removedAppId = -1; 17618 int[] origUsers; 17619 int[] removedUsers = null; 17620 SparseArray<Integer> installReasons; 17621 boolean isRemovedPackageSystemUpdate = false; 17622 boolean isUpdate; 17623 boolean dataRemoved; 17624 boolean removedForAllUsers; 17625 boolean isStaticSharedLib; 17626 // Clean up resources deleted packages. 17627 InstallArgs args = null; 17628 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17629 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17630 17631 void sendPackageRemovedBroadcasts(boolean killApp) { 17632 sendPackageRemovedBroadcastInternal(killApp); 17633 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17634 for (int i = 0; i < childCount; i++) { 17635 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17636 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17637 } 17638 } 17639 17640 void sendSystemPackageUpdatedBroadcasts() { 17641 if (isRemovedPackageSystemUpdate) { 17642 sendSystemPackageUpdatedBroadcastsInternal(); 17643 final int childCount = (removedChildPackages != null) 17644 ? removedChildPackages.size() : 0; 17645 for (int i = 0; i < childCount; i++) { 17646 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17647 if (childInfo.isRemovedPackageSystemUpdate) { 17648 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17649 } 17650 } 17651 } 17652 } 17653 17654 void sendSystemPackageAppearedBroadcasts() { 17655 final int packageCount = (appearedChildPackages != null) 17656 ? appearedChildPackages.size() : 0; 17657 for (int i = 0; i < packageCount; i++) { 17658 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17659 sendPackageAddedForNewUsers(installedInfo.name, true, 17660 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17661 } 17662 } 17663 17664 private void sendSystemPackageUpdatedBroadcastsInternal() { 17665 Bundle extras = new Bundle(2); 17666 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17667 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17668 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17669 extras, 0, null, null, null); 17670 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17671 extras, 0, null, null, null); 17672 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17673 null, 0, removedPackage, null, null); 17674 } 17675 17676 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17677 // Don't send static shared library removal broadcasts as these 17678 // libs are visible only the the apps that depend on them an one 17679 // cannot remove the library if it has a dependency. 17680 if (isStaticSharedLib) { 17681 return; 17682 } 17683 Bundle extras = new Bundle(2); 17684 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17685 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17686 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17687 if (isUpdate || isRemovedPackageSystemUpdate) { 17688 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17689 } 17690 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17691 if (removedPackage != null) { 17692 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17693 extras, 0, null, null, removedUsers); 17694 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17695 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17696 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17697 null, null, removedUsers); 17698 } 17699 } 17700 if (removedAppId >= 0) { 17701 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17702 removedUsers); 17703 } 17704 } 17705 } 17706 17707 /* 17708 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17709 * flag is not set, the data directory is removed as well. 17710 * make sure this flag is set for partially installed apps. If not its meaningless to 17711 * delete a partially installed application. 17712 */ 17713 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17714 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17715 String packageName = ps.name; 17716 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17717 // Retrieve object to delete permissions for shared user later on 17718 final PackageParser.Package deletedPkg; 17719 final PackageSetting deletedPs; 17720 // reader 17721 synchronized (mPackages) { 17722 deletedPkg = mPackages.get(packageName); 17723 deletedPs = mSettings.mPackages.get(packageName); 17724 if (outInfo != null) { 17725 outInfo.removedPackage = packageName; 17726 outInfo.isStaticSharedLib = deletedPkg != null 17727 && deletedPkg.staticSharedLibName != null; 17728 outInfo.removedUsers = deletedPs != null 17729 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17730 : null; 17731 } 17732 } 17733 17734 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17735 17736 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17737 final PackageParser.Package resolvedPkg; 17738 if (deletedPkg != null) { 17739 resolvedPkg = deletedPkg; 17740 } else { 17741 // We don't have a parsed package when it lives on an ejected 17742 // adopted storage device, so fake something together 17743 resolvedPkg = new PackageParser.Package(ps.name); 17744 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17745 } 17746 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17747 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17748 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17749 if (outInfo != null) { 17750 outInfo.dataRemoved = true; 17751 } 17752 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17753 } 17754 17755 int removedAppId = -1; 17756 17757 // writer 17758 synchronized (mPackages) { 17759 boolean installedStateChanged = false; 17760 if (deletedPs != null) { 17761 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17762 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17763 clearDefaultBrowserIfNeeded(packageName); 17764 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17765 removedAppId = mSettings.removePackageLPw(packageName); 17766 if (outInfo != null) { 17767 outInfo.removedAppId = removedAppId; 17768 } 17769 updatePermissionsLPw(deletedPs.name, null, 0); 17770 if (deletedPs.sharedUser != null) { 17771 // Remove permissions associated with package. Since runtime 17772 // permissions are per user we have to kill the removed package 17773 // or packages running under the shared user of the removed 17774 // package if revoking the permissions requested only by the removed 17775 // package is successful and this causes a change in gids. 17776 for (int userId : UserManagerService.getInstance().getUserIds()) { 17777 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17778 userId); 17779 if (userIdToKill == UserHandle.USER_ALL 17780 || userIdToKill >= UserHandle.USER_SYSTEM) { 17781 // If gids changed for this user, kill all affected packages. 17782 mHandler.post(new Runnable() { 17783 @Override 17784 public void run() { 17785 // This has to happen with no lock held. 17786 killApplication(deletedPs.name, deletedPs.appId, 17787 KILL_APP_REASON_GIDS_CHANGED); 17788 } 17789 }); 17790 break; 17791 } 17792 } 17793 } 17794 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17795 } 17796 // make sure to preserve per-user disabled state if this removal was just 17797 // a downgrade of a system app to the factory package 17798 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17799 if (DEBUG_REMOVE) { 17800 Slog.d(TAG, "Propagating install state across downgrade"); 17801 } 17802 for (int userId : allUserHandles) { 17803 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17804 if (DEBUG_REMOVE) { 17805 Slog.d(TAG, " user " + userId + " => " + installed); 17806 } 17807 if (installed != ps.getInstalled(userId)) { 17808 installedStateChanged = true; 17809 } 17810 ps.setInstalled(installed, userId); 17811 } 17812 } 17813 } 17814 // can downgrade to reader 17815 if (writeSettings) { 17816 // Save settings now 17817 mSettings.writeLPr(); 17818 } 17819 if (installedStateChanged) { 17820 mSettings.writeKernelMappingLPr(ps); 17821 } 17822 } 17823 if (removedAppId != -1) { 17824 // A user ID was deleted here. Go through all users and remove it 17825 // from KeyStore. 17826 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17827 } 17828 } 17829 17830 static boolean locationIsPrivileged(File path) { 17831 try { 17832 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17833 .getCanonicalPath(); 17834 return path.getCanonicalPath().startsWith(privilegedAppDir); 17835 } catch (IOException e) { 17836 Slog.e(TAG, "Unable to access code path " + path); 17837 } 17838 return false; 17839 } 17840 17841 /* 17842 * Tries to delete system package. 17843 */ 17844 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17845 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17846 boolean writeSettings) { 17847 if (deletedPs.parentPackageName != null) { 17848 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17849 return false; 17850 } 17851 17852 final boolean applyUserRestrictions 17853 = (allUserHandles != null) && (outInfo.origUsers != null); 17854 final PackageSetting disabledPs; 17855 // Confirm if the system package has been updated 17856 // An updated system app can be deleted. This will also have to restore 17857 // the system pkg from system partition 17858 // reader 17859 synchronized (mPackages) { 17860 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17861 } 17862 17863 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17864 + " disabledPs=" + disabledPs); 17865 17866 if (disabledPs == null) { 17867 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17868 return false; 17869 } else if (DEBUG_REMOVE) { 17870 Slog.d(TAG, "Deleting system pkg from data partition"); 17871 } 17872 17873 if (DEBUG_REMOVE) { 17874 if (applyUserRestrictions) { 17875 Slog.d(TAG, "Remembering install states:"); 17876 for (int userId : allUserHandles) { 17877 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17878 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17879 } 17880 } 17881 } 17882 17883 // Delete the updated package 17884 outInfo.isRemovedPackageSystemUpdate = true; 17885 if (outInfo.removedChildPackages != null) { 17886 final int childCount = (deletedPs.childPackageNames != null) 17887 ? deletedPs.childPackageNames.size() : 0; 17888 for (int i = 0; i < childCount; i++) { 17889 String childPackageName = deletedPs.childPackageNames.get(i); 17890 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17891 .contains(childPackageName)) { 17892 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17893 childPackageName); 17894 if (childInfo != null) { 17895 childInfo.isRemovedPackageSystemUpdate = true; 17896 } 17897 } 17898 } 17899 } 17900 17901 if (disabledPs.versionCode < deletedPs.versionCode) { 17902 // Delete data for downgrades 17903 flags &= ~PackageManager.DELETE_KEEP_DATA; 17904 } else { 17905 // Preserve data by setting flag 17906 flags |= PackageManager.DELETE_KEEP_DATA; 17907 } 17908 17909 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17910 outInfo, writeSettings, disabledPs.pkg); 17911 if (!ret) { 17912 return false; 17913 } 17914 17915 // writer 17916 synchronized (mPackages) { 17917 // Reinstate the old system package 17918 enableSystemPackageLPw(disabledPs.pkg); 17919 // Remove any native libraries from the upgraded package. 17920 removeNativeBinariesLI(deletedPs); 17921 } 17922 17923 // Install the system package 17924 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17925 int parseFlags = mDefParseFlags 17926 | PackageParser.PARSE_MUST_BE_APK 17927 | PackageParser.PARSE_IS_SYSTEM 17928 | PackageParser.PARSE_IS_SYSTEM_DIR; 17929 if (locationIsPrivileged(disabledPs.codePath)) { 17930 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17931 } 17932 17933 final PackageParser.Package newPkg; 17934 try { 17935 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17936 0 /* currentTime */, null); 17937 } catch (PackageManagerException e) { 17938 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17939 + e.getMessage()); 17940 return false; 17941 } 17942 17943 try { 17944 // update shared libraries for the newly re-installed system package 17945 updateSharedLibrariesLPr(newPkg, null); 17946 } catch (PackageManagerException e) { 17947 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17948 } 17949 17950 prepareAppDataAfterInstallLIF(newPkg); 17951 17952 // writer 17953 synchronized (mPackages) { 17954 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17955 17956 // Propagate the permissions state as we do not want to drop on the floor 17957 // runtime permissions. The update permissions method below will take 17958 // care of removing obsolete permissions and grant install permissions. 17959 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17960 updatePermissionsLPw(newPkg.packageName, newPkg, 17961 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17962 17963 if (applyUserRestrictions) { 17964 boolean installedStateChanged = false; 17965 if (DEBUG_REMOVE) { 17966 Slog.d(TAG, "Propagating install state across reinstall"); 17967 } 17968 for (int userId : allUserHandles) { 17969 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17970 if (DEBUG_REMOVE) { 17971 Slog.d(TAG, " user " + userId + " => " + installed); 17972 } 17973 if (installed != ps.getInstalled(userId)) { 17974 installedStateChanged = true; 17975 } 17976 ps.setInstalled(installed, userId); 17977 17978 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17979 } 17980 // Regardless of writeSettings we need to ensure that this restriction 17981 // state propagation is persisted 17982 mSettings.writeAllUsersPackageRestrictionsLPr(); 17983 if (installedStateChanged) { 17984 mSettings.writeKernelMappingLPr(ps); 17985 } 17986 } 17987 // can downgrade to reader here 17988 if (writeSettings) { 17989 mSettings.writeLPr(); 17990 } 17991 } 17992 return true; 17993 } 17994 17995 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17996 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17997 PackageRemovedInfo outInfo, boolean writeSettings, 17998 PackageParser.Package replacingPackage) { 17999 synchronized (mPackages) { 18000 if (outInfo != null) { 18001 outInfo.uid = ps.appId; 18002 } 18003 18004 if (outInfo != null && outInfo.removedChildPackages != null) { 18005 final int childCount = (ps.childPackageNames != null) 18006 ? ps.childPackageNames.size() : 0; 18007 for (int i = 0; i < childCount; i++) { 18008 String childPackageName = ps.childPackageNames.get(i); 18009 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18010 if (childPs == null) { 18011 return false; 18012 } 18013 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18014 childPackageName); 18015 if (childInfo != null) { 18016 childInfo.uid = childPs.appId; 18017 } 18018 } 18019 } 18020 } 18021 18022 // Delete package data from internal structures and also remove data if flag is set 18023 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18024 18025 // Delete the child packages data 18026 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18027 for (int i = 0; i < childCount; i++) { 18028 PackageSetting childPs; 18029 synchronized (mPackages) { 18030 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18031 } 18032 if (childPs != null) { 18033 PackageRemovedInfo childOutInfo = (outInfo != null 18034 && outInfo.removedChildPackages != null) 18035 ? outInfo.removedChildPackages.get(childPs.name) : null; 18036 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18037 && (replacingPackage != null 18038 && !replacingPackage.hasChildPackage(childPs.name)) 18039 ? flags & ~DELETE_KEEP_DATA : flags; 18040 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18041 deleteFlags, writeSettings); 18042 } 18043 } 18044 18045 // Delete application code and resources only for parent packages 18046 if (ps.parentPackageName == null) { 18047 if (deleteCodeAndResources && (outInfo != null)) { 18048 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18049 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18050 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18051 } 18052 } 18053 18054 return true; 18055 } 18056 18057 @Override 18058 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18059 int userId) { 18060 mContext.enforceCallingOrSelfPermission( 18061 android.Manifest.permission.DELETE_PACKAGES, null); 18062 synchronized (mPackages) { 18063 PackageSetting ps = mSettings.mPackages.get(packageName); 18064 if (ps == null) { 18065 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18066 return false; 18067 } 18068 // Cannot block uninstall of static shared libs as they are 18069 // considered a part of the using app (emulating static linking). 18070 // Also static libs are installed always on internal storage. 18071 PackageParser.Package pkg = mPackages.get(packageName); 18072 if (pkg != null && pkg.staticSharedLibName != null) { 18073 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18074 + " providing static shared library: " + pkg.staticSharedLibName); 18075 return false; 18076 } 18077 if (!ps.getInstalled(userId)) { 18078 // Can't block uninstall for an app that is not installed or enabled. 18079 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18080 return false; 18081 } 18082 ps.setBlockUninstall(blockUninstall, userId); 18083 mSettings.writePackageRestrictionsLPr(userId); 18084 } 18085 return true; 18086 } 18087 18088 @Override 18089 public boolean getBlockUninstallForUser(String packageName, int userId) { 18090 synchronized (mPackages) { 18091 PackageSetting ps = mSettings.mPackages.get(packageName); 18092 if (ps == null) { 18093 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18094 return false; 18095 } 18096 return ps.getBlockUninstall(userId); 18097 } 18098 } 18099 18100 @Override 18101 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18102 int callingUid = Binder.getCallingUid(); 18103 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18104 throw new SecurityException( 18105 "setRequiredForSystemUser can only be run by the system or root"); 18106 } 18107 synchronized (mPackages) { 18108 PackageSetting ps = mSettings.mPackages.get(packageName); 18109 if (ps == null) { 18110 Log.w(TAG, "Package doesn't exist: " + packageName); 18111 return false; 18112 } 18113 if (systemUserApp) { 18114 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18115 } else { 18116 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18117 } 18118 mSettings.writeLPr(); 18119 } 18120 return true; 18121 } 18122 18123 /* 18124 * This method handles package deletion in general 18125 */ 18126 private boolean deletePackageLIF(String packageName, UserHandle user, 18127 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18128 PackageRemovedInfo outInfo, boolean writeSettings, 18129 PackageParser.Package replacingPackage) { 18130 if (packageName == null) { 18131 Slog.w(TAG, "Attempt to delete null packageName."); 18132 return false; 18133 } 18134 18135 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18136 18137 PackageSetting ps; 18138 synchronized (mPackages) { 18139 ps = mSettings.mPackages.get(packageName); 18140 if (ps == null) { 18141 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18142 return false; 18143 } 18144 18145 if (ps.parentPackageName != null && (!isSystemApp(ps) 18146 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18147 if (DEBUG_REMOVE) { 18148 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18149 + ((user == null) ? UserHandle.USER_ALL : user)); 18150 } 18151 final int removedUserId = (user != null) ? user.getIdentifier() 18152 : UserHandle.USER_ALL; 18153 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18154 return false; 18155 } 18156 markPackageUninstalledForUserLPw(ps, user); 18157 scheduleWritePackageRestrictionsLocked(user); 18158 return true; 18159 } 18160 } 18161 18162 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18163 && user.getIdentifier() != UserHandle.USER_ALL)) { 18164 // The caller is asking that the package only be deleted for a single 18165 // user. To do this, we just mark its uninstalled state and delete 18166 // its data. If this is a system app, we only allow this to happen if 18167 // they have set the special DELETE_SYSTEM_APP which requests different 18168 // semantics than normal for uninstalling system apps. 18169 markPackageUninstalledForUserLPw(ps, user); 18170 18171 if (!isSystemApp(ps)) { 18172 // Do not uninstall the APK if an app should be cached 18173 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18174 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18175 // Other user still have this package installed, so all 18176 // we need to do is clear this user's data and save that 18177 // it is uninstalled. 18178 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18179 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18180 return false; 18181 } 18182 scheduleWritePackageRestrictionsLocked(user); 18183 return true; 18184 } else { 18185 // We need to set it back to 'installed' so the uninstall 18186 // broadcasts will be sent correctly. 18187 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18188 ps.setInstalled(true, user.getIdentifier()); 18189 mSettings.writeKernelMappingLPr(ps); 18190 } 18191 } else { 18192 // This is a system app, so we assume that the 18193 // other users still have this package installed, so all 18194 // we need to do is clear this user's data and save that 18195 // it is uninstalled. 18196 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18197 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18198 return false; 18199 } 18200 scheduleWritePackageRestrictionsLocked(user); 18201 return true; 18202 } 18203 } 18204 18205 // If we are deleting a composite package for all users, keep track 18206 // of result for each child. 18207 if (ps.childPackageNames != null && outInfo != null) { 18208 synchronized (mPackages) { 18209 final int childCount = ps.childPackageNames.size(); 18210 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18211 for (int i = 0; i < childCount; i++) { 18212 String childPackageName = ps.childPackageNames.get(i); 18213 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18214 childInfo.removedPackage = childPackageName; 18215 outInfo.removedChildPackages.put(childPackageName, childInfo); 18216 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18217 if (childPs != null) { 18218 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18219 } 18220 } 18221 } 18222 } 18223 18224 boolean ret = false; 18225 if (isSystemApp(ps)) { 18226 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18227 // When an updated system application is deleted we delete the existing resources 18228 // as well and fall back to existing code in system partition 18229 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18230 } else { 18231 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18232 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18233 outInfo, writeSettings, replacingPackage); 18234 } 18235 18236 // Take a note whether we deleted the package for all users 18237 if (outInfo != null) { 18238 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18239 if (outInfo.removedChildPackages != null) { 18240 synchronized (mPackages) { 18241 final int childCount = outInfo.removedChildPackages.size(); 18242 for (int i = 0; i < childCount; i++) { 18243 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18244 if (childInfo != null) { 18245 childInfo.removedForAllUsers = mPackages.get( 18246 childInfo.removedPackage) == null; 18247 } 18248 } 18249 } 18250 } 18251 // If we uninstalled an update to a system app there may be some 18252 // child packages that appeared as they are declared in the system 18253 // app but were not declared in the update. 18254 if (isSystemApp(ps)) { 18255 synchronized (mPackages) { 18256 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18257 final int childCount = (updatedPs.childPackageNames != null) 18258 ? updatedPs.childPackageNames.size() : 0; 18259 for (int i = 0; i < childCount; i++) { 18260 String childPackageName = updatedPs.childPackageNames.get(i); 18261 if (outInfo.removedChildPackages == null 18262 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18263 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18264 if (childPs == null) { 18265 continue; 18266 } 18267 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18268 installRes.name = childPackageName; 18269 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18270 installRes.pkg = mPackages.get(childPackageName); 18271 installRes.uid = childPs.pkg.applicationInfo.uid; 18272 if (outInfo.appearedChildPackages == null) { 18273 outInfo.appearedChildPackages = new ArrayMap<>(); 18274 } 18275 outInfo.appearedChildPackages.put(childPackageName, installRes); 18276 } 18277 } 18278 } 18279 } 18280 } 18281 18282 return ret; 18283 } 18284 18285 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18286 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18287 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18288 for (int nextUserId : userIds) { 18289 if (DEBUG_REMOVE) { 18290 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18291 } 18292 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18293 false /*installed*/, 18294 true /*stopped*/, 18295 true /*notLaunched*/, 18296 false /*hidden*/, 18297 false /*suspended*/, 18298 false /*instantApp*/, 18299 null /*lastDisableAppCaller*/, 18300 null /*enabledComponents*/, 18301 null /*disabledComponents*/, 18302 false /*blockUninstall*/, 18303 ps.readUserState(nextUserId).domainVerificationStatus, 18304 0, PackageManager.INSTALL_REASON_UNKNOWN); 18305 } 18306 mSettings.writeKernelMappingLPr(ps); 18307 } 18308 18309 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18310 PackageRemovedInfo outInfo) { 18311 final PackageParser.Package pkg; 18312 synchronized (mPackages) { 18313 pkg = mPackages.get(ps.name); 18314 } 18315 18316 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18317 : new int[] {userId}; 18318 for (int nextUserId : userIds) { 18319 if (DEBUG_REMOVE) { 18320 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18321 + nextUserId); 18322 } 18323 18324 destroyAppDataLIF(pkg, userId, 18325 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18326 destroyAppProfilesLIF(pkg, userId); 18327 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18328 schedulePackageCleaning(ps.name, nextUserId, false); 18329 synchronized (mPackages) { 18330 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18331 scheduleWritePackageRestrictionsLocked(nextUserId); 18332 } 18333 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18334 } 18335 } 18336 18337 if (outInfo != null) { 18338 outInfo.removedPackage = ps.name; 18339 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18340 outInfo.removedAppId = ps.appId; 18341 outInfo.removedUsers = userIds; 18342 } 18343 18344 return true; 18345 } 18346 18347 private final class ClearStorageConnection implements ServiceConnection { 18348 IMediaContainerService mContainerService; 18349 18350 @Override 18351 public void onServiceConnected(ComponentName name, IBinder service) { 18352 synchronized (this) { 18353 mContainerService = IMediaContainerService.Stub 18354 .asInterface(Binder.allowBlocking(service)); 18355 notifyAll(); 18356 } 18357 } 18358 18359 @Override 18360 public void onServiceDisconnected(ComponentName name) { 18361 } 18362 } 18363 18364 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18365 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18366 18367 final boolean mounted; 18368 if (Environment.isExternalStorageEmulated()) { 18369 mounted = true; 18370 } else { 18371 final String status = Environment.getExternalStorageState(); 18372 18373 mounted = status.equals(Environment.MEDIA_MOUNTED) 18374 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18375 } 18376 18377 if (!mounted) { 18378 return; 18379 } 18380 18381 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18382 int[] users; 18383 if (userId == UserHandle.USER_ALL) { 18384 users = sUserManager.getUserIds(); 18385 } else { 18386 users = new int[] { userId }; 18387 } 18388 final ClearStorageConnection conn = new ClearStorageConnection(); 18389 if (mContext.bindServiceAsUser( 18390 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18391 try { 18392 for (int curUser : users) { 18393 long timeout = SystemClock.uptimeMillis() + 5000; 18394 synchronized (conn) { 18395 long now; 18396 while (conn.mContainerService == null && 18397 (now = SystemClock.uptimeMillis()) < timeout) { 18398 try { 18399 conn.wait(timeout - now); 18400 } catch (InterruptedException e) { 18401 } 18402 } 18403 } 18404 if (conn.mContainerService == null) { 18405 return; 18406 } 18407 18408 final UserEnvironment userEnv = new UserEnvironment(curUser); 18409 clearDirectory(conn.mContainerService, 18410 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18411 if (allData) { 18412 clearDirectory(conn.mContainerService, 18413 userEnv.buildExternalStorageAppDataDirs(packageName)); 18414 clearDirectory(conn.mContainerService, 18415 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18416 } 18417 } 18418 } finally { 18419 mContext.unbindService(conn); 18420 } 18421 } 18422 } 18423 18424 @Override 18425 public void clearApplicationProfileData(String packageName) { 18426 enforceSystemOrRoot("Only the system can clear all profile data"); 18427 18428 final PackageParser.Package pkg; 18429 synchronized (mPackages) { 18430 pkg = mPackages.get(packageName); 18431 } 18432 18433 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18434 synchronized (mInstallLock) { 18435 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18436 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18437 true /* removeBaseMarker */); 18438 } 18439 } 18440 } 18441 18442 @Override 18443 public void clearApplicationUserData(final String packageName, 18444 final IPackageDataObserver observer, final int userId) { 18445 mContext.enforceCallingOrSelfPermission( 18446 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18447 18448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18449 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18450 18451 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18452 throw new SecurityException("Cannot clear data for a protected package: " 18453 + packageName); 18454 } 18455 // Queue up an async operation since the package deletion may take a little while. 18456 mHandler.post(new Runnable() { 18457 public void run() { 18458 mHandler.removeCallbacks(this); 18459 final boolean succeeded; 18460 try (PackageFreezer freezer = freezePackage(packageName, 18461 "clearApplicationUserData")) { 18462 synchronized (mInstallLock) { 18463 succeeded = clearApplicationUserDataLIF(packageName, userId); 18464 } 18465 clearExternalStorageDataSync(packageName, userId, true); 18466 synchronized (mPackages) { 18467 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18468 packageName, userId); 18469 } 18470 } 18471 if (succeeded) { 18472 // invoke DeviceStorageMonitor's update method to clear any notifications 18473 DeviceStorageMonitorInternal dsm = LocalServices 18474 .getService(DeviceStorageMonitorInternal.class); 18475 if (dsm != null) { 18476 dsm.checkMemory(); 18477 } 18478 } 18479 if(observer != null) { 18480 try { 18481 observer.onRemoveCompleted(packageName, succeeded); 18482 } catch (RemoteException e) { 18483 Log.i(TAG, "Observer no longer exists."); 18484 } 18485 } //end if observer 18486 } //end run 18487 }); 18488 } 18489 18490 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18491 if (packageName == null) { 18492 Slog.w(TAG, "Attempt to delete null packageName."); 18493 return false; 18494 } 18495 18496 // Try finding details about the requested package 18497 PackageParser.Package pkg; 18498 synchronized (mPackages) { 18499 pkg = mPackages.get(packageName); 18500 if (pkg == null) { 18501 final PackageSetting ps = mSettings.mPackages.get(packageName); 18502 if (ps != null) { 18503 pkg = ps.pkg; 18504 } 18505 } 18506 18507 if (pkg == null) { 18508 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18509 return false; 18510 } 18511 18512 PackageSetting ps = (PackageSetting) pkg.mExtras; 18513 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18514 } 18515 18516 clearAppDataLIF(pkg, userId, 18517 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18518 18519 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18520 removeKeystoreDataIfNeeded(userId, appId); 18521 18522 UserManagerInternal umInternal = getUserManagerInternal(); 18523 final int flags; 18524 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18525 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18526 } else if (umInternal.isUserRunning(userId)) { 18527 flags = StorageManager.FLAG_STORAGE_DE; 18528 } else { 18529 flags = 0; 18530 } 18531 prepareAppDataContentsLIF(pkg, userId, flags); 18532 18533 return true; 18534 } 18535 18536 /** 18537 * Reverts user permission state changes (permissions and flags) in 18538 * all packages for a given user. 18539 * 18540 * @param userId The device user for which to do a reset. 18541 */ 18542 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18543 final int packageCount = mPackages.size(); 18544 for (int i = 0; i < packageCount; i++) { 18545 PackageParser.Package pkg = mPackages.valueAt(i); 18546 PackageSetting ps = (PackageSetting) pkg.mExtras; 18547 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18548 } 18549 } 18550 18551 private void resetNetworkPolicies(int userId) { 18552 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18553 } 18554 18555 /** 18556 * Reverts user permission state changes (permissions and flags). 18557 * 18558 * @param ps The package for which to reset. 18559 * @param userId The device user for which to do a reset. 18560 */ 18561 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18562 final PackageSetting ps, final int userId) { 18563 if (ps.pkg == null) { 18564 return; 18565 } 18566 18567 // These are flags that can change base on user actions. 18568 final int userSettableMask = FLAG_PERMISSION_USER_SET 18569 | FLAG_PERMISSION_USER_FIXED 18570 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18571 | FLAG_PERMISSION_REVIEW_REQUIRED; 18572 18573 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18574 | FLAG_PERMISSION_POLICY_FIXED; 18575 18576 boolean writeInstallPermissions = false; 18577 boolean writeRuntimePermissions = false; 18578 18579 final int permissionCount = ps.pkg.requestedPermissions.size(); 18580 for (int i = 0; i < permissionCount; i++) { 18581 String permission = ps.pkg.requestedPermissions.get(i); 18582 18583 BasePermission bp = mSettings.mPermissions.get(permission); 18584 if (bp == null) { 18585 continue; 18586 } 18587 18588 // If shared user we just reset the state to which only this app contributed. 18589 if (ps.sharedUser != null) { 18590 boolean used = false; 18591 final int packageCount = ps.sharedUser.packages.size(); 18592 for (int j = 0; j < packageCount; j++) { 18593 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18594 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18595 && pkg.pkg.requestedPermissions.contains(permission)) { 18596 used = true; 18597 break; 18598 } 18599 } 18600 if (used) { 18601 continue; 18602 } 18603 } 18604 18605 PermissionsState permissionsState = ps.getPermissionsState(); 18606 18607 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18608 18609 // Always clear the user settable flags. 18610 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18611 bp.name) != null; 18612 // If permission review is enabled and this is a legacy app, mark the 18613 // permission as requiring a review as this is the initial state. 18614 int flags = 0; 18615 if (mPermissionReviewRequired 18616 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18617 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18618 } 18619 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18620 if (hasInstallState) { 18621 writeInstallPermissions = true; 18622 } else { 18623 writeRuntimePermissions = true; 18624 } 18625 } 18626 18627 // Below is only runtime permission handling. 18628 if (!bp.isRuntime()) { 18629 continue; 18630 } 18631 18632 // Never clobber system or policy. 18633 if ((oldFlags & policyOrSystemFlags) != 0) { 18634 continue; 18635 } 18636 18637 // If this permission was granted by default, make sure it is. 18638 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18639 if (permissionsState.grantRuntimePermission(bp, userId) 18640 != PERMISSION_OPERATION_FAILURE) { 18641 writeRuntimePermissions = true; 18642 } 18643 // If permission review is enabled the permissions for a legacy apps 18644 // are represented as constantly granted runtime ones, so don't revoke. 18645 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18646 // Otherwise, reset the permission. 18647 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18648 switch (revokeResult) { 18649 case PERMISSION_OPERATION_SUCCESS: 18650 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18651 writeRuntimePermissions = true; 18652 final int appId = ps.appId; 18653 mHandler.post(new Runnable() { 18654 @Override 18655 public void run() { 18656 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18657 } 18658 }); 18659 } break; 18660 } 18661 } 18662 } 18663 18664 // Synchronously write as we are taking permissions away. 18665 if (writeRuntimePermissions) { 18666 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18667 } 18668 18669 // Synchronously write as we are taking permissions away. 18670 if (writeInstallPermissions) { 18671 mSettings.writeLPr(); 18672 } 18673 } 18674 18675 /** 18676 * Remove entries from the keystore daemon. Will only remove it if the 18677 * {@code appId} is valid. 18678 */ 18679 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18680 if (appId < 0) { 18681 return; 18682 } 18683 18684 final KeyStore keyStore = KeyStore.getInstance(); 18685 if (keyStore != null) { 18686 if (userId == UserHandle.USER_ALL) { 18687 for (final int individual : sUserManager.getUserIds()) { 18688 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18689 } 18690 } else { 18691 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18692 } 18693 } else { 18694 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18695 } 18696 } 18697 18698 @Override 18699 public void deleteApplicationCacheFiles(final String packageName, 18700 final IPackageDataObserver observer) { 18701 final int userId = UserHandle.getCallingUserId(); 18702 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18703 } 18704 18705 @Override 18706 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18707 final IPackageDataObserver observer) { 18708 mContext.enforceCallingOrSelfPermission( 18709 android.Manifest.permission.DELETE_CACHE_FILES, null); 18710 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18711 /* requireFullPermission= */ true, /* checkShell= */ false, 18712 "delete application cache files"); 18713 18714 final PackageParser.Package pkg; 18715 synchronized (mPackages) { 18716 pkg = mPackages.get(packageName); 18717 } 18718 18719 // Queue up an async operation since the package deletion may take a little while. 18720 mHandler.post(new Runnable() { 18721 public void run() { 18722 synchronized (mInstallLock) { 18723 final int flags = StorageManager.FLAG_STORAGE_DE 18724 | StorageManager.FLAG_STORAGE_CE; 18725 // We're only clearing cache files, so we don't care if the 18726 // app is unfrozen and still able to run 18727 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18728 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18729 } 18730 clearExternalStorageDataSync(packageName, userId, false); 18731 if (observer != null) { 18732 try { 18733 observer.onRemoveCompleted(packageName, true); 18734 } catch (RemoteException e) { 18735 Log.i(TAG, "Observer no longer exists."); 18736 } 18737 } 18738 } 18739 }); 18740 } 18741 18742 @Override 18743 public void getPackageSizeInfo(final String packageName, int userHandle, 18744 final IPackageStatsObserver observer) { 18745 mContext.enforceCallingOrSelfPermission( 18746 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18747 if (packageName == null) { 18748 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18749 } 18750 18751 PackageStats stats = new PackageStats(packageName, userHandle); 18752 18753 /* 18754 * Queue up an async operation since the package measurement may take a 18755 * little while. 18756 */ 18757 Message msg = mHandler.obtainMessage(INIT_COPY); 18758 msg.obj = new MeasureParams(stats, observer); 18759 mHandler.sendMessage(msg); 18760 } 18761 18762 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18763 final PackageSetting ps; 18764 synchronized (mPackages) { 18765 ps = mSettings.mPackages.get(packageName); 18766 if (ps == null) { 18767 Slog.w(TAG, "Failed to find settings for " + packageName); 18768 return false; 18769 } 18770 } 18771 18772 final String[] packageNames = { packageName }; 18773 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18774 final String[] codePaths = { ps.codePathString }; 18775 18776 try { 18777 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18778 ps.appId, ceDataInodes, codePaths, stats); 18779 18780 // For now, ignore code size of packages on system partition 18781 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18782 stats.codeSize = 0; 18783 } 18784 18785 // External clients expect these to be tracked separately 18786 stats.dataSize -= stats.cacheSize; 18787 18788 } catch (InstallerException e) { 18789 Slog.w(TAG, String.valueOf(e)); 18790 return false; 18791 } 18792 18793 return true; 18794 } 18795 18796 private int getUidTargetSdkVersionLockedLPr(int uid) { 18797 Object obj = mSettings.getUserIdLPr(uid); 18798 if (obj instanceof SharedUserSetting) { 18799 final SharedUserSetting sus = (SharedUserSetting) obj; 18800 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18801 final Iterator<PackageSetting> it = sus.packages.iterator(); 18802 while (it.hasNext()) { 18803 final PackageSetting ps = it.next(); 18804 if (ps.pkg != null) { 18805 int v = ps.pkg.applicationInfo.targetSdkVersion; 18806 if (v < vers) vers = v; 18807 } 18808 } 18809 return vers; 18810 } else if (obj instanceof PackageSetting) { 18811 final PackageSetting ps = (PackageSetting) obj; 18812 if (ps.pkg != null) { 18813 return ps.pkg.applicationInfo.targetSdkVersion; 18814 } 18815 } 18816 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18817 } 18818 18819 @Override 18820 public void addPreferredActivity(IntentFilter filter, int match, 18821 ComponentName[] set, ComponentName activity, int userId) { 18822 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18823 "Adding preferred"); 18824 } 18825 18826 private void addPreferredActivityInternal(IntentFilter filter, int match, 18827 ComponentName[] set, ComponentName activity, boolean always, int userId, 18828 String opname) { 18829 // writer 18830 int callingUid = Binder.getCallingUid(); 18831 enforceCrossUserPermission(callingUid, userId, 18832 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18833 if (filter.countActions() == 0) { 18834 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18835 return; 18836 } 18837 synchronized (mPackages) { 18838 if (mContext.checkCallingOrSelfPermission( 18839 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18840 != PackageManager.PERMISSION_GRANTED) { 18841 if (getUidTargetSdkVersionLockedLPr(callingUid) 18842 < Build.VERSION_CODES.FROYO) { 18843 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18844 + callingUid); 18845 return; 18846 } 18847 mContext.enforceCallingOrSelfPermission( 18848 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18849 } 18850 18851 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18852 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18853 + userId + ":"); 18854 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18855 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18856 scheduleWritePackageRestrictionsLocked(userId); 18857 postPreferredActivityChangedBroadcast(userId); 18858 } 18859 } 18860 18861 private void postPreferredActivityChangedBroadcast(int userId) { 18862 mHandler.post(() -> { 18863 final IActivityManager am = ActivityManager.getService(); 18864 if (am == null) { 18865 return; 18866 } 18867 18868 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18869 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18870 try { 18871 am.broadcastIntent(null, intent, null, null, 18872 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18873 null, false, false, userId); 18874 } catch (RemoteException e) { 18875 } 18876 }); 18877 } 18878 18879 @Override 18880 public void replacePreferredActivity(IntentFilter filter, int match, 18881 ComponentName[] set, ComponentName activity, int userId) { 18882 if (filter.countActions() != 1) { 18883 throw new IllegalArgumentException( 18884 "replacePreferredActivity expects filter to have only 1 action."); 18885 } 18886 if (filter.countDataAuthorities() != 0 18887 || filter.countDataPaths() != 0 18888 || filter.countDataSchemes() > 1 18889 || filter.countDataTypes() != 0) { 18890 throw new IllegalArgumentException( 18891 "replacePreferredActivity expects filter to have no data authorities, " + 18892 "paths, or types; and at most one scheme."); 18893 } 18894 18895 final int callingUid = Binder.getCallingUid(); 18896 enforceCrossUserPermission(callingUid, userId, 18897 true /* requireFullPermission */, false /* checkShell */, 18898 "replace preferred activity"); 18899 synchronized (mPackages) { 18900 if (mContext.checkCallingOrSelfPermission( 18901 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18902 != PackageManager.PERMISSION_GRANTED) { 18903 if (getUidTargetSdkVersionLockedLPr(callingUid) 18904 < Build.VERSION_CODES.FROYO) { 18905 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18906 + Binder.getCallingUid()); 18907 return; 18908 } 18909 mContext.enforceCallingOrSelfPermission( 18910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18911 } 18912 18913 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18914 if (pir != null) { 18915 // Get all of the existing entries that exactly match this filter. 18916 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18917 if (existing != null && existing.size() == 1) { 18918 PreferredActivity cur = existing.get(0); 18919 if (DEBUG_PREFERRED) { 18920 Slog.i(TAG, "Checking replace of preferred:"); 18921 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18922 if (!cur.mPref.mAlways) { 18923 Slog.i(TAG, " -- CUR; not mAlways!"); 18924 } else { 18925 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18926 Slog.i(TAG, " -- CUR: mSet=" 18927 + Arrays.toString(cur.mPref.mSetComponents)); 18928 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18929 Slog.i(TAG, " -- NEW: mMatch=" 18930 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18931 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18932 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18933 } 18934 } 18935 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18936 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18937 && cur.mPref.sameSet(set)) { 18938 // Setting the preferred activity to what it happens to be already 18939 if (DEBUG_PREFERRED) { 18940 Slog.i(TAG, "Replacing with same preferred activity " 18941 + cur.mPref.mShortComponent + " for user " 18942 + userId + ":"); 18943 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18944 } 18945 return; 18946 } 18947 } 18948 18949 if (existing != null) { 18950 if (DEBUG_PREFERRED) { 18951 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18952 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18953 } 18954 for (int i = 0; i < existing.size(); i++) { 18955 PreferredActivity pa = existing.get(i); 18956 if (DEBUG_PREFERRED) { 18957 Slog.i(TAG, "Removing existing preferred activity " 18958 + pa.mPref.mComponent + ":"); 18959 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18960 } 18961 pir.removeFilter(pa); 18962 } 18963 } 18964 } 18965 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18966 "Replacing preferred"); 18967 } 18968 } 18969 18970 @Override 18971 public void clearPackagePreferredActivities(String packageName) { 18972 final int uid = Binder.getCallingUid(); 18973 // writer 18974 synchronized (mPackages) { 18975 PackageParser.Package pkg = mPackages.get(packageName); 18976 if (pkg == null || pkg.applicationInfo.uid != uid) { 18977 if (mContext.checkCallingOrSelfPermission( 18978 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18979 != PackageManager.PERMISSION_GRANTED) { 18980 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18981 < Build.VERSION_CODES.FROYO) { 18982 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18983 + Binder.getCallingUid()); 18984 return; 18985 } 18986 mContext.enforceCallingOrSelfPermission( 18987 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18988 } 18989 } 18990 18991 int user = UserHandle.getCallingUserId(); 18992 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18993 scheduleWritePackageRestrictionsLocked(user); 18994 } 18995 } 18996 } 18997 18998 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18999 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19000 ArrayList<PreferredActivity> removed = null; 19001 boolean changed = false; 19002 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19003 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19004 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19005 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19006 continue; 19007 } 19008 Iterator<PreferredActivity> it = pir.filterIterator(); 19009 while (it.hasNext()) { 19010 PreferredActivity pa = it.next(); 19011 // Mark entry for removal only if it matches the package name 19012 // and the entry is of type "always". 19013 if (packageName == null || 19014 (pa.mPref.mComponent.getPackageName().equals(packageName) 19015 && pa.mPref.mAlways)) { 19016 if (removed == null) { 19017 removed = new ArrayList<PreferredActivity>(); 19018 } 19019 removed.add(pa); 19020 } 19021 } 19022 if (removed != null) { 19023 for (int j=0; j<removed.size(); j++) { 19024 PreferredActivity pa = removed.get(j); 19025 pir.removeFilter(pa); 19026 } 19027 changed = true; 19028 } 19029 } 19030 if (changed) { 19031 postPreferredActivityChangedBroadcast(userId); 19032 } 19033 return changed; 19034 } 19035 19036 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19037 private void clearIntentFilterVerificationsLPw(int userId) { 19038 final int packageCount = mPackages.size(); 19039 for (int i = 0; i < packageCount; i++) { 19040 PackageParser.Package pkg = mPackages.valueAt(i); 19041 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19042 } 19043 } 19044 19045 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19046 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19047 if (userId == UserHandle.USER_ALL) { 19048 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19049 sUserManager.getUserIds())) { 19050 for (int oneUserId : sUserManager.getUserIds()) { 19051 scheduleWritePackageRestrictionsLocked(oneUserId); 19052 } 19053 } 19054 } else { 19055 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19056 scheduleWritePackageRestrictionsLocked(userId); 19057 } 19058 } 19059 } 19060 19061 void clearDefaultBrowserIfNeeded(String packageName) { 19062 for (int oneUserId : sUserManager.getUserIds()) { 19063 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19064 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19065 if (packageName.equals(defaultBrowserPackageName)) { 19066 setDefaultBrowserPackageName(null, oneUserId); 19067 } 19068 } 19069 } 19070 19071 @Override 19072 public void resetApplicationPreferences(int userId) { 19073 mContext.enforceCallingOrSelfPermission( 19074 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19075 final long identity = Binder.clearCallingIdentity(); 19076 // writer 19077 try { 19078 synchronized (mPackages) { 19079 clearPackagePreferredActivitiesLPw(null, userId); 19080 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19081 // TODO: We have to reset the default SMS and Phone. This requires 19082 // significant refactoring to keep all default apps in the package 19083 // manager (cleaner but more work) or have the services provide 19084 // callbacks to the package manager to request a default app reset. 19085 applyFactoryDefaultBrowserLPw(userId); 19086 clearIntentFilterVerificationsLPw(userId); 19087 primeDomainVerificationsLPw(userId); 19088 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19089 scheduleWritePackageRestrictionsLocked(userId); 19090 } 19091 resetNetworkPolicies(userId); 19092 } finally { 19093 Binder.restoreCallingIdentity(identity); 19094 } 19095 } 19096 19097 @Override 19098 public int getPreferredActivities(List<IntentFilter> outFilters, 19099 List<ComponentName> outActivities, String packageName) { 19100 19101 int num = 0; 19102 final int userId = UserHandle.getCallingUserId(); 19103 // reader 19104 synchronized (mPackages) { 19105 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19106 if (pir != null) { 19107 final Iterator<PreferredActivity> it = pir.filterIterator(); 19108 while (it.hasNext()) { 19109 final PreferredActivity pa = it.next(); 19110 if (packageName == null 19111 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19112 && pa.mPref.mAlways)) { 19113 if (outFilters != null) { 19114 outFilters.add(new IntentFilter(pa)); 19115 } 19116 if (outActivities != null) { 19117 outActivities.add(pa.mPref.mComponent); 19118 } 19119 } 19120 } 19121 } 19122 } 19123 19124 return num; 19125 } 19126 19127 @Override 19128 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19129 int userId) { 19130 int callingUid = Binder.getCallingUid(); 19131 if (callingUid != Process.SYSTEM_UID) { 19132 throw new SecurityException( 19133 "addPersistentPreferredActivity can only be run by the system"); 19134 } 19135 if (filter.countActions() == 0) { 19136 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19137 return; 19138 } 19139 synchronized (mPackages) { 19140 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19141 ":"); 19142 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19143 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19144 new PersistentPreferredActivity(filter, activity)); 19145 scheduleWritePackageRestrictionsLocked(userId); 19146 postPreferredActivityChangedBroadcast(userId); 19147 } 19148 } 19149 19150 @Override 19151 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19152 int callingUid = Binder.getCallingUid(); 19153 if (callingUid != Process.SYSTEM_UID) { 19154 throw new SecurityException( 19155 "clearPackagePersistentPreferredActivities can only be run by the system"); 19156 } 19157 ArrayList<PersistentPreferredActivity> removed = null; 19158 boolean changed = false; 19159 synchronized (mPackages) { 19160 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19161 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19162 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19163 .valueAt(i); 19164 if (userId != thisUserId) { 19165 continue; 19166 } 19167 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19168 while (it.hasNext()) { 19169 PersistentPreferredActivity ppa = it.next(); 19170 // Mark entry for removal only if it matches the package name. 19171 if (ppa.mComponent.getPackageName().equals(packageName)) { 19172 if (removed == null) { 19173 removed = new ArrayList<PersistentPreferredActivity>(); 19174 } 19175 removed.add(ppa); 19176 } 19177 } 19178 if (removed != null) { 19179 for (int j=0; j<removed.size(); j++) { 19180 PersistentPreferredActivity ppa = removed.get(j); 19181 ppir.removeFilter(ppa); 19182 } 19183 changed = true; 19184 } 19185 } 19186 19187 if (changed) { 19188 scheduleWritePackageRestrictionsLocked(userId); 19189 postPreferredActivityChangedBroadcast(userId); 19190 } 19191 } 19192 } 19193 19194 /** 19195 * Common machinery for picking apart a restored XML blob and passing 19196 * it to a caller-supplied functor to be applied to the running system. 19197 */ 19198 private void restoreFromXml(XmlPullParser parser, int userId, 19199 String expectedStartTag, BlobXmlRestorer functor) 19200 throws IOException, XmlPullParserException { 19201 int type; 19202 while ((type = parser.next()) != XmlPullParser.START_TAG 19203 && type != XmlPullParser.END_DOCUMENT) { 19204 } 19205 if (type != XmlPullParser.START_TAG) { 19206 // oops didn't find a start tag?! 19207 if (DEBUG_BACKUP) { 19208 Slog.e(TAG, "Didn't find start tag during restore"); 19209 } 19210 return; 19211 } 19212Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19213 // this is supposed to be TAG_PREFERRED_BACKUP 19214 if (!expectedStartTag.equals(parser.getName())) { 19215 if (DEBUG_BACKUP) { 19216 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19217 } 19218 return; 19219 } 19220 19221 // skip interfering stuff, then we're aligned with the backing implementation 19222 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19223Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19224 functor.apply(parser, userId); 19225 } 19226 19227 private interface BlobXmlRestorer { 19228 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19229 } 19230 19231 /** 19232 * Non-Binder method, support for the backup/restore mechanism: write the 19233 * full set of preferred activities in its canonical XML format. Returns the 19234 * XML output as a byte array, or null if there is none. 19235 */ 19236 @Override 19237 public byte[] getPreferredActivityBackup(int userId) { 19238 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19239 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19240 } 19241 19242 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19243 try { 19244 final XmlSerializer serializer = new FastXmlSerializer(); 19245 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19246 serializer.startDocument(null, true); 19247 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19248 19249 synchronized (mPackages) { 19250 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19251 } 19252 19253 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19254 serializer.endDocument(); 19255 serializer.flush(); 19256 } catch (Exception e) { 19257 if (DEBUG_BACKUP) { 19258 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19259 } 19260 return null; 19261 } 19262 19263 return dataStream.toByteArray(); 19264 } 19265 19266 @Override 19267 public void restorePreferredActivities(byte[] backup, int userId) { 19268 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19269 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19270 } 19271 19272 try { 19273 final XmlPullParser parser = Xml.newPullParser(); 19274 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19275 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19276 new BlobXmlRestorer() { 19277 @Override 19278 public void apply(XmlPullParser parser, int userId) 19279 throws XmlPullParserException, IOException { 19280 synchronized (mPackages) { 19281 mSettings.readPreferredActivitiesLPw(parser, userId); 19282 } 19283 } 19284 } ); 19285 } catch (Exception e) { 19286 if (DEBUG_BACKUP) { 19287 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19288 } 19289 } 19290 } 19291 19292 /** 19293 * Non-Binder method, support for the backup/restore mechanism: write the 19294 * default browser (etc) settings in its canonical XML format. Returns the default 19295 * browser XML representation as a byte array, or null if there is none. 19296 */ 19297 @Override 19298 public byte[] getDefaultAppsBackup(int userId) { 19299 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19300 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19301 } 19302 19303 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19304 try { 19305 final XmlSerializer serializer = new FastXmlSerializer(); 19306 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19307 serializer.startDocument(null, true); 19308 serializer.startTag(null, TAG_DEFAULT_APPS); 19309 19310 synchronized (mPackages) { 19311 mSettings.writeDefaultAppsLPr(serializer, userId); 19312 } 19313 19314 serializer.endTag(null, TAG_DEFAULT_APPS); 19315 serializer.endDocument(); 19316 serializer.flush(); 19317 } catch (Exception e) { 19318 if (DEBUG_BACKUP) { 19319 Slog.e(TAG, "Unable to write default apps for backup", e); 19320 } 19321 return null; 19322 } 19323 19324 return dataStream.toByteArray(); 19325 } 19326 19327 @Override 19328 public void restoreDefaultApps(byte[] backup, int userId) { 19329 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19330 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19331 } 19332 19333 try { 19334 final XmlPullParser parser = Xml.newPullParser(); 19335 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19336 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19337 new BlobXmlRestorer() { 19338 @Override 19339 public void apply(XmlPullParser parser, int userId) 19340 throws XmlPullParserException, IOException { 19341 synchronized (mPackages) { 19342 mSettings.readDefaultAppsLPw(parser, userId); 19343 } 19344 } 19345 } ); 19346 } catch (Exception e) { 19347 if (DEBUG_BACKUP) { 19348 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19349 } 19350 } 19351 } 19352 19353 @Override 19354 public byte[] getIntentFilterVerificationBackup(int userId) { 19355 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19356 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19357 } 19358 19359 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19360 try { 19361 final XmlSerializer serializer = new FastXmlSerializer(); 19362 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19363 serializer.startDocument(null, true); 19364 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19365 19366 synchronized (mPackages) { 19367 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19368 } 19369 19370 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19371 serializer.endDocument(); 19372 serializer.flush(); 19373 } catch (Exception e) { 19374 if (DEBUG_BACKUP) { 19375 Slog.e(TAG, "Unable to write default apps for backup", e); 19376 } 19377 return null; 19378 } 19379 19380 return dataStream.toByteArray(); 19381 } 19382 19383 @Override 19384 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19385 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19386 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19387 } 19388 19389 try { 19390 final XmlPullParser parser = Xml.newPullParser(); 19391 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19392 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19393 new BlobXmlRestorer() { 19394 @Override 19395 public void apply(XmlPullParser parser, int userId) 19396 throws XmlPullParserException, IOException { 19397 synchronized (mPackages) { 19398 mSettings.readAllDomainVerificationsLPr(parser, userId); 19399 mSettings.writeLPr(); 19400 } 19401 } 19402 } ); 19403 } catch (Exception e) { 19404 if (DEBUG_BACKUP) { 19405 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19406 } 19407 } 19408 } 19409 19410 @Override 19411 public byte[] getPermissionGrantBackup(int userId) { 19412 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19413 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19414 } 19415 19416 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19417 try { 19418 final XmlSerializer serializer = new FastXmlSerializer(); 19419 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19420 serializer.startDocument(null, true); 19421 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19422 19423 synchronized (mPackages) { 19424 serializeRuntimePermissionGrantsLPr(serializer, userId); 19425 } 19426 19427 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19428 serializer.endDocument(); 19429 serializer.flush(); 19430 } catch (Exception e) { 19431 if (DEBUG_BACKUP) { 19432 Slog.e(TAG, "Unable to write default apps for backup", e); 19433 } 19434 return null; 19435 } 19436 19437 return dataStream.toByteArray(); 19438 } 19439 19440 @Override 19441 public void restorePermissionGrants(byte[] backup, int userId) { 19442 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19443 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19444 } 19445 19446 try { 19447 final XmlPullParser parser = Xml.newPullParser(); 19448 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19449 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19450 new BlobXmlRestorer() { 19451 @Override 19452 public void apply(XmlPullParser parser, int userId) 19453 throws XmlPullParserException, IOException { 19454 synchronized (mPackages) { 19455 processRestoredPermissionGrantsLPr(parser, userId); 19456 } 19457 } 19458 } ); 19459 } catch (Exception e) { 19460 if (DEBUG_BACKUP) { 19461 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19462 } 19463 } 19464 } 19465 19466 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19467 throws IOException { 19468 serializer.startTag(null, TAG_ALL_GRANTS); 19469 19470 final int N = mSettings.mPackages.size(); 19471 for (int i = 0; i < N; i++) { 19472 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19473 boolean pkgGrantsKnown = false; 19474 19475 PermissionsState packagePerms = ps.getPermissionsState(); 19476 19477 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19478 final int grantFlags = state.getFlags(); 19479 // only look at grants that are not system/policy fixed 19480 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19481 final boolean isGranted = state.isGranted(); 19482 // And only back up the user-twiddled state bits 19483 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19484 final String packageName = mSettings.mPackages.keyAt(i); 19485 if (!pkgGrantsKnown) { 19486 serializer.startTag(null, TAG_GRANT); 19487 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19488 pkgGrantsKnown = true; 19489 } 19490 19491 final boolean userSet = 19492 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19493 final boolean userFixed = 19494 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19495 final boolean revoke = 19496 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19497 19498 serializer.startTag(null, TAG_PERMISSION); 19499 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19500 if (isGranted) { 19501 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19502 } 19503 if (userSet) { 19504 serializer.attribute(null, ATTR_USER_SET, "true"); 19505 } 19506 if (userFixed) { 19507 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19508 } 19509 if (revoke) { 19510 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19511 } 19512 serializer.endTag(null, TAG_PERMISSION); 19513 } 19514 } 19515 } 19516 19517 if (pkgGrantsKnown) { 19518 serializer.endTag(null, TAG_GRANT); 19519 } 19520 } 19521 19522 serializer.endTag(null, TAG_ALL_GRANTS); 19523 } 19524 19525 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19526 throws XmlPullParserException, IOException { 19527 String pkgName = null; 19528 int outerDepth = parser.getDepth(); 19529 int type; 19530 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19531 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19532 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19533 continue; 19534 } 19535 19536 final String tagName = parser.getName(); 19537 if (tagName.equals(TAG_GRANT)) { 19538 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19539 if (DEBUG_BACKUP) { 19540 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19541 } 19542 } else if (tagName.equals(TAG_PERMISSION)) { 19543 19544 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19545 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19546 19547 int newFlagSet = 0; 19548 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19549 newFlagSet |= FLAG_PERMISSION_USER_SET; 19550 } 19551 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19552 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19553 } 19554 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19555 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19556 } 19557 if (DEBUG_BACKUP) { 19558 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19559 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19560 } 19561 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19562 if (ps != null) { 19563 // Already installed so we apply the grant immediately 19564 if (DEBUG_BACKUP) { 19565 Slog.v(TAG, " + already installed; applying"); 19566 } 19567 PermissionsState perms = ps.getPermissionsState(); 19568 BasePermission bp = mSettings.mPermissions.get(permName); 19569 if (bp != null) { 19570 if (isGranted) { 19571 perms.grantRuntimePermission(bp, userId); 19572 } 19573 if (newFlagSet != 0) { 19574 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19575 } 19576 } 19577 } else { 19578 // Need to wait for post-restore install to apply the grant 19579 if (DEBUG_BACKUP) { 19580 Slog.v(TAG, " - not yet installed; saving for later"); 19581 } 19582 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19583 isGranted, newFlagSet, userId); 19584 } 19585 } else { 19586 PackageManagerService.reportSettingsProblem(Log.WARN, 19587 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19588 XmlUtils.skipCurrentTag(parser); 19589 } 19590 } 19591 19592 scheduleWriteSettingsLocked(); 19593 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19594 } 19595 19596 @Override 19597 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19598 int sourceUserId, int targetUserId, int flags) { 19599 mContext.enforceCallingOrSelfPermission( 19600 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19601 int callingUid = Binder.getCallingUid(); 19602 enforceOwnerRights(ownerPackage, callingUid); 19603 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19604 if (intentFilter.countActions() == 0) { 19605 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19606 return; 19607 } 19608 synchronized (mPackages) { 19609 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19610 ownerPackage, targetUserId, flags); 19611 CrossProfileIntentResolver resolver = 19612 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19613 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19614 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19615 if (existing != null) { 19616 int size = existing.size(); 19617 for (int i = 0; i < size; i++) { 19618 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19619 return; 19620 } 19621 } 19622 } 19623 resolver.addFilter(newFilter); 19624 scheduleWritePackageRestrictionsLocked(sourceUserId); 19625 } 19626 } 19627 19628 @Override 19629 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19630 mContext.enforceCallingOrSelfPermission( 19631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19632 int callingUid = Binder.getCallingUid(); 19633 enforceOwnerRights(ownerPackage, callingUid); 19634 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19635 synchronized (mPackages) { 19636 CrossProfileIntentResolver resolver = 19637 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19638 ArraySet<CrossProfileIntentFilter> set = 19639 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19640 for (CrossProfileIntentFilter filter : set) { 19641 if (filter.getOwnerPackage().equals(ownerPackage)) { 19642 resolver.removeFilter(filter); 19643 } 19644 } 19645 scheduleWritePackageRestrictionsLocked(sourceUserId); 19646 } 19647 } 19648 19649 // Enforcing that callingUid is owning pkg on userId 19650 private void enforceOwnerRights(String pkg, int callingUid) { 19651 // The system owns everything. 19652 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19653 return; 19654 } 19655 int callingUserId = UserHandle.getUserId(callingUid); 19656 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19657 if (pi == null) { 19658 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19659 + callingUserId); 19660 } 19661 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19662 throw new SecurityException("Calling uid " + callingUid 19663 + " does not own package " + pkg); 19664 } 19665 } 19666 19667 @Override 19668 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19669 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19670 } 19671 19672 private Intent getHomeIntent() { 19673 Intent intent = new Intent(Intent.ACTION_MAIN); 19674 intent.addCategory(Intent.CATEGORY_HOME); 19675 intent.addCategory(Intent.CATEGORY_DEFAULT); 19676 return intent; 19677 } 19678 19679 private IntentFilter getHomeFilter() { 19680 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19681 filter.addCategory(Intent.CATEGORY_HOME); 19682 filter.addCategory(Intent.CATEGORY_DEFAULT); 19683 return filter; 19684 } 19685 19686 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19687 int userId) { 19688 Intent intent = getHomeIntent(); 19689 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19690 PackageManager.GET_META_DATA, userId); 19691 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19692 true, false, false, userId); 19693 19694 allHomeCandidates.clear(); 19695 if (list != null) { 19696 for (ResolveInfo ri : list) { 19697 allHomeCandidates.add(ri); 19698 } 19699 } 19700 return (preferred == null || preferred.activityInfo == null) 19701 ? null 19702 : new ComponentName(preferred.activityInfo.packageName, 19703 preferred.activityInfo.name); 19704 } 19705 19706 @Override 19707 public void setHomeActivity(ComponentName comp, int userId) { 19708 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19709 getHomeActivitiesAsUser(homeActivities, userId); 19710 19711 boolean found = false; 19712 19713 final int size = homeActivities.size(); 19714 final ComponentName[] set = new ComponentName[size]; 19715 for (int i = 0; i < size; i++) { 19716 final ResolveInfo candidate = homeActivities.get(i); 19717 final ActivityInfo info = candidate.activityInfo; 19718 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19719 set[i] = activityName; 19720 if (!found && activityName.equals(comp)) { 19721 found = true; 19722 } 19723 } 19724 if (!found) { 19725 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19726 + userId); 19727 } 19728 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19729 set, comp, userId); 19730 } 19731 19732 private @Nullable String getSetupWizardPackageName() { 19733 final Intent intent = new Intent(Intent.ACTION_MAIN); 19734 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19735 19736 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19737 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19738 | MATCH_DISABLED_COMPONENTS, 19739 UserHandle.myUserId()); 19740 if (matches.size() == 1) { 19741 return matches.get(0).getComponentInfo().packageName; 19742 } else { 19743 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19744 + ": matches=" + matches); 19745 return null; 19746 } 19747 } 19748 19749 private @Nullable String getStorageManagerPackageName() { 19750 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19751 19752 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19753 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19754 | MATCH_DISABLED_COMPONENTS, 19755 UserHandle.myUserId()); 19756 if (matches.size() == 1) { 19757 return matches.get(0).getComponentInfo().packageName; 19758 } else { 19759 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19760 + matches.size() + ": matches=" + matches); 19761 return null; 19762 } 19763 } 19764 19765 @Override 19766 public void setApplicationEnabledSetting(String appPackageName, 19767 int newState, int flags, int userId, String callingPackage) { 19768 if (!sUserManager.exists(userId)) return; 19769 if (callingPackage == null) { 19770 callingPackage = Integer.toString(Binder.getCallingUid()); 19771 } 19772 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19773 } 19774 19775 @Override 19776 public void setComponentEnabledSetting(ComponentName componentName, 19777 int newState, int flags, int userId) { 19778 if (!sUserManager.exists(userId)) return; 19779 setEnabledSetting(componentName.getPackageName(), 19780 componentName.getClassName(), newState, flags, userId, null); 19781 } 19782 19783 private void setEnabledSetting(final String packageName, String className, int newState, 19784 final int flags, int userId, String callingPackage) { 19785 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19786 || newState == COMPONENT_ENABLED_STATE_ENABLED 19787 || newState == COMPONENT_ENABLED_STATE_DISABLED 19788 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19789 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19790 throw new IllegalArgumentException("Invalid new component state: " 19791 + newState); 19792 } 19793 PackageSetting pkgSetting; 19794 final int uid = Binder.getCallingUid(); 19795 final int permission; 19796 if (uid == Process.SYSTEM_UID) { 19797 permission = PackageManager.PERMISSION_GRANTED; 19798 } else { 19799 permission = mContext.checkCallingOrSelfPermission( 19800 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19801 } 19802 enforceCrossUserPermission(uid, userId, 19803 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19804 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19805 boolean sendNow = false; 19806 boolean isApp = (className == null); 19807 String componentName = isApp ? packageName : className; 19808 int packageUid = -1; 19809 ArrayList<String> components; 19810 19811 // writer 19812 synchronized (mPackages) { 19813 pkgSetting = mSettings.mPackages.get(packageName); 19814 if (pkgSetting == null) { 19815 if (className == null) { 19816 throw new IllegalArgumentException("Unknown package: " + packageName); 19817 } 19818 throw new IllegalArgumentException( 19819 "Unknown component: " + packageName + "/" + className); 19820 } 19821 } 19822 19823 // Limit who can change which apps 19824 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19825 // Don't allow apps that don't have permission to modify other apps 19826 if (!allowedByPermission) { 19827 throw new SecurityException( 19828 "Permission Denial: attempt to change component state from pid=" 19829 + Binder.getCallingPid() 19830 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19831 } 19832 // Don't allow changing protected packages. 19833 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19834 throw new SecurityException("Cannot disable a protected package: " + packageName); 19835 } 19836 } 19837 19838 synchronized (mPackages) { 19839 if (uid == Process.SHELL_UID 19840 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19841 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19842 // unless it is a test package. 19843 int oldState = pkgSetting.getEnabled(userId); 19844 if (className == null 19845 && 19846 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19847 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19848 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19849 && 19850 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19851 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19852 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19853 // ok 19854 } else { 19855 throw new SecurityException( 19856 "Shell cannot change component state for " + packageName + "/" 19857 + className + " to " + newState); 19858 } 19859 } 19860 if (className == null) { 19861 // We're dealing with an application/package level state change 19862 if (pkgSetting.getEnabled(userId) == newState) { 19863 // Nothing to do 19864 return; 19865 } 19866 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19867 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19868 // Don't care about who enables an app. 19869 callingPackage = null; 19870 } 19871 pkgSetting.setEnabled(newState, userId, callingPackage); 19872 // pkgSetting.pkg.mSetEnabled = newState; 19873 } else { 19874 // We're dealing with a component level state change 19875 // First, verify that this is a valid class name. 19876 PackageParser.Package pkg = pkgSetting.pkg; 19877 if (pkg == null || !pkg.hasComponentClassName(className)) { 19878 if (pkg != null && 19879 pkg.applicationInfo.targetSdkVersion >= 19880 Build.VERSION_CODES.JELLY_BEAN) { 19881 throw new IllegalArgumentException("Component class " + className 19882 + " does not exist in " + packageName); 19883 } else { 19884 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19885 + className + " does not exist in " + packageName); 19886 } 19887 } 19888 switch (newState) { 19889 case COMPONENT_ENABLED_STATE_ENABLED: 19890 if (!pkgSetting.enableComponentLPw(className, userId)) { 19891 return; 19892 } 19893 break; 19894 case COMPONENT_ENABLED_STATE_DISABLED: 19895 if (!pkgSetting.disableComponentLPw(className, userId)) { 19896 return; 19897 } 19898 break; 19899 case COMPONENT_ENABLED_STATE_DEFAULT: 19900 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19901 return; 19902 } 19903 break; 19904 default: 19905 Slog.e(TAG, "Invalid new component state: " + newState); 19906 return; 19907 } 19908 } 19909 scheduleWritePackageRestrictionsLocked(userId); 19910 updateSequenceNumberLP(packageName, new int[] { userId }); 19911 components = mPendingBroadcasts.get(userId, packageName); 19912 final boolean newPackage = components == null; 19913 if (newPackage) { 19914 components = new ArrayList<String>(); 19915 } 19916 if (!components.contains(componentName)) { 19917 components.add(componentName); 19918 } 19919 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19920 sendNow = true; 19921 // Purge entry from pending broadcast list if another one exists already 19922 // since we are sending one right away. 19923 mPendingBroadcasts.remove(userId, packageName); 19924 } else { 19925 if (newPackage) { 19926 mPendingBroadcasts.put(userId, packageName, components); 19927 } 19928 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19929 // Schedule a message 19930 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19931 } 19932 } 19933 } 19934 19935 long callingId = Binder.clearCallingIdentity(); 19936 try { 19937 if (sendNow) { 19938 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19939 sendPackageChangedBroadcast(packageName, 19940 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19941 } 19942 } finally { 19943 Binder.restoreCallingIdentity(callingId); 19944 } 19945 } 19946 19947 @Override 19948 public void flushPackageRestrictionsAsUser(int userId) { 19949 if (!sUserManager.exists(userId)) { 19950 return; 19951 } 19952 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19953 false /* checkShell */, "flushPackageRestrictions"); 19954 synchronized (mPackages) { 19955 mSettings.writePackageRestrictionsLPr(userId); 19956 mDirtyUsers.remove(userId); 19957 if (mDirtyUsers.isEmpty()) { 19958 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19959 } 19960 } 19961 } 19962 19963 private void sendPackageChangedBroadcast(String packageName, 19964 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19965 if (DEBUG_INSTALL) 19966 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19967 + componentNames); 19968 Bundle extras = new Bundle(4); 19969 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19970 String nameList[] = new String[componentNames.size()]; 19971 componentNames.toArray(nameList); 19972 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19973 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19974 extras.putInt(Intent.EXTRA_UID, packageUid); 19975 // If this is not reporting a change of the overall package, then only send it 19976 // to registered receivers. We don't want to launch a swath of apps for every 19977 // little component state change. 19978 final int flags = !componentNames.contains(packageName) 19979 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19980 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19981 new int[] {UserHandle.getUserId(packageUid)}); 19982 } 19983 19984 @Override 19985 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19986 if (!sUserManager.exists(userId)) return; 19987 final int uid = Binder.getCallingUid(); 19988 final int permission = mContext.checkCallingOrSelfPermission( 19989 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19990 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19991 enforceCrossUserPermission(uid, userId, 19992 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19993 // writer 19994 synchronized (mPackages) { 19995 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19996 allowedByPermission, uid, userId)) { 19997 scheduleWritePackageRestrictionsLocked(userId); 19998 } 19999 } 20000 } 20001 20002 @Override 20003 public String getInstallerPackageName(String packageName) { 20004 // reader 20005 synchronized (mPackages) { 20006 return mSettings.getInstallerPackageNameLPr(packageName); 20007 } 20008 } 20009 20010 public boolean isOrphaned(String packageName) { 20011 // reader 20012 synchronized (mPackages) { 20013 return mSettings.isOrphaned(packageName); 20014 } 20015 } 20016 20017 @Override 20018 public int getApplicationEnabledSetting(String packageName, int userId) { 20019 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20020 int uid = Binder.getCallingUid(); 20021 enforceCrossUserPermission(uid, userId, 20022 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20023 // reader 20024 synchronized (mPackages) { 20025 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20026 } 20027 } 20028 20029 @Override 20030 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20031 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20032 int uid = Binder.getCallingUid(); 20033 enforceCrossUserPermission(uid, userId, 20034 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20035 // reader 20036 synchronized (mPackages) { 20037 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20038 } 20039 } 20040 20041 @Override 20042 public void enterSafeMode() { 20043 enforceSystemOrRoot("Only the system can request entering safe mode"); 20044 20045 if (!mSystemReady) { 20046 mSafeMode = true; 20047 } 20048 } 20049 20050 @Override 20051 public void systemReady() { 20052 mSystemReady = true; 20053 20054 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20055 // disabled after already being started. 20056 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20057 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20058 20059 // Read the compatibilty setting when the system is ready. 20060 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20061 mContext.getContentResolver(), 20062 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20063 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20064 if (DEBUG_SETTINGS) { 20065 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20066 } 20067 20068 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20069 20070 synchronized (mPackages) { 20071 // Verify that all of the preferred activity components actually 20072 // exist. It is possible for applications to be updated and at 20073 // that point remove a previously declared activity component that 20074 // had been set as a preferred activity. We try to clean this up 20075 // the next time we encounter that preferred activity, but it is 20076 // possible for the user flow to never be able to return to that 20077 // situation so here we do a sanity check to make sure we haven't 20078 // left any junk around. 20079 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20080 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20081 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20082 removed.clear(); 20083 for (PreferredActivity pa : pir.filterSet()) { 20084 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20085 removed.add(pa); 20086 } 20087 } 20088 if (removed.size() > 0) { 20089 for (int r=0; r<removed.size(); r++) { 20090 PreferredActivity pa = removed.get(r); 20091 Slog.w(TAG, "Removing dangling preferred activity: " 20092 + pa.mPref.mComponent); 20093 pir.removeFilter(pa); 20094 } 20095 mSettings.writePackageRestrictionsLPr( 20096 mSettings.mPreferredActivities.keyAt(i)); 20097 } 20098 } 20099 20100 for (int userId : UserManagerService.getInstance().getUserIds()) { 20101 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20102 grantPermissionsUserIds = ArrayUtils.appendInt( 20103 grantPermissionsUserIds, userId); 20104 } 20105 } 20106 } 20107 sUserManager.systemReady(); 20108 20109 // If we upgraded grant all default permissions before kicking off. 20110 for (int userId : grantPermissionsUserIds) { 20111 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20112 } 20113 20114 // If we did not grant default permissions, we preload from this the 20115 // default permission exceptions lazily to ensure we don't hit the 20116 // disk on a new user creation. 20117 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20118 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20119 } 20120 20121 // Kick off any messages waiting for system ready 20122 if (mPostSystemReadyMessages != null) { 20123 for (Message msg : mPostSystemReadyMessages) { 20124 msg.sendToTarget(); 20125 } 20126 mPostSystemReadyMessages = null; 20127 } 20128 20129 // Watch for external volumes that come and go over time 20130 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20131 storage.registerListener(mStorageListener); 20132 20133 mInstallerService.systemReady(); 20134 mPackageDexOptimizer.systemReady(); 20135 20136 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20137 StorageManagerInternal.class); 20138 StorageManagerInternal.addExternalStoragePolicy( 20139 new StorageManagerInternal.ExternalStorageMountPolicy() { 20140 @Override 20141 public int getMountMode(int uid, String packageName) { 20142 if (Process.isIsolated(uid)) { 20143 return Zygote.MOUNT_EXTERNAL_NONE; 20144 } 20145 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20146 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20147 } 20148 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20149 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20150 } 20151 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20152 return Zygote.MOUNT_EXTERNAL_READ; 20153 } 20154 return Zygote.MOUNT_EXTERNAL_WRITE; 20155 } 20156 20157 @Override 20158 public boolean hasExternalStorage(int uid, String packageName) { 20159 return true; 20160 } 20161 }); 20162 20163 // Now that we're mostly running, clean up stale users and apps 20164 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20165 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20166 20167 if (mPrivappPermissionsViolations != null) { 20168 Slog.wtf(TAG,"Signature|privileged permissions not in " 20169 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20170 mPrivappPermissionsViolations = null; 20171 } 20172 } 20173 20174 @Override 20175 public boolean isSafeMode() { 20176 return mSafeMode; 20177 } 20178 20179 @Override 20180 public boolean hasSystemUidErrors() { 20181 return mHasSystemUidErrors; 20182 } 20183 20184 static String arrayToString(int[] array) { 20185 StringBuffer buf = new StringBuffer(128); 20186 buf.append('['); 20187 if (array != null) { 20188 for (int i=0; i<array.length; i++) { 20189 if (i > 0) buf.append(", "); 20190 buf.append(array[i]); 20191 } 20192 } 20193 buf.append(']'); 20194 return buf.toString(); 20195 } 20196 20197 static class DumpState { 20198 public static final int DUMP_LIBS = 1 << 0; 20199 public static final int DUMP_FEATURES = 1 << 1; 20200 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20201 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20202 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20203 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20204 public static final int DUMP_PERMISSIONS = 1 << 6; 20205 public static final int DUMP_PACKAGES = 1 << 7; 20206 public static final int DUMP_SHARED_USERS = 1 << 8; 20207 public static final int DUMP_MESSAGES = 1 << 9; 20208 public static final int DUMP_PROVIDERS = 1 << 10; 20209 public static final int DUMP_VERIFIERS = 1 << 11; 20210 public static final int DUMP_PREFERRED = 1 << 12; 20211 public static final int DUMP_PREFERRED_XML = 1 << 13; 20212 public static final int DUMP_KEYSETS = 1 << 14; 20213 public static final int DUMP_VERSION = 1 << 15; 20214 public static final int DUMP_INSTALLS = 1 << 16; 20215 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20216 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20217 public static final int DUMP_FROZEN = 1 << 19; 20218 public static final int DUMP_DEXOPT = 1 << 20; 20219 public static final int DUMP_COMPILER_STATS = 1 << 21; 20220 20221 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20222 20223 private int mTypes; 20224 20225 private int mOptions; 20226 20227 private boolean mTitlePrinted; 20228 20229 private SharedUserSetting mSharedUser; 20230 20231 public boolean isDumping(int type) { 20232 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20233 return true; 20234 } 20235 20236 return (mTypes & type) != 0; 20237 } 20238 20239 public void setDump(int type) { 20240 mTypes |= type; 20241 } 20242 20243 public boolean isOptionEnabled(int option) { 20244 return (mOptions & option) != 0; 20245 } 20246 20247 public void setOptionEnabled(int option) { 20248 mOptions |= option; 20249 } 20250 20251 public boolean onTitlePrinted() { 20252 final boolean printed = mTitlePrinted; 20253 mTitlePrinted = true; 20254 return printed; 20255 } 20256 20257 public boolean getTitlePrinted() { 20258 return mTitlePrinted; 20259 } 20260 20261 public void setTitlePrinted(boolean enabled) { 20262 mTitlePrinted = enabled; 20263 } 20264 20265 public SharedUserSetting getSharedUser() { 20266 return mSharedUser; 20267 } 20268 20269 public void setSharedUser(SharedUserSetting user) { 20270 mSharedUser = user; 20271 } 20272 } 20273 20274 @Override 20275 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20276 FileDescriptor err, String[] args, ShellCallback callback, 20277 ResultReceiver resultReceiver) { 20278 (new PackageManagerShellCommand(this)).exec( 20279 this, in, out, err, args, callback, resultReceiver); 20280 } 20281 20282 @Override 20283 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20284 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20285 != PackageManager.PERMISSION_GRANTED) { 20286 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20287 + Binder.getCallingPid() 20288 + ", uid=" + Binder.getCallingUid() 20289 + " without permission " 20290 + android.Manifest.permission.DUMP); 20291 return; 20292 } 20293 20294 DumpState dumpState = new DumpState(); 20295 boolean fullPreferred = false; 20296 boolean checkin = false; 20297 20298 String packageName = null; 20299 ArraySet<String> permissionNames = null; 20300 20301 int opti = 0; 20302 while (opti < args.length) { 20303 String opt = args[opti]; 20304 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20305 break; 20306 } 20307 opti++; 20308 20309 if ("-a".equals(opt)) { 20310 // Right now we only know how to print all. 20311 } else if ("-h".equals(opt)) { 20312 pw.println("Package manager dump options:"); 20313 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20314 pw.println(" --checkin: dump for a checkin"); 20315 pw.println(" -f: print details of intent filters"); 20316 pw.println(" -h: print this help"); 20317 pw.println(" cmd may be one of:"); 20318 pw.println(" l[ibraries]: list known shared libraries"); 20319 pw.println(" f[eatures]: list device features"); 20320 pw.println(" k[eysets]: print known keysets"); 20321 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20322 pw.println(" perm[issions]: dump permissions"); 20323 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20324 pw.println(" pref[erred]: print preferred package settings"); 20325 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20326 pw.println(" prov[iders]: dump content providers"); 20327 pw.println(" p[ackages]: dump installed packages"); 20328 pw.println(" s[hared-users]: dump shared user IDs"); 20329 pw.println(" m[essages]: print collected runtime messages"); 20330 pw.println(" v[erifiers]: print package verifier info"); 20331 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20332 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20333 pw.println(" version: print database version info"); 20334 pw.println(" write: write current settings now"); 20335 pw.println(" installs: details about install sessions"); 20336 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20337 pw.println(" dexopt: dump dexopt state"); 20338 pw.println(" compiler-stats: dump compiler statistics"); 20339 pw.println(" <package.name>: info about given package"); 20340 return; 20341 } else if ("--checkin".equals(opt)) { 20342 checkin = true; 20343 } else if ("-f".equals(opt)) { 20344 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20345 } else { 20346 pw.println("Unknown argument: " + opt + "; use -h for help"); 20347 } 20348 } 20349 20350 // Is the caller requesting to dump a particular piece of data? 20351 if (opti < args.length) { 20352 String cmd = args[opti]; 20353 opti++; 20354 // Is this a package name? 20355 if ("android".equals(cmd) || cmd.contains(".")) { 20356 packageName = cmd; 20357 // When dumping a single package, we always dump all of its 20358 // filter information since the amount of data will be reasonable. 20359 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20360 } else if ("check-permission".equals(cmd)) { 20361 if (opti >= args.length) { 20362 pw.println("Error: check-permission missing permission argument"); 20363 return; 20364 } 20365 String perm = args[opti]; 20366 opti++; 20367 if (opti >= args.length) { 20368 pw.println("Error: check-permission missing package argument"); 20369 return; 20370 } 20371 20372 String pkg = args[opti]; 20373 opti++; 20374 int user = UserHandle.getUserId(Binder.getCallingUid()); 20375 if (opti < args.length) { 20376 try { 20377 user = Integer.parseInt(args[opti]); 20378 } catch (NumberFormatException e) { 20379 pw.println("Error: check-permission user argument is not a number: " 20380 + args[opti]); 20381 return; 20382 } 20383 } 20384 20385 // Normalize package name to handle renamed packages and static libs 20386 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20387 20388 pw.println(checkPermission(perm, pkg, user)); 20389 return; 20390 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20391 dumpState.setDump(DumpState.DUMP_LIBS); 20392 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20393 dumpState.setDump(DumpState.DUMP_FEATURES); 20394 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20395 if (opti >= args.length) { 20396 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20397 | DumpState.DUMP_SERVICE_RESOLVERS 20398 | DumpState.DUMP_RECEIVER_RESOLVERS 20399 | DumpState.DUMP_CONTENT_RESOLVERS); 20400 } else { 20401 while (opti < args.length) { 20402 String name = args[opti]; 20403 if ("a".equals(name) || "activity".equals(name)) { 20404 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20405 } else if ("s".equals(name) || "service".equals(name)) { 20406 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20407 } else if ("r".equals(name) || "receiver".equals(name)) { 20408 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20409 } else if ("c".equals(name) || "content".equals(name)) { 20410 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20411 } else { 20412 pw.println("Error: unknown resolver table type: " + name); 20413 return; 20414 } 20415 opti++; 20416 } 20417 } 20418 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20419 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20420 } else if ("permission".equals(cmd)) { 20421 if (opti >= args.length) { 20422 pw.println("Error: permission requires permission name"); 20423 return; 20424 } 20425 permissionNames = new ArraySet<>(); 20426 while (opti < args.length) { 20427 permissionNames.add(args[opti]); 20428 opti++; 20429 } 20430 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20431 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20432 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20433 dumpState.setDump(DumpState.DUMP_PREFERRED); 20434 } else if ("preferred-xml".equals(cmd)) { 20435 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20436 if (opti < args.length && "--full".equals(args[opti])) { 20437 fullPreferred = true; 20438 opti++; 20439 } 20440 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20441 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20442 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20443 dumpState.setDump(DumpState.DUMP_PACKAGES); 20444 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20445 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20446 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20447 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20448 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20449 dumpState.setDump(DumpState.DUMP_MESSAGES); 20450 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20451 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20452 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20453 || "intent-filter-verifiers".equals(cmd)) { 20454 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20455 } else if ("version".equals(cmd)) { 20456 dumpState.setDump(DumpState.DUMP_VERSION); 20457 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20458 dumpState.setDump(DumpState.DUMP_KEYSETS); 20459 } else if ("installs".equals(cmd)) { 20460 dumpState.setDump(DumpState.DUMP_INSTALLS); 20461 } else if ("frozen".equals(cmd)) { 20462 dumpState.setDump(DumpState.DUMP_FROZEN); 20463 } else if ("dexopt".equals(cmd)) { 20464 dumpState.setDump(DumpState.DUMP_DEXOPT); 20465 } else if ("compiler-stats".equals(cmd)) { 20466 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20467 } else if ("write".equals(cmd)) { 20468 synchronized (mPackages) { 20469 mSettings.writeLPr(); 20470 pw.println("Settings written."); 20471 return; 20472 } 20473 } 20474 } 20475 20476 if (checkin) { 20477 pw.println("vers,1"); 20478 } 20479 20480 // reader 20481 synchronized (mPackages) { 20482 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20483 if (!checkin) { 20484 if (dumpState.onTitlePrinted()) 20485 pw.println(); 20486 pw.println("Database versions:"); 20487 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20488 } 20489 } 20490 20491 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20492 if (!checkin) { 20493 if (dumpState.onTitlePrinted()) 20494 pw.println(); 20495 pw.println("Verifiers:"); 20496 pw.print(" Required: "); 20497 pw.print(mRequiredVerifierPackage); 20498 pw.print(" (uid="); 20499 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20500 UserHandle.USER_SYSTEM)); 20501 pw.println(")"); 20502 } else if (mRequiredVerifierPackage != null) { 20503 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20504 pw.print(","); 20505 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20506 UserHandle.USER_SYSTEM)); 20507 } 20508 } 20509 20510 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20511 packageName == null) { 20512 if (mIntentFilterVerifierComponent != null) { 20513 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20514 if (!checkin) { 20515 if (dumpState.onTitlePrinted()) 20516 pw.println(); 20517 pw.println("Intent Filter Verifier:"); 20518 pw.print(" Using: "); 20519 pw.print(verifierPackageName); 20520 pw.print(" (uid="); 20521 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20522 UserHandle.USER_SYSTEM)); 20523 pw.println(")"); 20524 } else if (verifierPackageName != null) { 20525 pw.print("ifv,"); pw.print(verifierPackageName); 20526 pw.print(","); 20527 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20528 UserHandle.USER_SYSTEM)); 20529 } 20530 } else { 20531 pw.println(); 20532 pw.println("No Intent Filter Verifier available!"); 20533 } 20534 } 20535 20536 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20537 boolean printedHeader = false; 20538 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20539 while (it.hasNext()) { 20540 String libName = it.next(); 20541 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20542 if (versionedLib == null) { 20543 continue; 20544 } 20545 final int versionCount = versionedLib.size(); 20546 for (int i = 0; i < versionCount; i++) { 20547 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20548 if (!checkin) { 20549 if (!printedHeader) { 20550 if (dumpState.onTitlePrinted()) 20551 pw.println(); 20552 pw.println("Libraries:"); 20553 printedHeader = true; 20554 } 20555 pw.print(" "); 20556 } else { 20557 pw.print("lib,"); 20558 } 20559 pw.print(libEntry.info.getName()); 20560 if (libEntry.info.isStatic()) { 20561 pw.print(" version=" + libEntry.info.getVersion()); 20562 } 20563 if (!checkin) { 20564 pw.print(" -> "); 20565 } 20566 if (libEntry.path != null) { 20567 pw.print(" (jar) "); 20568 pw.print(libEntry.path); 20569 } else { 20570 pw.print(" (apk) "); 20571 pw.print(libEntry.apk); 20572 } 20573 pw.println(); 20574 } 20575 } 20576 } 20577 20578 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20579 if (dumpState.onTitlePrinted()) 20580 pw.println(); 20581 if (!checkin) { 20582 pw.println("Features:"); 20583 } 20584 20585 synchronized (mAvailableFeatures) { 20586 for (FeatureInfo feat : mAvailableFeatures.values()) { 20587 if (checkin) { 20588 pw.print("feat,"); 20589 pw.print(feat.name); 20590 pw.print(","); 20591 pw.println(feat.version); 20592 } else { 20593 pw.print(" "); 20594 pw.print(feat.name); 20595 if (feat.version > 0) { 20596 pw.print(" version="); 20597 pw.print(feat.version); 20598 } 20599 pw.println(); 20600 } 20601 } 20602 } 20603 } 20604 20605 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20606 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20607 : "Activity Resolver Table:", " ", packageName, 20608 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20609 dumpState.setTitlePrinted(true); 20610 } 20611 } 20612 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20613 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20614 : "Receiver Resolver Table:", " ", packageName, 20615 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20616 dumpState.setTitlePrinted(true); 20617 } 20618 } 20619 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20620 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20621 : "Service Resolver Table:", " ", packageName, 20622 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20623 dumpState.setTitlePrinted(true); 20624 } 20625 } 20626 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20627 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20628 : "Provider Resolver Table:", " ", packageName, 20629 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20630 dumpState.setTitlePrinted(true); 20631 } 20632 } 20633 20634 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20635 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20636 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20637 int user = mSettings.mPreferredActivities.keyAt(i); 20638 if (pir.dump(pw, 20639 dumpState.getTitlePrinted() 20640 ? "\nPreferred Activities User " + user + ":" 20641 : "Preferred Activities User " + user + ":", " ", 20642 packageName, true, false)) { 20643 dumpState.setTitlePrinted(true); 20644 } 20645 } 20646 } 20647 20648 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20649 pw.flush(); 20650 FileOutputStream fout = new FileOutputStream(fd); 20651 BufferedOutputStream str = new BufferedOutputStream(fout); 20652 XmlSerializer serializer = new FastXmlSerializer(); 20653 try { 20654 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20655 serializer.startDocument(null, true); 20656 serializer.setFeature( 20657 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20658 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20659 serializer.endDocument(); 20660 serializer.flush(); 20661 } catch (IllegalArgumentException e) { 20662 pw.println("Failed writing: " + e); 20663 } catch (IllegalStateException e) { 20664 pw.println("Failed writing: " + e); 20665 } catch (IOException e) { 20666 pw.println("Failed writing: " + e); 20667 } 20668 } 20669 20670 if (!checkin 20671 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20672 && packageName == null) { 20673 pw.println(); 20674 int count = mSettings.mPackages.size(); 20675 if (count == 0) { 20676 pw.println("No applications!"); 20677 pw.println(); 20678 } else { 20679 final String prefix = " "; 20680 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20681 if (allPackageSettings.size() == 0) { 20682 pw.println("No domain preferred apps!"); 20683 pw.println(); 20684 } else { 20685 pw.println("App verification status:"); 20686 pw.println(); 20687 count = 0; 20688 for (PackageSetting ps : allPackageSettings) { 20689 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20690 if (ivi == null || ivi.getPackageName() == null) continue; 20691 pw.println(prefix + "Package: " + ivi.getPackageName()); 20692 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20693 pw.println(prefix + "Status: " + ivi.getStatusString()); 20694 pw.println(); 20695 count++; 20696 } 20697 if (count == 0) { 20698 pw.println(prefix + "No app verification established."); 20699 pw.println(); 20700 } 20701 for (int userId : sUserManager.getUserIds()) { 20702 pw.println("App linkages for user " + userId + ":"); 20703 pw.println(); 20704 count = 0; 20705 for (PackageSetting ps : allPackageSettings) { 20706 final long status = ps.getDomainVerificationStatusForUser(userId); 20707 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20708 && !DEBUG_DOMAIN_VERIFICATION) { 20709 continue; 20710 } 20711 pw.println(prefix + "Package: " + ps.name); 20712 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20713 String statusStr = IntentFilterVerificationInfo. 20714 getStatusStringFromValue(status); 20715 pw.println(prefix + "Status: " + statusStr); 20716 pw.println(); 20717 count++; 20718 } 20719 if (count == 0) { 20720 pw.println(prefix + "No configured app linkages."); 20721 pw.println(); 20722 } 20723 } 20724 } 20725 } 20726 } 20727 20728 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20729 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20730 if (packageName == null && permissionNames == null) { 20731 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20732 if (iperm == 0) { 20733 if (dumpState.onTitlePrinted()) 20734 pw.println(); 20735 pw.println("AppOp Permissions:"); 20736 } 20737 pw.print(" AppOp Permission "); 20738 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20739 pw.println(":"); 20740 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20741 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20742 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20743 } 20744 } 20745 } 20746 } 20747 20748 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20749 boolean printedSomething = false; 20750 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20751 if (packageName != null && !packageName.equals(p.info.packageName)) { 20752 continue; 20753 } 20754 if (!printedSomething) { 20755 if (dumpState.onTitlePrinted()) 20756 pw.println(); 20757 pw.println("Registered ContentProviders:"); 20758 printedSomething = true; 20759 } 20760 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20761 pw.print(" "); pw.println(p.toString()); 20762 } 20763 printedSomething = false; 20764 for (Map.Entry<String, PackageParser.Provider> entry : 20765 mProvidersByAuthority.entrySet()) { 20766 PackageParser.Provider p = entry.getValue(); 20767 if (packageName != null && !packageName.equals(p.info.packageName)) { 20768 continue; 20769 } 20770 if (!printedSomething) { 20771 if (dumpState.onTitlePrinted()) 20772 pw.println(); 20773 pw.println("ContentProvider Authorities:"); 20774 printedSomething = true; 20775 } 20776 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20777 pw.print(" "); pw.println(p.toString()); 20778 if (p.info != null && p.info.applicationInfo != null) { 20779 final String appInfo = p.info.applicationInfo.toString(); 20780 pw.print(" applicationInfo="); pw.println(appInfo); 20781 } 20782 } 20783 } 20784 20785 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20786 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20787 } 20788 20789 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20790 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20791 } 20792 20793 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20794 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20795 } 20796 20797 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20798 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20799 } 20800 20801 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20802 // XXX should handle packageName != null by dumping only install data that 20803 // the given package is involved with. 20804 if (dumpState.onTitlePrinted()) pw.println(); 20805 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20806 } 20807 20808 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20809 // XXX should handle packageName != null by dumping only install data that 20810 // the given package is involved with. 20811 if (dumpState.onTitlePrinted()) pw.println(); 20812 20813 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20814 ipw.println(); 20815 ipw.println("Frozen packages:"); 20816 ipw.increaseIndent(); 20817 if (mFrozenPackages.size() == 0) { 20818 ipw.println("(none)"); 20819 } else { 20820 for (int i = 0; i < mFrozenPackages.size(); i++) { 20821 ipw.println(mFrozenPackages.valueAt(i)); 20822 } 20823 } 20824 ipw.decreaseIndent(); 20825 } 20826 20827 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20828 if (dumpState.onTitlePrinted()) pw.println(); 20829 dumpDexoptStateLPr(pw, packageName); 20830 } 20831 20832 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20833 if (dumpState.onTitlePrinted()) pw.println(); 20834 dumpCompilerStatsLPr(pw, packageName); 20835 } 20836 20837 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20838 if (dumpState.onTitlePrinted()) pw.println(); 20839 mSettings.dumpReadMessagesLPr(pw, dumpState); 20840 20841 pw.println(); 20842 pw.println("Package warning messages:"); 20843 BufferedReader in = null; 20844 String line = null; 20845 try { 20846 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20847 while ((line = in.readLine()) != null) { 20848 if (line.contains("ignored: updated version")) continue; 20849 pw.println(line); 20850 } 20851 } catch (IOException ignored) { 20852 } finally { 20853 IoUtils.closeQuietly(in); 20854 } 20855 } 20856 20857 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20858 BufferedReader in = null; 20859 String line = null; 20860 try { 20861 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20862 while ((line = in.readLine()) != null) { 20863 if (line.contains("ignored: updated version")) continue; 20864 pw.print("msg,"); 20865 pw.println(line); 20866 } 20867 } catch (IOException ignored) { 20868 } finally { 20869 IoUtils.closeQuietly(in); 20870 } 20871 } 20872 } 20873 } 20874 20875 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20876 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20877 ipw.println(); 20878 ipw.println("Dexopt state:"); 20879 ipw.increaseIndent(); 20880 Collection<PackageParser.Package> packages = null; 20881 if (packageName != null) { 20882 PackageParser.Package targetPackage = mPackages.get(packageName); 20883 if (targetPackage != null) { 20884 packages = Collections.singletonList(targetPackage); 20885 } else { 20886 ipw.println("Unable to find package: " + packageName); 20887 return; 20888 } 20889 } else { 20890 packages = mPackages.values(); 20891 } 20892 20893 for (PackageParser.Package pkg : packages) { 20894 ipw.println("[" + pkg.packageName + "]"); 20895 ipw.increaseIndent(); 20896 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20897 ipw.decreaseIndent(); 20898 } 20899 } 20900 20901 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20902 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20903 ipw.println(); 20904 ipw.println("Compiler stats:"); 20905 ipw.increaseIndent(); 20906 Collection<PackageParser.Package> packages = null; 20907 if (packageName != null) { 20908 PackageParser.Package targetPackage = mPackages.get(packageName); 20909 if (targetPackage != null) { 20910 packages = Collections.singletonList(targetPackage); 20911 } else { 20912 ipw.println("Unable to find package: " + packageName); 20913 return; 20914 } 20915 } else { 20916 packages = mPackages.values(); 20917 } 20918 20919 for (PackageParser.Package pkg : packages) { 20920 ipw.println("[" + pkg.packageName + "]"); 20921 ipw.increaseIndent(); 20922 20923 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20924 if (stats == null) { 20925 ipw.println("(No recorded stats)"); 20926 } else { 20927 stats.dump(ipw); 20928 } 20929 ipw.decreaseIndent(); 20930 } 20931 } 20932 20933 private String dumpDomainString(String packageName) { 20934 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20935 .getList(); 20936 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20937 20938 ArraySet<String> result = new ArraySet<>(); 20939 if (iviList.size() > 0) { 20940 for (IntentFilterVerificationInfo ivi : iviList) { 20941 for (String host : ivi.getDomains()) { 20942 result.add(host); 20943 } 20944 } 20945 } 20946 if (filters != null && filters.size() > 0) { 20947 for (IntentFilter filter : filters) { 20948 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20949 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20950 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20951 result.addAll(filter.getHostsList()); 20952 } 20953 } 20954 } 20955 20956 StringBuilder sb = new StringBuilder(result.size() * 16); 20957 for (String domain : result) { 20958 if (sb.length() > 0) sb.append(" "); 20959 sb.append(domain); 20960 } 20961 return sb.toString(); 20962 } 20963 20964 // ------- apps on sdcard specific code ------- 20965 static final boolean DEBUG_SD_INSTALL = false; 20966 20967 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20968 20969 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20970 20971 private boolean mMediaMounted = false; 20972 20973 static String getEncryptKey() { 20974 try { 20975 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20976 SD_ENCRYPTION_KEYSTORE_NAME); 20977 if (sdEncKey == null) { 20978 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20979 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20980 if (sdEncKey == null) { 20981 Slog.e(TAG, "Failed to create encryption keys"); 20982 return null; 20983 } 20984 } 20985 return sdEncKey; 20986 } catch (NoSuchAlgorithmException nsae) { 20987 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20988 return null; 20989 } catch (IOException ioe) { 20990 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20991 return null; 20992 } 20993 } 20994 20995 /* 20996 * Update media status on PackageManager. 20997 */ 20998 @Override 20999 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21000 int callingUid = Binder.getCallingUid(); 21001 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21002 throw new SecurityException("Media status can only be updated by the system"); 21003 } 21004 // reader; this apparently protects mMediaMounted, but should probably 21005 // be a different lock in that case. 21006 synchronized (mPackages) { 21007 Log.i(TAG, "Updating external media status from " 21008 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21009 + (mediaStatus ? "mounted" : "unmounted")); 21010 if (DEBUG_SD_INSTALL) 21011 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21012 + ", mMediaMounted=" + mMediaMounted); 21013 if (mediaStatus == mMediaMounted) { 21014 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21015 : 0, -1); 21016 mHandler.sendMessage(msg); 21017 return; 21018 } 21019 mMediaMounted = mediaStatus; 21020 } 21021 // Queue up an async operation since the package installation may take a 21022 // little while. 21023 mHandler.post(new Runnable() { 21024 public void run() { 21025 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21026 } 21027 }); 21028 } 21029 21030 /** 21031 * Called by StorageManagerService when the initial ASECs to scan are available. 21032 * Should block until all the ASEC containers are finished being scanned. 21033 */ 21034 public void scanAvailableAsecs() { 21035 updateExternalMediaStatusInner(true, false, false); 21036 } 21037 21038 /* 21039 * Collect information of applications on external media, map them against 21040 * existing containers and update information based on current mount status. 21041 * Please note that we always have to report status if reportStatus has been 21042 * set to true especially when unloading packages. 21043 */ 21044 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21045 boolean externalStorage) { 21046 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21047 int[] uidArr = EmptyArray.INT; 21048 21049 final String[] list = PackageHelper.getSecureContainerList(); 21050 if (ArrayUtils.isEmpty(list)) { 21051 Log.i(TAG, "No secure containers found"); 21052 } else { 21053 // Process list of secure containers and categorize them 21054 // as active or stale based on their package internal state. 21055 21056 // reader 21057 synchronized (mPackages) { 21058 for (String cid : list) { 21059 // Leave stages untouched for now; installer service owns them 21060 if (PackageInstallerService.isStageName(cid)) continue; 21061 21062 if (DEBUG_SD_INSTALL) 21063 Log.i(TAG, "Processing container " + cid); 21064 String pkgName = getAsecPackageName(cid); 21065 if (pkgName == null) { 21066 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21067 continue; 21068 } 21069 if (DEBUG_SD_INSTALL) 21070 Log.i(TAG, "Looking for pkg : " + pkgName); 21071 21072 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21073 if (ps == null) { 21074 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21075 continue; 21076 } 21077 21078 /* 21079 * Skip packages that are not external if we're unmounting 21080 * external storage. 21081 */ 21082 if (externalStorage && !isMounted && !isExternal(ps)) { 21083 continue; 21084 } 21085 21086 final AsecInstallArgs args = new AsecInstallArgs(cid, 21087 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21088 // The package status is changed only if the code path 21089 // matches between settings and the container id. 21090 if (ps.codePathString != null 21091 && ps.codePathString.startsWith(args.getCodePath())) { 21092 if (DEBUG_SD_INSTALL) { 21093 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21094 + " at code path: " + ps.codePathString); 21095 } 21096 21097 // We do have a valid package installed on sdcard 21098 processCids.put(args, ps.codePathString); 21099 final int uid = ps.appId; 21100 if (uid != -1) { 21101 uidArr = ArrayUtils.appendInt(uidArr, uid); 21102 } 21103 } else { 21104 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21105 + ps.codePathString); 21106 } 21107 } 21108 } 21109 21110 Arrays.sort(uidArr); 21111 } 21112 21113 // Process packages with valid entries. 21114 if (isMounted) { 21115 if (DEBUG_SD_INSTALL) 21116 Log.i(TAG, "Loading packages"); 21117 loadMediaPackages(processCids, uidArr, externalStorage); 21118 startCleaningPackages(); 21119 mInstallerService.onSecureContainersAvailable(); 21120 } else { 21121 if (DEBUG_SD_INSTALL) 21122 Log.i(TAG, "Unloading packages"); 21123 unloadMediaPackages(processCids, uidArr, reportStatus); 21124 } 21125 } 21126 21127 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21128 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21129 final int size = infos.size(); 21130 final String[] packageNames = new String[size]; 21131 final int[] packageUids = new int[size]; 21132 for (int i = 0; i < size; i++) { 21133 final ApplicationInfo info = infos.get(i); 21134 packageNames[i] = info.packageName; 21135 packageUids[i] = info.uid; 21136 } 21137 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21138 finishedReceiver); 21139 } 21140 21141 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21142 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21143 sendResourcesChangedBroadcast(mediaStatus, replacing, 21144 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21145 } 21146 21147 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21148 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21149 int size = pkgList.length; 21150 if (size > 0) { 21151 // Send broadcasts here 21152 Bundle extras = new Bundle(); 21153 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21154 if (uidArr != null) { 21155 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21156 } 21157 if (replacing) { 21158 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21159 } 21160 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21161 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21162 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21163 } 21164 } 21165 21166 /* 21167 * Look at potentially valid container ids from processCids If package 21168 * information doesn't match the one on record or package scanning fails, 21169 * the cid is added to list of removeCids. We currently don't delete stale 21170 * containers. 21171 */ 21172 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21173 boolean externalStorage) { 21174 ArrayList<String> pkgList = new ArrayList<String>(); 21175 Set<AsecInstallArgs> keys = processCids.keySet(); 21176 21177 for (AsecInstallArgs args : keys) { 21178 String codePath = processCids.get(args); 21179 if (DEBUG_SD_INSTALL) 21180 Log.i(TAG, "Loading container : " + args.cid); 21181 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21182 try { 21183 // Make sure there are no container errors first. 21184 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21185 Slog.e(TAG, "Failed to mount cid : " + args.cid 21186 + " when installing from sdcard"); 21187 continue; 21188 } 21189 // Check code path here. 21190 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21191 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21192 + " does not match one in settings " + codePath); 21193 continue; 21194 } 21195 // Parse package 21196 int parseFlags = mDefParseFlags; 21197 if (args.isExternalAsec()) { 21198 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21199 } 21200 if (args.isFwdLocked()) { 21201 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21202 } 21203 21204 synchronized (mInstallLock) { 21205 PackageParser.Package pkg = null; 21206 try { 21207 // Sadly we don't know the package name yet to freeze it 21208 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21209 SCAN_IGNORE_FROZEN, 0, null); 21210 } catch (PackageManagerException e) { 21211 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21212 } 21213 // Scan the package 21214 if (pkg != null) { 21215 /* 21216 * TODO why is the lock being held? doPostInstall is 21217 * called in other places without the lock. This needs 21218 * to be straightened out. 21219 */ 21220 // writer 21221 synchronized (mPackages) { 21222 retCode = PackageManager.INSTALL_SUCCEEDED; 21223 pkgList.add(pkg.packageName); 21224 // Post process args 21225 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21226 pkg.applicationInfo.uid); 21227 } 21228 } else { 21229 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21230 } 21231 } 21232 21233 } finally { 21234 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21235 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21236 } 21237 } 21238 } 21239 // writer 21240 synchronized (mPackages) { 21241 // If the platform SDK has changed since the last time we booted, 21242 // we need to re-grant app permission to catch any new ones that 21243 // appear. This is really a hack, and means that apps can in some 21244 // cases get permissions that the user didn't initially explicitly 21245 // allow... it would be nice to have some better way to handle 21246 // this situation. 21247 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21248 : mSettings.getInternalVersion(); 21249 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21250 : StorageManager.UUID_PRIVATE_INTERNAL; 21251 21252 int updateFlags = UPDATE_PERMISSIONS_ALL; 21253 if (ver.sdkVersion != mSdkVersion) { 21254 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21255 + mSdkVersion + "; regranting permissions for external"); 21256 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21257 } 21258 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21259 21260 // Yay, everything is now upgraded 21261 ver.forceCurrent(); 21262 21263 // can downgrade to reader 21264 // Persist settings 21265 mSettings.writeLPr(); 21266 } 21267 // Send a broadcast to let everyone know we are done processing 21268 if (pkgList.size() > 0) { 21269 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21270 } 21271 } 21272 21273 /* 21274 * Utility method to unload a list of specified containers 21275 */ 21276 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21277 // Just unmount all valid containers. 21278 for (AsecInstallArgs arg : cidArgs) { 21279 synchronized (mInstallLock) { 21280 arg.doPostDeleteLI(false); 21281 } 21282 } 21283 } 21284 21285 /* 21286 * Unload packages mounted on external media. This involves deleting package 21287 * data from internal structures, sending broadcasts about disabled packages, 21288 * gc'ing to free up references, unmounting all secure containers 21289 * corresponding to packages on external media, and posting a 21290 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21291 * that we always have to post this message if status has been requested no 21292 * matter what. 21293 */ 21294 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21295 final boolean reportStatus) { 21296 if (DEBUG_SD_INSTALL) 21297 Log.i(TAG, "unloading media packages"); 21298 ArrayList<String> pkgList = new ArrayList<String>(); 21299 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21300 final Set<AsecInstallArgs> keys = processCids.keySet(); 21301 for (AsecInstallArgs args : keys) { 21302 String pkgName = args.getPackageName(); 21303 if (DEBUG_SD_INSTALL) 21304 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21305 // Delete package internally 21306 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21307 synchronized (mInstallLock) { 21308 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21309 final boolean res; 21310 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21311 "unloadMediaPackages")) { 21312 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21313 null); 21314 } 21315 if (res) { 21316 pkgList.add(pkgName); 21317 } else { 21318 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21319 failedList.add(args); 21320 } 21321 } 21322 } 21323 21324 // reader 21325 synchronized (mPackages) { 21326 // We didn't update the settings after removing each package; 21327 // write them now for all packages. 21328 mSettings.writeLPr(); 21329 } 21330 21331 // We have to absolutely send UPDATED_MEDIA_STATUS only 21332 // after confirming that all the receivers processed the ordered 21333 // broadcast when packages get disabled, force a gc to clean things up. 21334 // and unload all the containers. 21335 if (pkgList.size() > 0) { 21336 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21337 new IIntentReceiver.Stub() { 21338 public void performReceive(Intent intent, int resultCode, String data, 21339 Bundle extras, boolean ordered, boolean sticky, 21340 int sendingUser) throws RemoteException { 21341 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21342 reportStatus ? 1 : 0, 1, keys); 21343 mHandler.sendMessage(msg); 21344 } 21345 }); 21346 } else { 21347 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21348 keys); 21349 mHandler.sendMessage(msg); 21350 } 21351 } 21352 21353 private void loadPrivatePackages(final VolumeInfo vol) { 21354 mHandler.post(new Runnable() { 21355 @Override 21356 public void run() { 21357 loadPrivatePackagesInner(vol); 21358 } 21359 }); 21360 } 21361 21362 private void loadPrivatePackagesInner(VolumeInfo vol) { 21363 final String volumeUuid = vol.fsUuid; 21364 if (TextUtils.isEmpty(volumeUuid)) { 21365 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21366 return; 21367 } 21368 21369 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21370 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21371 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21372 21373 final VersionInfo ver; 21374 final List<PackageSetting> packages; 21375 synchronized (mPackages) { 21376 ver = mSettings.findOrCreateVersion(volumeUuid); 21377 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21378 } 21379 21380 for (PackageSetting ps : packages) { 21381 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21382 synchronized (mInstallLock) { 21383 final PackageParser.Package pkg; 21384 try { 21385 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21386 loaded.add(pkg.applicationInfo); 21387 21388 } catch (PackageManagerException e) { 21389 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21390 } 21391 21392 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21393 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21394 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21395 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21396 } 21397 } 21398 } 21399 21400 // Reconcile app data for all started/unlocked users 21401 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21402 final UserManager um = mContext.getSystemService(UserManager.class); 21403 UserManagerInternal umInternal = getUserManagerInternal(); 21404 for (UserInfo user : um.getUsers()) { 21405 final int flags; 21406 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21407 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21408 } else if (umInternal.isUserRunning(user.id)) { 21409 flags = StorageManager.FLAG_STORAGE_DE; 21410 } else { 21411 continue; 21412 } 21413 21414 try { 21415 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21416 synchronized (mInstallLock) { 21417 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21418 } 21419 } catch (IllegalStateException e) { 21420 // Device was probably ejected, and we'll process that event momentarily 21421 Slog.w(TAG, "Failed to prepare storage: " + e); 21422 } 21423 } 21424 21425 synchronized (mPackages) { 21426 int updateFlags = UPDATE_PERMISSIONS_ALL; 21427 if (ver.sdkVersion != mSdkVersion) { 21428 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21429 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21430 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21431 } 21432 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21433 21434 // Yay, everything is now upgraded 21435 ver.forceCurrent(); 21436 21437 mSettings.writeLPr(); 21438 } 21439 21440 for (PackageFreezer freezer : freezers) { 21441 freezer.close(); 21442 } 21443 21444 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21445 sendResourcesChangedBroadcast(true, false, loaded, null); 21446 } 21447 21448 private void unloadPrivatePackages(final VolumeInfo vol) { 21449 mHandler.post(new Runnable() { 21450 @Override 21451 public void run() { 21452 unloadPrivatePackagesInner(vol); 21453 } 21454 }); 21455 } 21456 21457 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21458 final String volumeUuid = vol.fsUuid; 21459 if (TextUtils.isEmpty(volumeUuid)) { 21460 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21461 return; 21462 } 21463 21464 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21465 synchronized (mInstallLock) { 21466 synchronized (mPackages) { 21467 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21468 for (PackageSetting ps : packages) { 21469 if (ps.pkg == null) continue; 21470 21471 final ApplicationInfo info = ps.pkg.applicationInfo; 21472 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21473 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21474 21475 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21476 "unloadPrivatePackagesInner")) { 21477 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21478 false, null)) { 21479 unloaded.add(info); 21480 } else { 21481 Slog.w(TAG, "Failed to unload " + ps.codePath); 21482 } 21483 } 21484 21485 // Try very hard to release any references to this package 21486 // so we don't risk the system server being killed due to 21487 // open FDs 21488 AttributeCache.instance().removePackage(ps.name); 21489 } 21490 21491 mSettings.writeLPr(); 21492 } 21493 } 21494 21495 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21496 sendResourcesChangedBroadcast(false, false, unloaded, null); 21497 21498 // Try very hard to release any references to this path so we don't risk 21499 // the system server being killed due to open FDs 21500 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21501 21502 for (int i = 0; i < 3; i++) { 21503 System.gc(); 21504 System.runFinalization(); 21505 } 21506 } 21507 21508 private void assertPackageKnown(String volumeUuid, String packageName) 21509 throws PackageManagerException { 21510 synchronized (mPackages) { 21511 // Normalize package name to handle renamed packages 21512 packageName = normalizePackageNameLPr(packageName); 21513 21514 final PackageSetting ps = mSettings.mPackages.get(packageName); 21515 if (ps == null) { 21516 throw new PackageManagerException("Package " + packageName + " is unknown"); 21517 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21518 throw new PackageManagerException( 21519 "Package " + packageName + " found on unknown volume " + volumeUuid 21520 + "; expected volume " + ps.volumeUuid); 21521 } 21522 } 21523 } 21524 21525 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21526 throws PackageManagerException { 21527 synchronized (mPackages) { 21528 // Normalize package name to handle renamed packages 21529 packageName = normalizePackageNameLPr(packageName); 21530 21531 final PackageSetting ps = mSettings.mPackages.get(packageName); 21532 if (ps == null) { 21533 throw new PackageManagerException("Package " + packageName + " is unknown"); 21534 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21535 throw new PackageManagerException( 21536 "Package " + packageName + " found on unknown volume " + volumeUuid 21537 + "; expected volume " + ps.volumeUuid); 21538 } else if (!ps.getInstalled(userId)) { 21539 throw new PackageManagerException( 21540 "Package " + packageName + " not installed for user " + userId); 21541 } 21542 } 21543 } 21544 21545 private List<String> collectAbsoluteCodePaths() { 21546 synchronized (mPackages) { 21547 List<String> codePaths = new ArrayList<>(); 21548 final int packageCount = mSettings.mPackages.size(); 21549 for (int i = 0; i < packageCount; i++) { 21550 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21551 codePaths.add(ps.codePath.getAbsolutePath()); 21552 } 21553 return codePaths; 21554 } 21555 } 21556 21557 /** 21558 * Examine all apps present on given mounted volume, and destroy apps that 21559 * aren't expected, either due to uninstallation or reinstallation on 21560 * another volume. 21561 */ 21562 private void reconcileApps(String volumeUuid) { 21563 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21564 List<File> filesToDelete = null; 21565 21566 final File[] files = FileUtils.listFilesOrEmpty( 21567 Environment.getDataAppDirectory(volumeUuid)); 21568 for (File file : files) { 21569 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21570 && !PackageInstallerService.isStageName(file.getName()); 21571 if (!isPackage) { 21572 // Ignore entries which are not packages 21573 continue; 21574 } 21575 21576 String absolutePath = file.getAbsolutePath(); 21577 21578 boolean pathValid = false; 21579 final int absoluteCodePathCount = absoluteCodePaths.size(); 21580 for (int i = 0; i < absoluteCodePathCount; i++) { 21581 String absoluteCodePath = absoluteCodePaths.get(i); 21582 if (absolutePath.startsWith(absoluteCodePath)) { 21583 pathValid = true; 21584 break; 21585 } 21586 } 21587 21588 if (!pathValid) { 21589 if (filesToDelete == null) { 21590 filesToDelete = new ArrayList<>(); 21591 } 21592 filesToDelete.add(file); 21593 } 21594 } 21595 21596 if (filesToDelete != null) { 21597 final int fileToDeleteCount = filesToDelete.size(); 21598 for (int i = 0; i < fileToDeleteCount; i++) { 21599 File fileToDelete = filesToDelete.get(i); 21600 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21601 synchronized (mInstallLock) { 21602 removeCodePathLI(fileToDelete); 21603 } 21604 } 21605 } 21606 } 21607 21608 /** 21609 * Reconcile all app data for the given user. 21610 * <p> 21611 * Verifies that directories exist and that ownership and labeling is 21612 * correct for all installed apps on all mounted volumes. 21613 */ 21614 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21615 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21616 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21617 final String volumeUuid = vol.getFsUuid(); 21618 synchronized (mInstallLock) { 21619 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21620 } 21621 } 21622 } 21623 21624 /** 21625 * Reconcile all app data on given mounted volume. 21626 * <p> 21627 * Destroys app data that isn't expected, either due to uninstallation or 21628 * reinstallation on another volume. 21629 * <p> 21630 * Verifies that directories exist and that ownership and labeling is 21631 * correct for all installed apps. 21632 */ 21633 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21634 boolean migrateAppData) { 21635 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21636 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21637 21638 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21639 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21640 21641 // First look for stale data that doesn't belong, and check if things 21642 // have changed since we did our last restorecon 21643 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21644 if (StorageManager.isFileEncryptedNativeOrEmulated() 21645 && !StorageManager.isUserKeyUnlocked(userId)) { 21646 throw new RuntimeException( 21647 "Yikes, someone asked us to reconcile CE storage while " + userId 21648 + " was still locked; this would have caused massive data loss!"); 21649 } 21650 21651 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21652 for (File file : files) { 21653 final String packageName = file.getName(); 21654 try { 21655 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21656 } catch (PackageManagerException e) { 21657 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21658 try { 21659 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21660 StorageManager.FLAG_STORAGE_CE, 0); 21661 } catch (InstallerException e2) { 21662 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21663 } 21664 } 21665 } 21666 } 21667 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21668 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21669 for (File file : files) { 21670 final String packageName = file.getName(); 21671 try { 21672 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21673 } catch (PackageManagerException e) { 21674 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21675 try { 21676 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21677 StorageManager.FLAG_STORAGE_DE, 0); 21678 } catch (InstallerException e2) { 21679 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21680 } 21681 } 21682 } 21683 } 21684 21685 // Ensure that data directories are ready to roll for all packages 21686 // installed for this volume and user 21687 final List<PackageSetting> packages; 21688 synchronized (mPackages) { 21689 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21690 } 21691 int preparedCount = 0; 21692 for (PackageSetting ps : packages) { 21693 final String packageName = ps.name; 21694 if (ps.pkg == null) { 21695 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21696 // TODO: might be due to legacy ASEC apps; we should circle back 21697 // and reconcile again once they're scanned 21698 continue; 21699 } 21700 21701 if (ps.getInstalled(userId)) { 21702 prepareAppDataLIF(ps.pkg, userId, flags); 21703 21704 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21705 // We may have just shuffled around app data directories, so 21706 // prepare them one more time 21707 prepareAppDataLIF(ps.pkg, userId, flags); 21708 } 21709 21710 preparedCount++; 21711 } 21712 } 21713 21714 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21715 } 21716 21717 /** 21718 * Prepare app data for the given app just after it was installed or 21719 * upgraded. This method carefully only touches users that it's installed 21720 * for, and it forces a restorecon to handle any seinfo changes. 21721 * <p> 21722 * Verifies that directories exist and that ownership and labeling is 21723 * correct for all installed apps. If there is an ownership mismatch, it 21724 * will try recovering system apps by wiping data; third-party app data is 21725 * left intact. 21726 * <p> 21727 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21728 */ 21729 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21730 final PackageSetting ps; 21731 synchronized (mPackages) { 21732 ps = mSettings.mPackages.get(pkg.packageName); 21733 mSettings.writeKernelMappingLPr(ps); 21734 } 21735 21736 final UserManager um = mContext.getSystemService(UserManager.class); 21737 UserManagerInternal umInternal = getUserManagerInternal(); 21738 for (UserInfo user : um.getUsers()) { 21739 final int flags; 21740 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21741 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21742 } else if (umInternal.isUserRunning(user.id)) { 21743 flags = StorageManager.FLAG_STORAGE_DE; 21744 } else { 21745 continue; 21746 } 21747 21748 if (ps.getInstalled(user.id)) { 21749 // TODO: when user data is locked, mark that we're still dirty 21750 prepareAppDataLIF(pkg, user.id, flags); 21751 } 21752 } 21753 } 21754 21755 /** 21756 * Prepare app data for the given app. 21757 * <p> 21758 * Verifies that directories exist and that ownership and labeling is 21759 * correct for all installed apps. If there is an ownership mismatch, this 21760 * will try recovering system apps by wiping data; third-party app data is 21761 * left intact. 21762 */ 21763 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21764 if (pkg == null) { 21765 Slog.wtf(TAG, "Package was null!", new Throwable()); 21766 return; 21767 } 21768 prepareAppDataLeafLIF(pkg, userId, flags); 21769 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21770 for (int i = 0; i < childCount; i++) { 21771 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21772 } 21773 } 21774 21775 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21776 if (DEBUG_APP_DATA) { 21777 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21778 + Integer.toHexString(flags)); 21779 } 21780 21781 final String volumeUuid = pkg.volumeUuid; 21782 final String packageName = pkg.packageName; 21783 final ApplicationInfo app = pkg.applicationInfo; 21784 final int appId = UserHandle.getAppId(app.uid); 21785 21786 Preconditions.checkNotNull(app.seInfo); 21787 21788 long ceDataInode = -1; 21789 try { 21790 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21791 appId, app.seInfo, app.targetSdkVersion); 21792 } catch (InstallerException e) { 21793 if (app.isSystemApp()) { 21794 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21795 + ", but trying to recover: " + e); 21796 destroyAppDataLeafLIF(pkg, userId, flags); 21797 try { 21798 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21799 appId, app.seInfo, app.targetSdkVersion); 21800 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21801 } catch (InstallerException e2) { 21802 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21803 } 21804 } else { 21805 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21806 } 21807 } 21808 21809 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21810 // TODO: mark this structure as dirty so we persist it! 21811 synchronized (mPackages) { 21812 final PackageSetting ps = mSettings.mPackages.get(packageName); 21813 if (ps != null) { 21814 ps.setCeDataInode(ceDataInode, userId); 21815 } 21816 } 21817 } 21818 21819 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21820 } 21821 21822 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21823 if (pkg == null) { 21824 Slog.wtf(TAG, "Package was null!", new Throwable()); 21825 return; 21826 } 21827 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21828 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21829 for (int i = 0; i < childCount; i++) { 21830 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21831 } 21832 } 21833 21834 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21835 final String volumeUuid = pkg.volumeUuid; 21836 final String packageName = pkg.packageName; 21837 final ApplicationInfo app = pkg.applicationInfo; 21838 21839 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21840 // Create a native library symlink only if we have native libraries 21841 // and if the native libraries are 32 bit libraries. We do not provide 21842 // this symlink for 64 bit libraries. 21843 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21844 final String nativeLibPath = app.nativeLibraryDir; 21845 try { 21846 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21847 nativeLibPath, userId); 21848 } catch (InstallerException e) { 21849 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21850 } 21851 } 21852 } 21853 } 21854 21855 /** 21856 * For system apps on non-FBE devices, this method migrates any existing 21857 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21858 * requested by the app. 21859 */ 21860 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21861 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21862 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21863 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21864 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21865 try { 21866 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21867 storageTarget); 21868 } catch (InstallerException e) { 21869 logCriticalInfo(Log.WARN, 21870 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21871 } 21872 return true; 21873 } else { 21874 return false; 21875 } 21876 } 21877 21878 public PackageFreezer freezePackage(String packageName, String killReason) { 21879 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21880 } 21881 21882 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21883 return new PackageFreezer(packageName, userId, killReason); 21884 } 21885 21886 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21887 String killReason) { 21888 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21889 } 21890 21891 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21892 String killReason) { 21893 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21894 return new PackageFreezer(); 21895 } else { 21896 return freezePackage(packageName, userId, killReason); 21897 } 21898 } 21899 21900 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21901 String killReason) { 21902 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21903 } 21904 21905 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21906 String killReason) { 21907 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21908 return new PackageFreezer(); 21909 } else { 21910 return freezePackage(packageName, userId, killReason); 21911 } 21912 } 21913 21914 /** 21915 * Class that freezes and kills the given package upon creation, and 21916 * unfreezes it upon closing. This is typically used when doing surgery on 21917 * app code/data to prevent the app from running while you're working. 21918 */ 21919 private class PackageFreezer implements AutoCloseable { 21920 private final String mPackageName; 21921 private final PackageFreezer[] mChildren; 21922 21923 private final boolean mWeFroze; 21924 21925 private final AtomicBoolean mClosed = new AtomicBoolean(); 21926 private final CloseGuard mCloseGuard = CloseGuard.get(); 21927 21928 /** 21929 * Create and return a stub freezer that doesn't actually do anything, 21930 * typically used when someone requested 21931 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21932 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21933 */ 21934 public PackageFreezer() { 21935 mPackageName = null; 21936 mChildren = null; 21937 mWeFroze = false; 21938 mCloseGuard.open("close"); 21939 } 21940 21941 public PackageFreezer(String packageName, int userId, String killReason) { 21942 synchronized (mPackages) { 21943 mPackageName = packageName; 21944 mWeFroze = mFrozenPackages.add(mPackageName); 21945 21946 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21947 if (ps != null) { 21948 killApplication(ps.name, ps.appId, userId, killReason); 21949 } 21950 21951 final PackageParser.Package p = mPackages.get(packageName); 21952 if (p != null && p.childPackages != null) { 21953 final int N = p.childPackages.size(); 21954 mChildren = new PackageFreezer[N]; 21955 for (int i = 0; i < N; i++) { 21956 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21957 userId, killReason); 21958 } 21959 } else { 21960 mChildren = null; 21961 } 21962 } 21963 mCloseGuard.open("close"); 21964 } 21965 21966 @Override 21967 protected void finalize() throws Throwable { 21968 try { 21969 mCloseGuard.warnIfOpen(); 21970 close(); 21971 } finally { 21972 super.finalize(); 21973 } 21974 } 21975 21976 @Override 21977 public void close() { 21978 mCloseGuard.close(); 21979 if (mClosed.compareAndSet(false, true)) { 21980 synchronized (mPackages) { 21981 if (mWeFroze) { 21982 mFrozenPackages.remove(mPackageName); 21983 } 21984 21985 if (mChildren != null) { 21986 for (PackageFreezer freezer : mChildren) { 21987 freezer.close(); 21988 } 21989 } 21990 } 21991 } 21992 } 21993 } 21994 21995 /** 21996 * Verify that given package is currently frozen. 21997 */ 21998 private void checkPackageFrozen(String packageName) { 21999 synchronized (mPackages) { 22000 if (!mFrozenPackages.contains(packageName)) { 22001 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22002 } 22003 } 22004 } 22005 22006 @Override 22007 public int movePackage(final String packageName, final String volumeUuid) { 22008 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22009 22010 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22011 final int moveId = mNextMoveId.getAndIncrement(); 22012 mHandler.post(new Runnable() { 22013 @Override 22014 public void run() { 22015 try { 22016 movePackageInternal(packageName, volumeUuid, moveId, user); 22017 } catch (PackageManagerException e) { 22018 Slog.w(TAG, "Failed to move " + packageName, e); 22019 mMoveCallbacks.notifyStatusChanged(moveId, 22020 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22021 } 22022 } 22023 }); 22024 return moveId; 22025 } 22026 22027 private void movePackageInternal(final String packageName, final String volumeUuid, 22028 final int moveId, UserHandle user) throws PackageManagerException { 22029 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22030 final PackageManager pm = mContext.getPackageManager(); 22031 22032 final boolean currentAsec; 22033 final String currentVolumeUuid; 22034 final File codeFile; 22035 final String installerPackageName; 22036 final String packageAbiOverride; 22037 final int appId; 22038 final String seinfo; 22039 final String label; 22040 final int targetSdkVersion; 22041 final PackageFreezer freezer; 22042 final int[] installedUserIds; 22043 22044 // reader 22045 synchronized (mPackages) { 22046 final PackageParser.Package pkg = mPackages.get(packageName); 22047 final PackageSetting ps = mSettings.mPackages.get(packageName); 22048 if (pkg == null || ps == null) { 22049 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22050 } 22051 22052 if (pkg.applicationInfo.isSystemApp()) { 22053 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22054 "Cannot move system application"); 22055 } 22056 22057 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22058 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22059 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22060 if (isInternalStorage && !allow3rdPartyOnInternal) { 22061 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22062 "3rd party apps are not allowed on internal storage"); 22063 } 22064 22065 if (pkg.applicationInfo.isExternalAsec()) { 22066 currentAsec = true; 22067 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22068 } else if (pkg.applicationInfo.isForwardLocked()) { 22069 currentAsec = true; 22070 currentVolumeUuid = "forward_locked"; 22071 } else { 22072 currentAsec = false; 22073 currentVolumeUuid = ps.volumeUuid; 22074 22075 final File probe = new File(pkg.codePath); 22076 final File probeOat = new File(probe, "oat"); 22077 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22078 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22079 "Move only supported for modern cluster style installs"); 22080 } 22081 } 22082 22083 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22084 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22085 "Package already moved to " + volumeUuid); 22086 } 22087 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22088 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22089 "Device admin cannot be moved"); 22090 } 22091 22092 if (mFrozenPackages.contains(packageName)) { 22093 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22094 "Failed to move already frozen package"); 22095 } 22096 22097 codeFile = new File(pkg.codePath); 22098 installerPackageName = ps.installerPackageName; 22099 packageAbiOverride = ps.cpuAbiOverrideString; 22100 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22101 seinfo = pkg.applicationInfo.seInfo; 22102 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22103 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22104 freezer = freezePackage(packageName, "movePackageInternal"); 22105 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22106 } 22107 22108 final Bundle extras = new Bundle(); 22109 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22110 extras.putString(Intent.EXTRA_TITLE, label); 22111 mMoveCallbacks.notifyCreated(moveId, extras); 22112 22113 int installFlags; 22114 final boolean moveCompleteApp; 22115 final File measurePath; 22116 22117 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22118 installFlags = INSTALL_INTERNAL; 22119 moveCompleteApp = !currentAsec; 22120 measurePath = Environment.getDataAppDirectory(volumeUuid); 22121 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22122 installFlags = INSTALL_EXTERNAL; 22123 moveCompleteApp = false; 22124 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22125 } else { 22126 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22127 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22128 || !volume.isMountedWritable()) { 22129 freezer.close(); 22130 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22131 "Move location not mounted private volume"); 22132 } 22133 22134 Preconditions.checkState(!currentAsec); 22135 22136 installFlags = INSTALL_INTERNAL; 22137 moveCompleteApp = true; 22138 measurePath = Environment.getDataAppDirectory(volumeUuid); 22139 } 22140 22141 final PackageStats stats = new PackageStats(null, -1); 22142 synchronized (mInstaller) { 22143 for (int userId : installedUserIds) { 22144 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22145 freezer.close(); 22146 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22147 "Failed to measure package size"); 22148 } 22149 } 22150 } 22151 22152 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22153 + stats.dataSize); 22154 22155 final long startFreeBytes = measurePath.getFreeSpace(); 22156 final long sizeBytes; 22157 if (moveCompleteApp) { 22158 sizeBytes = stats.codeSize + stats.dataSize; 22159 } else { 22160 sizeBytes = stats.codeSize; 22161 } 22162 22163 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22164 freezer.close(); 22165 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22166 "Not enough free space to move"); 22167 } 22168 22169 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22170 22171 final CountDownLatch installedLatch = new CountDownLatch(1); 22172 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22173 @Override 22174 public void onUserActionRequired(Intent intent) throws RemoteException { 22175 throw new IllegalStateException(); 22176 } 22177 22178 @Override 22179 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22180 Bundle extras) throws RemoteException { 22181 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22182 + PackageManager.installStatusToString(returnCode, msg)); 22183 22184 installedLatch.countDown(); 22185 freezer.close(); 22186 22187 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22188 switch (status) { 22189 case PackageInstaller.STATUS_SUCCESS: 22190 mMoveCallbacks.notifyStatusChanged(moveId, 22191 PackageManager.MOVE_SUCCEEDED); 22192 break; 22193 case PackageInstaller.STATUS_FAILURE_STORAGE: 22194 mMoveCallbacks.notifyStatusChanged(moveId, 22195 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22196 break; 22197 default: 22198 mMoveCallbacks.notifyStatusChanged(moveId, 22199 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22200 break; 22201 } 22202 } 22203 }; 22204 22205 final MoveInfo move; 22206 if (moveCompleteApp) { 22207 // Kick off a thread to report progress estimates 22208 new Thread() { 22209 @Override 22210 public void run() { 22211 while (true) { 22212 try { 22213 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22214 break; 22215 } 22216 } catch (InterruptedException ignored) { 22217 } 22218 22219 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22220 final int progress = 10 + (int) MathUtils.constrain( 22221 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22222 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22223 } 22224 } 22225 }.start(); 22226 22227 final String dataAppName = codeFile.getName(); 22228 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22229 dataAppName, appId, seinfo, targetSdkVersion); 22230 } else { 22231 move = null; 22232 } 22233 22234 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22235 22236 final Message msg = mHandler.obtainMessage(INIT_COPY); 22237 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22238 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22239 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22240 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22241 PackageManager.INSTALL_REASON_UNKNOWN); 22242 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22243 msg.obj = params; 22244 22245 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22246 System.identityHashCode(msg.obj)); 22247 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22248 System.identityHashCode(msg.obj)); 22249 22250 mHandler.sendMessage(msg); 22251 } 22252 22253 @Override 22254 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22255 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22256 22257 final int realMoveId = mNextMoveId.getAndIncrement(); 22258 final Bundle extras = new Bundle(); 22259 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22260 mMoveCallbacks.notifyCreated(realMoveId, extras); 22261 22262 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22263 @Override 22264 public void onCreated(int moveId, Bundle extras) { 22265 // Ignored 22266 } 22267 22268 @Override 22269 public void onStatusChanged(int moveId, int status, long estMillis) { 22270 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22271 } 22272 }; 22273 22274 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22275 storage.setPrimaryStorageUuid(volumeUuid, callback); 22276 return realMoveId; 22277 } 22278 22279 @Override 22280 public int getMoveStatus(int moveId) { 22281 mContext.enforceCallingOrSelfPermission( 22282 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22283 return mMoveCallbacks.mLastStatus.get(moveId); 22284 } 22285 22286 @Override 22287 public void registerMoveCallback(IPackageMoveObserver callback) { 22288 mContext.enforceCallingOrSelfPermission( 22289 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22290 mMoveCallbacks.register(callback); 22291 } 22292 22293 @Override 22294 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22295 mContext.enforceCallingOrSelfPermission( 22296 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22297 mMoveCallbacks.unregister(callback); 22298 } 22299 22300 @Override 22301 public boolean setInstallLocation(int loc) { 22302 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22303 null); 22304 if (getInstallLocation() == loc) { 22305 return true; 22306 } 22307 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22308 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22309 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22310 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22311 return true; 22312 } 22313 return false; 22314 } 22315 22316 @Override 22317 public int getInstallLocation() { 22318 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22319 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22320 PackageHelper.APP_INSTALL_AUTO); 22321 } 22322 22323 /** Called by UserManagerService */ 22324 void cleanUpUser(UserManagerService userManager, int userHandle) { 22325 synchronized (mPackages) { 22326 mDirtyUsers.remove(userHandle); 22327 mUserNeedsBadging.delete(userHandle); 22328 mSettings.removeUserLPw(userHandle); 22329 mPendingBroadcasts.remove(userHandle); 22330 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22331 removeUnusedPackagesLPw(userManager, userHandle); 22332 } 22333 } 22334 22335 /** 22336 * We're removing userHandle and would like to remove any downloaded packages 22337 * that are no longer in use by any other user. 22338 * @param userHandle the user being removed 22339 */ 22340 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22341 final boolean DEBUG_CLEAN_APKS = false; 22342 int [] users = userManager.getUserIds(); 22343 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22344 while (psit.hasNext()) { 22345 PackageSetting ps = psit.next(); 22346 if (ps.pkg == null) { 22347 continue; 22348 } 22349 final String packageName = ps.pkg.packageName; 22350 // Skip over if system app 22351 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22352 continue; 22353 } 22354 if (DEBUG_CLEAN_APKS) { 22355 Slog.i(TAG, "Checking package " + packageName); 22356 } 22357 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22358 if (keep) { 22359 if (DEBUG_CLEAN_APKS) { 22360 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22361 } 22362 } else { 22363 for (int i = 0; i < users.length; i++) { 22364 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22365 keep = true; 22366 if (DEBUG_CLEAN_APKS) { 22367 Slog.i(TAG, " Keeping package " + packageName + " for user " 22368 + users[i]); 22369 } 22370 break; 22371 } 22372 } 22373 } 22374 if (!keep) { 22375 if (DEBUG_CLEAN_APKS) { 22376 Slog.i(TAG, " Removing package " + packageName); 22377 } 22378 mHandler.post(new Runnable() { 22379 public void run() { 22380 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22381 userHandle, 0); 22382 } //end run 22383 }); 22384 } 22385 } 22386 } 22387 22388 /** Called by UserManagerService */ 22389 void createNewUser(int userId, String[] disallowedPackages) { 22390 synchronized (mInstallLock) { 22391 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22392 } 22393 synchronized (mPackages) { 22394 scheduleWritePackageRestrictionsLocked(userId); 22395 scheduleWritePackageListLocked(userId); 22396 applyFactoryDefaultBrowserLPw(userId); 22397 primeDomainVerificationsLPw(userId); 22398 } 22399 } 22400 22401 void onNewUserCreated(final int userId) { 22402 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22403 // If permission review for legacy apps is required, we represent 22404 // dagerous permissions for such apps as always granted runtime 22405 // permissions to keep per user flag state whether review is needed. 22406 // Hence, if a new user is added we have to propagate dangerous 22407 // permission grants for these legacy apps. 22408 if (mPermissionReviewRequired) { 22409 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22410 | UPDATE_PERMISSIONS_REPLACE_ALL); 22411 } 22412 } 22413 22414 @Override 22415 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22416 mContext.enforceCallingOrSelfPermission( 22417 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22418 "Only package verification agents can read the verifier device identity"); 22419 22420 synchronized (mPackages) { 22421 return mSettings.getVerifierDeviceIdentityLPw(); 22422 } 22423 } 22424 22425 @Override 22426 public void setPermissionEnforced(String permission, boolean enforced) { 22427 // TODO: Now that we no longer change GID for storage, this should to away. 22428 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22429 "setPermissionEnforced"); 22430 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22431 synchronized (mPackages) { 22432 if (mSettings.mReadExternalStorageEnforced == null 22433 || mSettings.mReadExternalStorageEnforced != enforced) { 22434 mSettings.mReadExternalStorageEnforced = enforced; 22435 mSettings.writeLPr(); 22436 } 22437 } 22438 // kill any non-foreground processes so we restart them and 22439 // grant/revoke the GID. 22440 final IActivityManager am = ActivityManager.getService(); 22441 if (am != null) { 22442 final long token = Binder.clearCallingIdentity(); 22443 try { 22444 am.killProcessesBelowForeground("setPermissionEnforcement"); 22445 } catch (RemoteException e) { 22446 } finally { 22447 Binder.restoreCallingIdentity(token); 22448 } 22449 } 22450 } else { 22451 throw new IllegalArgumentException("No selective enforcement for " + permission); 22452 } 22453 } 22454 22455 @Override 22456 @Deprecated 22457 public boolean isPermissionEnforced(String permission) { 22458 return true; 22459 } 22460 22461 @Override 22462 public boolean isStorageLow() { 22463 final long token = Binder.clearCallingIdentity(); 22464 try { 22465 final DeviceStorageMonitorInternal 22466 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22467 if (dsm != null) { 22468 return dsm.isMemoryLow(); 22469 } else { 22470 return false; 22471 } 22472 } finally { 22473 Binder.restoreCallingIdentity(token); 22474 } 22475 } 22476 22477 @Override 22478 public IPackageInstaller getPackageInstaller() { 22479 return mInstallerService; 22480 } 22481 22482 private boolean userNeedsBadging(int userId) { 22483 int index = mUserNeedsBadging.indexOfKey(userId); 22484 if (index < 0) { 22485 final UserInfo userInfo; 22486 final long token = Binder.clearCallingIdentity(); 22487 try { 22488 userInfo = sUserManager.getUserInfo(userId); 22489 } finally { 22490 Binder.restoreCallingIdentity(token); 22491 } 22492 final boolean b; 22493 if (userInfo != null && userInfo.isManagedProfile()) { 22494 b = true; 22495 } else { 22496 b = false; 22497 } 22498 mUserNeedsBadging.put(userId, b); 22499 return b; 22500 } 22501 return mUserNeedsBadging.valueAt(index); 22502 } 22503 22504 @Override 22505 public KeySet getKeySetByAlias(String packageName, String alias) { 22506 if (packageName == null || alias == null) { 22507 return null; 22508 } 22509 synchronized(mPackages) { 22510 final PackageParser.Package pkg = mPackages.get(packageName); 22511 if (pkg == null) { 22512 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22513 throw new IllegalArgumentException("Unknown package: " + packageName); 22514 } 22515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22516 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22517 } 22518 } 22519 22520 @Override 22521 public KeySet getSigningKeySet(String packageName) { 22522 if (packageName == null) { 22523 return null; 22524 } 22525 synchronized(mPackages) { 22526 final PackageParser.Package pkg = mPackages.get(packageName); 22527 if (pkg == null) { 22528 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22529 throw new IllegalArgumentException("Unknown package: " + packageName); 22530 } 22531 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22532 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22533 throw new SecurityException("May not access signing KeySet of other apps."); 22534 } 22535 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22536 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22537 } 22538 } 22539 22540 @Override 22541 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22542 if (packageName == null || ks == null) { 22543 return false; 22544 } 22545 synchronized(mPackages) { 22546 final PackageParser.Package pkg = mPackages.get(packageName); 22547 if (pkg == null) { 22548 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22549 throw new IllegalArgumentException("Unknown package: " + packageName); 22550 } 22551 IBinder ksh = ks.getToken(); 22552 if (ksh instanceof KeySetHandle) { 22553 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22554 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22555 } 22556 return false; 22557 } 22558 } 22559 22560 @Override 22561 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22562 if (packageName == null || ks == null) { 22563 return false; 22564 } 22565 synchronized(mPackages) { 22566 final PackageParser.Package pkg = mPackages.get(packageName); 22567 if (pkg == null) { 22568 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22569 throw new IllegalArgumentException("Unknown package: " + packageName); 22570 } 22571 IBinder ksh = ks.getToken(); 22572 if (ksh instanceof KeySetHandle) { 22573 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22574 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22575 } 22576 return false; 22577 } 22578 } 22579 22580 private void deletePackageIfUnusedLPr(final String packageName) { 22581 PackageSetting ps = mSettings.mPackages.get(packageName); 22582 if (ps == null) { 22583 return; 22584 } 22585 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22586 // TODO Implement atomic delete if package is unused 22587 // It is currently possible that the package will be deleted even if it is installed 22588 // after this method returns. 22589 mHandler.post(new Runnable() { 22590 public void run() { 22591 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22592 0, PackageManager.DELETE_ALL_USERS); 22593 } 22594 }); 22595 } 22596 } 22597 22598 /** 22599 * Check and throw if the given before/after packages would be considered a 22600 * downgrade. 22601 */ 22602 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22603 throws PackageManagerException { 22604 if (after.versionCode < before.mVersionCode) { 22605 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22606 "Update version code " + after.versionCode + " is older than current " 22607 + before.mVersionCode); 22608 } else if (after.versionCode == before.mVersionCode) { 22609 if (after.baseRevisionCode < before.baseRevisionCode) { 22610 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22611 "Update base revision code " + after.baseRevisionCode 22612 + " is older than current " + before.baseRevisionCode); 22613 } 22614 22615 if (!ArrayUtils.isEmpty(after.splitNames)) { 22616 for (int i = 0; i < after.splitNames.length; i++) { 22617 final String splitName = after.splitNames[i]; 22618 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22619 if (j != -1) { 22620 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22621 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22622 "Update split " + splitName + " revision code " 22623 + after.splitRevisionCodes[i] + " is older than current " 22624 + before.splitRevisionCodes[j]); 22625 } 22626 } 22627 } 22628 } 22629 } 22630 } 22631 22632 private static class MoveCallbacks extends Handler { 22633 private static final int MSG_CREATED = 1; 22634 private static final int MSG_STATUS_CHANGED = 2; 22635 22636 private final RemoteCallbackList<IPackageMoveObserver> 22637 mCallbacks = new RemoteCallbackList<>(); 22638 22639 private final SparseIntArray mLastStatus = new SparseIntArray(); 22640 22641 public MoveCallbacks(Looper looper) { 22642 super(looper); 22643 } 22644 22645 public void register(IPackageMoveObserver callback) { 22646 mCallbacks.register(callback); 22647 } 22648 22649 public void unregister(IPackageMoveObserver callback) { 22650 mCallbacks.unregister(callback); 22651 } 22652 22653 @Override 22654 public void handleMessage(Message msg) { 22655 final SomeArgs args = (SomeArgs) msg.obj; 22656 final int n = mCallbacks.beginBroadcast(); 22657 for (int i = 0; i < n; i++) { 22658 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22659 try { 22660 invokeCallback(callback, msg.what, args); 22661 } catch (RemoteException ignored) { 22662 } 22663 } 22664 mCallbacks.finishBroadcast(); 22665 args.recycle(); 22666 } 22667 22668 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22669 throws RemoteException { 22670 switch (what) { 22671 case MSG_CREATED: { 22672 callback.onCreated(args.argi1, (Bundle) args.arg2); 22673 break; 22674 } 22675 case MSG_STATUS_CHANGED: { 22676 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22677 break; 22678 } 22679 } 22680 } 22681 22682 private void notifyCreated(int moveId, Bundle extras) { 22683 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22684 22685 final SomeArgs args = SomeArgs.obtain(); 22686 args.argi1 = moveId; 22687 args.arg2 = extras; 22688 obtainMessage(MSG_CREATED, args).sendToTarget(); 22689 } 22690 22691 private void notifyStatusChanged(int moveId, int status) { 22692 notifyStatusChanged(moveId, status, -1); 22693 } 22694 22695 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22696 Slog.v(TAG, "Move " + moveId + " status " + status); 22697 22698 final SomeArgs args = SomeArgs.obtain(); 22699 args.argi1 = moveId; 22700 args.argi2 = status; 22701 args.arg3 = estMillis; 22702 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22703 22704 synchronized (mLastStatus) { 22705 mLastStatus.put(moveId, status); 22706 } 22707 } 22708 } 22709 22710 private final static class OnPermissionChangeListeners extends Handler { 22711 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22712 22713 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22714 new RemoteCallbackList<>(); 22715 22716 public OnPermissionChangeListeners(Looper looper) { 22717 super(looper); 22718 } 22719 22720 @Override 22721 public void handleMessage(Message msg) { 22722 switch (msg.what) { 22723 case MSG_ON_PERMISSIONS_CHANGED: { 22724 final int uid = msg.arg1; 22725 handleOnPermissionsChanged(uid); 22726 } break; 22727 } 22728 } 22729 22730 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22731 mPermissionListeners.register(listener); 22732 22733 } 22734 22735 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22736 mPermissionListeners.unregister(listener); 22737 } 22738 22739 public void onPermissionsChanged(int uid) { 22740 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22741 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22742 } 22743 } 22744 22745 private void handleOnPermissionsChanged(int uid) { 22746 final int count = mPermissionListeners.beginBroadcast(); 22747 try { 22748 for (int i = 0; i < count; i++) { 22749 IOnPermissionsChangeListener callback = mPermissionListeners 22750 .getBroadcastItem(i); 22751 try { 22752 callback.onPermissionsChanged(uid); 22753 } catch (RemoteException e) { 22754 Log.e(TAG, "Permission listener is dead", e); 22755 } 22756 } 22757 } finally { 22758 mPermissionListeners.finishBroadcast(); 22759 } 22760 } 22761 } 22762 22763 private class PackageManagerInternalImpl extends PackageManagerInternal { 22764 @Override 22765 public void setLocationPackagesProvider(PackagesProvider provider) { 22766 synchronized (mPackages) { 22767 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22768 } 22769 } 22770 22771 @Override 22772 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22773 synchronized (mPackages) { 22774 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22775 } 22776 } 22777 22778 @Override 22779 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22780 synchronized (mPackages) { 22781 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22782 } 22783 } 22784 22785 @Override 22786 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22787 synchronized (mPackages) { 22788 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22789 } 22790 } 22791 22792 @Override 22793 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22794 synchronized (mPackages) { 22795 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22796 } 22797 } 22798 22799 @Override 22800 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22801 synchronized (mPackages) { 22802 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22803 } 22804 } 22805 22806 @Override 22807 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22808 synchronized (mPackages) { 22809 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22810 packageName, userId); 22811 } 22812 } 22813 22814 @Override 22815 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22816 synchronized (mPackages) { 22817 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22818 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22819 packageName, userId); 22820 } 22821 } 22822 22823 @Override 22824 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22825 synchronized (mPackages) { 22826 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22827 packageName, userId); 22828 } 22829 } 22830 22831 @Override 22832 public void setKeepUninstalledPackages(final List<String> packageList) { 22833 Preconditions.checkNotNull(packageList); 22834 List<String> removedFromList = null; 22835 synchronized (mPackages) { 22836 if (mKeepUninstalledPackages != null) { 22837 final int packagesCount = mKeepUninstalledPackages.size(); 22838 for (int i = 0; i < packagesCount; i++) { 22839 String oldPackage = mKeepUninstalledPackages.get(i); 22840 if (packageList != null && packageList.contains(oldPackage)) { 22841 continue; 22842 } 22843 if (removedFromList == null) { 22844 removedFromList = new ArrayList<>(); 22845 } 22846 removedFromList.add(oldPackage); 22847 } 22848 } 22849 mKeepUninstalledPackages = new ArrayList<>(packageList); 22850 if (removedFromList != null) { 22851 final int removedCount = removedFromList.size(); 22852 for (int i = 0; i < removedCount; i++) { 22853 deletePackageIfUnusedLPr(removedFromList.get(i)); 22854 } 22855 } 22856 } 22857 } 22858 22859 @Override 22860 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22861 synchronized (mPackages) { 22862 // If we do not support permission review, done. 22863 if (!mPermissionReviewRequired) { 22864 return false; 22865 } 22866 22867 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22868 if (packageSetting == null) { 22869 return false; 22870 } 22871 22872 // Permission review applies only to apps not supporting the new permission model. 22873 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22874 return false; 22875 } 22876 22877 // Legacy apps have the permission and get user consent on launch. 22878 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22879 return permissionsState.isPermissionReviewRequired(userId); 22880 } 22881 } 22882 22883 @Override 22884 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22885 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22886 } 22887 22888 @Override 22889 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22890 int userId) { 22891 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22892 } 22893 22894 @Override 22895 public void setDeviceAndProfileOwnerPackages( 22896 int deviceOwnerUserId, String deviceOwnerPackage, 22897 SparseArray<String> profileOwnerPackages) { 22898 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22899 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22900 } 22901 22902 @Override 22903 public boolean isPackageDataProtected(int userId, String packageName) { 22904 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22905 } 22906 22907 @Override 22908 public boolean isPackageEphemeral(int userId, String packageName) { 22909 synchronized (mPackages) { 22910 final PackageSetting ps = mSettings.mPackages.get(packageName); 22911 return ps != null ? ps.getInstantApp(userId) : false; 22912 } 22913 } 22914 22915 @Override 22916 public boolean wasPackageEverLaunched(String packageName, int userId) { 22917 synchronized (mPackages) { 22918 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22919 } 22920 } 22921 22922 @Override 22923 public void grantRuntimePermission(String packageName, String name, int userId, 22924 boolean overridePolicy) { 22925 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22926 overridePolicy); 22927 } 22928 22929 @Override 22930 public void revokeRuntimePermission(String packageName, String name, int userId, 22931 boolean overridePolicy) { 22932 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22933 overridePolicy); 22934 } 22935 22936 @Override 22937 public String getNameForUid(int uid) { 22938 return PackageManagerService.this.getNameForUid(uid); 22939 } 22940 22941 @Override 22942 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22943 Intent origIntent, String resolvedType, String callingPackage, int userId) { 22944 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22945 responseObj, origIntent, resolvedType, callingPackage, userId); 22946 } 22947 22948 @Override 22949 public void grantEphemeralAccess(int userId, Intent intent, 22950 int targetAppId, int ephemeralAppId) { 22951 synchronized (mPackages) { 22952 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22953 targetAppId, ephemeralAppId); 22954 } 22955 } 22956 22957 @Override 22958 public void pruneInstantApps() { 22959 synchronized (mPackages) { 22960 mInstantAppRegistry.pruneInstantAppsLPw(); 22961 } 22962 } 22963 22964 @Override 22965 public String getSetupWizardPackageName() { 22966 return mSetupWizardPackage; 22967 } 22968 22969 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22970 if (policy != null) { 22971 mExternalSourcesPolicy = policy; 22972 } 22973 } 22974 22975 @Override 22976 public boolean isPackagePersistent(String packageName) { 22977 synchronized (mPackages) { 22978 PackageParser.Package pkg = mPackages.get(packageName); 22979 return pkg != null 22980 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22981 | ApplicationInfo.FLAG_PERSISTENT)) == 22982 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22983 : false; 22984 } 22985 } 22986 22987 @Override 22988 public List<PackageInfo> getOverlayPackages(int userId) { 22989 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22990 synchronized (mPackages) { 22991 for (PackageParser.Package p : mPackages.values()) { 22992 if (p.mOverlayTarget != null) { 22993 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22994 if (pkg != null) { 22995 overlayPackages.add(pkg); 22996 } 22997 } 22998 } 22999 } 23000 return overlayPackages; 23001 } 23002 23003 @Override 23004 public List<String> getTargetPackageNames(int userId) { 23005 List<String> targetPackages = new ArrayList<>(); 23006 synchronized (mPackages) { 23007 for (PackageParser.Package p : mPackages.values()) { 23008 if (p.mOverlayTarget == null) { 23009 targetPackages.add(p.packageName); 23010 } 23011 } 23012 } 23013 return targetPackages; 23014 } 23015 23016 23017 @Override 23018 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 23019 List<String> overlayPackageNames) { 23020 // TODO: implement when we integrate OMS properly 23021 return false; 23022 } 23023 } 23024 23025 @Override 23026 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23027 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23028 synchronized (mPackages) { 23029 final long identity = Binder.clearCallingIdentity(); 23030 try { 23031 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23032 packageNames, userId); 23033 } finally { 23034 Binder.restoreCallingIdentity(identity); 23035 } 23036 } 23037 } 23038 23039 @Override 23040 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23041 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23042 synchronized (mPackages) { 23043 final long identity = Binder.clearCallingIdentity(); 23044 try { 23045 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23046 packageNames, userId); 23047 } finally { 23048 Binder.restoreCallingIdentity(identity); 23049 } 23050 } 23051 } 23052 23053 private static void enforceSystemOrPhoneCaller(String tag) { 23054 int callingUid = Binder.getCallingUid(); 23055 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23056 throw new SecurityException( 23057 "Cannot call " + tag + " from UID " + callingUid); 23058 } 23059 } 23060 23061 boolean isHistoricalPackageUsageAvailable() { 23062 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23063 } 23064 23065 /** 23066 * Return a <b>copy</b> of the collection of packages known to the package manager. 23067 * @return A copy of the values of mPackages. 23068 */ 23069 Collection<PackageParser.Package> getPackages() { 23070 synchronized (mPackages) { 23071 return new ArrayList<>(mPackages.values()); 23072 } 23073 } 23074 23075 /** 23076 * Logs process start information (including base APK hash) to the security log. 23077 * @hide 23078 */ 23079 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23080 String apkFile, int pid) { 23081 if (!SecurityLog.isLoggingEnabled()) { 23082 return; 23083 } 23084 Bundle data = new Bundle(); 23085 data.putLong("startTimestamp", System.currentTimeMillis()); 23086 data.putString("processName", processName); 23087 data.putInt("uid", uid); 23088 data.putString("seinfo", seinfo); 23089 data.putString("apkFile", apkFile); 23090 data.putInt("pid", pid); 23091 Message msg = mProcessLoggingHandler.obtainMessage( 23092 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23093 msg.setData(data); 23094 mProcessLoggingHandler.sendMessage(msg); 23095 } 23096 23097 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23098 return mCompilerStats.getPackageStats(pkgName); 23099 } 23100 23101 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23102 return getOrCreateCompilerPackageStats(pkg.packageName); 23103 } 23104 23105 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23106 return mCompilerStats.getOrCreatePackageStats(pkgName); 23107 } 23108 23109 public void deleteCompilerPackageStats(String pkgName) { 23110 mCompilerStats.deletePackageStats(pkgName); 23111 } 23112 23113 @Override 23114 public int getInstallReason(String packageName, int userId) { 23115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23116 true /* requireFullPermission */, false /* checkShell */, 23117 "get install reason"); 23118 synchronized (mPackages) { 23119 final PackageSetting ps = mSettings.mPackages.get(packageName); 23120 if (ps != null) { 23121 return ps.getInstallReason(userId); 23122 } 23123 } 23124 return PackageManager.INSTALL_REASON_UNKNOWN; 23125 } 23126 23127 @Override 23128 public boolean canRequestPackageInstalls(String packageName, int userId) { 23129 int callingUid = Binder.getCallingUid(); 23130 int uid = getPackageUid(packageName, 0, userId); 23131 if (callingUid != uid && callingUid != Process.ROOT_UID 23132 && callingUid != Process.SYSTEM_UID) { 23133 throw new SecurityException( 23134 "Caller uid " + callingUid + " does not own package " + packageName); 23135 } 23136 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23137 if (info == null) { 23138 return false; 23139 } 23140 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23141 throw new UnsupportedOperationException( 23142 "Operation only supported on apps targeting Android O or higher"); 23143 } 23144 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23145 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23146 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23147 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23148 } 23149 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23150 return false; 23151 } 23152 if (mExternalSourcesPolicy != null) { 23153 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23154 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23155 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23156 } 23157 } 23158 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23159 } 23160} 23161