PackageManagerService.java revision 14c716c911dea7eeb28a0040d7807d6ea83464a9
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.SET_HARMFUL_APP_WARNINGS; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 26import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 115 116import android.Manifest; 117import android.annotation.IntDef; 118import android.annotation.NonNull; 119import android.annotation.Nullable; 120import android.app.ActivityManager; 121import android.app.ActivityManagerInternal; 122import android.app.AppOpsManager; 123import android.app.IActivityManager; 124import android.app.ResourcesManager; 125import android.app.admin.IDevicePolicyManager; 126import android.app.admin.SecurityLog; 127import android.app.backup.IBackupManager; 128import android.content.BroadcastReceiver; 129import android.content.ComponentName; 130import android.content.ContentResolver; 131import android.content.Context; 132import android.content.IIntentReceiver; 133import android.content.Intent; 134import android.content.IntentFilter; 135import android.content.IntentSender; 136import android.content.IntentSender.SendIntentException; 137import android.content.ServiceConnection; 138import android.content.pm.ActivityInfo; 139import android.content.pm.ApplicationInfo; 140import android.content.pm.AppsQueryHelper; 141import android.content.pm.AuxiliaryResolveInfo; 142import android.content.pm.ChangedPackages; 143import android.content.pm.ComponentInfo; 144import android.content.pm.FallbackCategoryProvider; 145import android.content.pm.FeatureInfo; 146import android.content.pm.IDexModuleRegisterCallback; 147import android.content.pm.IOnPermissionsChangeListener; 148import android.content.pm.IPackageDataObserver; 149import android.content.pm.IPackageDeleteObserver; 150import android.content.pm.IPackageDeleteObserver2; 151import android.content.pm.IPackageInstallObserver2; 152import android.content.pm.IPackageInstaller; 153import android.content.pm.IPackageManager; 154import android.content.pm.IPackageManagerNative; 155import android.content.pm.IPackageMoveObserver; 156import android.content.pm.IPackageStatsObserver; 157import android.content.pm.InstantAppInfo; 158import android.content.pm.InstantAppRequest; 159import android.content.pm.InstantAppResolveInfo; 160import android.content.pm.InstrumentationInfo; 161import android.content.pm.IntentFilterVerificationInfo; 162import android.content.pm.KeySet; 163import android.content.pm.PackageCleanItem; 164import android.content.pm.PackageInfo; 165import android.content.pm.PackageInfoLite; 166import android.content.pm.PackageInstaller; 167import android.content.pm.PackageList; 168import android.content.pm.PackageManager; 169import android.content.pm.PackageManagerInternal; 170import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 171import android.content.pm.PackageManagerInternal.PackageListObserver; 172import android.content.pm.PackageParser; 173import android.content.pm.PackageParser.ActivityIntentInfo; 174import android.content.pm.PackageParser.Package; 175import android.content.pm.PackageParser.PackageLite; 176import android.content.pm.PackageParser.PackageParserException; 177import android.content.pm.PackageParser.ParseFlags; 178import android.content.pm.PackageParser.ServiceIntentInfo; 179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 180import android.content.pm.PackageStats; 181import android.content.pm.PackageUserState; 182import android.content.pm.ParceledListSlice; 183import android.content.pm.PermissionGroupInfo; 184import android.content.pm.PermissionInfo; 185import android.content.pm.ProviderInfo; 186import android.content.pm.ResolveInfo; 187import android.content.pm.ServiceInfo; 188import android.content.pm.SharedLibraryInfo; 189import android.content.pm.Signature; 190import android.content.pm.UserInfo; 191import android.content.pm.VerifierDeviceIdentity; 192import android.content.pm.VerifierInfo; 193import android.content.pm.VersionedPackage; 194import android.content.pm.dex.ArtManager; 195import android.content.pm.dex.DexMetadataHelper; 196import android.content.pm.dex.IArtManager; 197import android.content.res.Resources; 198import android.database.ContentObserver; 199import android.graphics.Bitmap; 200import android.hardware.display.DisplayManager; 201import android.net.Uri; 202import android.os.Binder; 203import android.os.Build; 204import android.os.Bundle; 205import android.os.Debug; 206import android.os.Environment; 207import android.os.Environment.UserEnvironment; 208import android.os.FileUtils; 209import android.os.Handler; 210import android.os.IBinder; 211import android.os.Looper; 212import android.os.Message; 213import android.os.Parcel; 214import android.os.ParcelFileDescriptor; 215import android.os.PatternMatcher; 216import android.os.Process; 217import android.os.RemoteCallbackList; 218import android.os.RemoteException; 219import android.os.ResultReceiver; 220import android.os.SELinux; 221import android.os.ServiceManager; 222import android.os.ShellCallback; 223import android.os.SystemClock; 224import android.os.SystemProperties; 225import android.os.Trace; 226import android.os.UserHandle; 227import android.os.UserManager; 228import android.os.UserManagerInternal; 229import android.os.storage.IStorageManager; 230import android.os.storage.StorageEventListener; 231import android.os.storage.StorageManager; 232import android.os.storage.StorageManagerInternal; 233import android.os.storage.VolumeInfo; 234import android.os.storage.VolumeRecord; 235import android.provider.Settings.Global; 236import android.provider.Settings.Secure; 237import android.security.KeyStore; 238import android.security.SystemKeyStore; 239import android.service.pm.PackageServiceDumpProto; 240import android.service.textclassifier.TextClassifierService; 241import android.system.ErrnoException; 242import android.system.Os; 243import android.text.TextUtils; 244import android.text.format.DateUtils; 245import android.util.ArrayMap; 246import android.util.ArraySet; 247import android.util.Base64; 248import android.util.ByteStringUtils; 249import android.util.DisplayMetrics; 250import android.util.EventLog; 251import android.util.ExceptionUtils; 252import android.util.Log; 253import android.util.LogPrinter; 254import android.util.LongSparseArray; 255import android.util.LongSparseLongArray; 256import android.util.MathUtils; 257import android.util.PackageUtils; 258import android.util.Pair; 259import android.util.PrintStreamPrinter; 260import android.util.Slog; 261import android.util.SparseArray; 262import android.util.SparseBooleanArray; 263import android.util.SparseIntArray; 264import android.util.TimingsTraceLog; 265import android.util.Xml; 266import android.util.jar.StrictJarFile; 267import android.util.proto.ProtoOutputStream; 268import android.view.Display; 269 270import com.android.internal.R; 271import com.android.internal.annotations.GuardedBy; 272import com.android.internal.app.IMediaContainerService; 273import com.android.internal.app.ResolverActivity; 274import com.android.internal.content.NativeLibraryHelper; 275import com.android.internal.content.PackageHelper; 276import com.android.internal.logging.MetricsLogger; 277import com.android.internal.os.IParcelFileDescriptorFactory; 278import com.android.internal.os.SomeArgs; 279import com.android.internal.os.Zygote; 280import com.android.internal.telephony.CarrierAppUtils; 281import com.android.internal.util.ArrayUtils; 282import com.android.internal.util.ConcurrentUtils; 283import com.android.internal.util.DumpUtils; 284import com.android.internal.util.FastXmlSerializer; 285import com.android.internal.util.IndentingPrintWriter; 286import com.android.internal.util.Preconditions; 287import com.android.internal.util.XmlUtils; 288import com.android.server.AttributeCache; 289import com.android.server.DeviceIdleController; 290import com.android.server.EventLogTags; 291import com.android.server.FgThread; 292import com.android.server.IntentResolver; 293import com.android.server.LocalServices; 294import com.android.server.LockGuard; 295import com.android.server.ServiceThread; 296import com.android.server.SystemConfig; 297import com.android.server.SystemServerInitThreadPool; 298import com.android.server.Watchdog; 299import com.android.server.net.NetworkPolicyManagerInternal; 300import com.android.server.pm.Installer.InstallerException; 301import com.android.server.pm.Settings.DatabaseVersion; 302import com.android.server.pm.Settings.VersionInfo; 303import com.android.server.pm.dex.ArtManagerService; 304import com.android.server.pm.dex.DexLogger; 305import com.android.server.pm.dex.DexManager; 306import com.android.server.pm.dex.DexoptOptions; 307import com.android.server.pm.dex.PackageDexUsage; 308import com.android.server.pm.permission.BasePermission; 309import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 310import com.android.server.pm.permission.PermissionManagerService; 311import com.android.server.pm.permission.PermissionManagerInternal; 312import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 313import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 314import com.android.server.pm.permission.PermissionsState; 315import com.android.server.pm.permission.PermissionsState.PermissionState; 316import com.android.server.security.VerityUtils; 317import com.android.server.storage.DeviceStorageMonitorInternal; 318 319import dalvik.system.CloseGuard; 320import dalvik.system.VMRuntime; 321 322import libcore.io.IoUtils; 323 324import org.xmlpull.v1.XmlPullParser; 325import org.xmlpull.v1.XmlPullParserException; 326import org.xmlpull.v1.XmlSerializer; 327 328import java.io.BufferedOutputStream; 329import java.io.ByteArrayInputStream; 330import java.io.ByteArrayOutputStream; 331import java.io.File; 332import java.io.FileDescriptor; 333import java.io.FileInputStream; 334import java.io.FileOutputStream; 335import java.io.FilenameFilter; 336import java.io.IOException; 337import java.io.PrintWriter; 338import java.lang.annotation.Retention; 339import java.lang.annotation.RetentionPolicy; 340import java.nio.charset.StandardCharsets; 341import java.security.DigestException; 342import java.security.DigestInputStream; 343import java.security.MessageDigest; 344import java.security.NoSuchAlgorithmException; 345import java.security.PublicKey; 346import java.security.SecureRandom; 347import java.security.cert.CertificateException; 348import java.util.ArrayList; 349import java.util.Arrays; 350import java.util.Collection; 351import java.util.Collections; 352import java.util.Comparator; 353import java.util.HashMap; 354import java.util.HashSet; 355import java.util.Iterator; 356import java.util.LinkedHashSet; 357import java.util.List; 358import java.util.Map; 359import java.util.Objects; 360import java.util.Set; 361import java.util.concurrent.CountDownLatch; 362import java.util.concurrent.Future; 363import java.util.concurrent.TimeUnit; 364import java.util.concurrent.atomic.AtomicBoolean; 365import java.util.concurrent.atomic.AtomicInteger; 366 367/** 368 * Keep track of all those APKs everywhere. 369 * <p> 370 * Internally there are two important locks: 371 * <ul> 372 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 373 * and other related state. It is a fine-grained lock that should only be held 374 * momentarily, as it's one of the most contended locks in the system. 375 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 376 * operations typically involve heavy lifting of application data on disk. Since 377 * {@code installd} is single-threaded, and it's operations can often be slow, 378 * this lock should never be acquired while already holding {@link #mPackages}. 379 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 380 * holding {@link #mInstallLock}. 381 * </ul> 382 * Many internal methods rely on the caller to hold the appropriate locks, and 383 * this contract is expressed through method name suffixes: 384 * <ul> 385 * <li>fooLI(): the caller must hold {@link #mInstallLock} 386 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 387 * being modified must be frozen 388 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 389 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 390 * </ul> 391 * <p> 392 * Because this class is very central to the platform's security; please run all 393 * CTS and unit tests whenever making modifications: 394 * 395 * <pre> 396 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 397 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 398 * </pre> 399 */ 400public class PackageManagerService extends IPackageManager.Stub 401 implements PackageSender { 402 static final String TAG = "PackageManager"; 403 public static final boolean DEBUG_SETTINGS = false; 404 static final boolean DEBUG_PREFERRED = false; 405 static final boolean DEBUG_UPGRADE = false; 406 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 407 private static final boolean DEBUG_BACKUP = false; 408 public static final boolean DEBUG_INSTALL = false; 409 public static final boolean DEBUG_REMOVE = false; 410 private static final boolean DEBUG_BROADCASTS = false; 411 private static final boolean DEBUG_SHOW_INFO = false; 412 private static final boolean DEBUG_PACKAGE_INFO = false; 413 private static final boolean DEBUG_INTENT_MATCHING = false; 414 public static final boolean DEBUG_PACKAGE_SCANNING = false; 415 private static final boolean DEBUG_VERIFY = false; 416 private static final boolean DEBUG_FILTERS = false; 417 public static final boolean DEBUG_PERMISSIONS = false; 418 private static final boolean DEBUG_SHARED_LIBRARIES = false; 419 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 420 421 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 422 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 423 // user, but by default initialize to this. 424 public static final boolean DEBUG_DEXOPT = false; 425 426 private static final boolean DEBUG_ABI_SELECTION = false; 427 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 428 private static final boolean DEBUG_TRIAGED_MISSING = false; 429 private static final boolean DEBUG_APP_DATA = false; 430 431 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 432 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 433 434 private static final boolean HIDE_EPHEMERAL_APIS = false; 435 436 private static final boolean ENABLE_FREE_CACHE_V2 = 437 SystemProperties.getBoolean("fw.free_cache_v2", true); 438 439 private static final int RADIO_UID = Process.PHONE_UID; 440 private static final int LOG_UID = Process.LOG_UID; 441 private static final int NFC_UID = Process.NFC_UID; 442 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 443 private static final int SHELL_UID = Process.SHELL_UID; 444 private static final int SE_UID = Process.SE_UID; 445 446 // Suffix used during package installation when copying/moving 447 // package apks to install directory. 448 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 449 450 static final int SCAN_NO_DEX = 1<<0; 451 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 452 static final int SCAN_NEW_INSTALL = 1<<2; 453 static final int SCAN_UPDATE_TIME = 1<<3; 454 static final int SCAN_BOOTING = 1<<4; 455 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 456 static final int SCAN_REQUIRE_KNOWN = 1<<7; 457 static final int SCAN_MOVE = 1<<8; 458 static final int SCAN_INITIAL = 1<<9; 459 static final int SCAN_CHECK_ONLY = 1<<10; 460 static final int SCAN_DONT_KILL_APP = 1<<11; 461 static final int SCAN_IGNORE_FROZEN = 1<<12; 462 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 463 static final int SCAN_AS_INSTANT_APP = 1<<14; 464 static final int SCAN_AS_FULL_APP = 1<<15; 465 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 466 static final int SCAN_AS_SYSTEM = 1<<17; 467 static final int SCAN_AS_PRIVILEGED = 1<<18; 468 static final int SCAN_AS_OEM = 1<<19; 469 static final int SCAN_AS_VENDOR = 1<<20; 470 static final int SCAN_AS_PRODUCT = 1<<21; 471 472 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 473 SCAN_NO_DEX, 474 SCAN_UPDATE_SIGNATURE, 475 SCAN_NEW_INSTALL, 476 SCAN_UPDATE_TIME, 477 SCAN_BOOTING, 478 SCAN_DELETE_DATA_ON_FAILURES, 479 SCAN_REQUIRE_KNOWN, 480 SCAN_MOVE, 481 SCAN_INITIAL, 482 SCAN_CHECK_ONLY, 483 SCAN_DONT_KILL_APP, 484 SCAN_IGNORE_FROZEN, 485 SCAN_FIRST_BOOT_OR_UPGRADE, 486 SCAN_AS_INSTANT_APP, 487 SCAN_AS_FULL_APP, 488 SCAN_AS_VIRTUAL_PRELOAD, 489 }) 490 @Retention(RetentionPolicy.SOURCE) 491 public @interface ScanFlags {} 492 493 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 494 /** Extension of the compressed packages */ 495 public final static String COMPRESSED_EXTENSION = ".gz"; 496 /** Suffix of stub packages on the system partition */ 497 public final static String STUB_SUFFIX = "-Stub"; 498 499 private static final int[] EMPTY_INT_ARRAY = new int[0]; 500 501 private static final int TYPE_UNKNOWN = 0; 502 private static final int TYPE_ACTIVITY = 1; 503 private static final int TYPE_RECEIVER = 2; 504 private static final int TYPE_SERVICE = 3; 505 private static final int TYPE_PROVIDER = 4; 506 @IntDef(prefix = { "TYPE_" }, value = { 507 TYPE_UNKNOWN, 508 TYPE_ACTIVITY, 509 TYPE_RECEIVER, 510 TYPE_SERVICE, 511 TYPE_PROVIDER, 512 }) 513 @Retention(RetentionPolicy.SOURCE) 514 public @interface ComponentType {} 515 516 /** 517 * Timeout (in milliseconds) after which the watchdog should declare that 518 * our handler thread is wedged. The usual default for such things is one 519 * minute but we sometimes do very lengthy I/O operations on this thread, 520 * such as installing multi-gigabyte applications, so ours needs to be longer. 521 */ 522 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 523 524 /** 525 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 526 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 527 * settings entry if available, otherwise we use the hardcoded default. If it's been 528 * more than this long since the last fstrim, we force one during the boot sequence. 529 * 530 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 531 * one gets run at the next available charging+idle time. This final mandatory 532 * no-fstrim check kicks in only of the other scheduling criteria is never met. 533 */ 534 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 535 536 /** 537 * Whether verification is enabled by default. 538 */ 539 private static final boolean DEFAULT_VERIFY_ENABLE = true; 540 541 /** 542 * The default maximum time to wait for the verification agent to return in 543 * milliseconds. 544 */ 545 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 546 547 /** 548 * The default response for package verification timeout. 549 * 550 * This can be either PackageManager.VERIFICATION_ALLOW or 551 * PackageManager.VERIFICATION_REJECT. 552 */ 553 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 554 555 public static final String PLATFORM_PACKAGE_NAME = "android"; 556 557 public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 558 559 public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 560 DEFAULT_CONTAINER_PACKAGE, 561 "com.android.defcontainer.DefaultContainerService"); 562 563 private static final String KILL_APP_REASON_GIDS_CHANGED = 564 "permission grant or revoke changed gids"; 565 566 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 567 "permissions revoked"; 568 569 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 570 571 private static final String PACKAGE_SCHEME = "package"; 572 573 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 574 575 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 576 577 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 578 579 /** Canonical intent used to identify what counts as a "web browser" app */ 580 private static final Intent sBrowserIntent; 581 static { 582 sBrowserIntent = new Intent(); 583 sBrowserIntent.setAction(Intent.ACTION_VIEW); 584 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 585 sBrowserIntent.setData(Uri.parse("http:")); 586 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 587 } 588 589 /** 590 * The set of all protected actions [i.e. those actions for which a high priority 591 * intent filter is disallowed]. 592 */ 593 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 594 static { 595 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 596 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 597 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 598 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 599 } 600 601 // Compilation reasons. 602 public static final int REASON_UNKNOWN = -1; 603 public static final int REASON_FIRST_BOOT = 0; 604 public static final int REASON_BOOT = 1; 605 public static final int REASON_INSTALL = 2; 606 public static final int REASON_BACKGROUND_DEXOPT = 3; 607 public static final int REASON_AB_OTA = 4; 608 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 609 public static final int REASON_SHARED = 6; 610 611 public static final int REASON_LAST = REASON_SHARED; 612 613 /** 614 * Version number for the package parser cache. Increment this whenever the format or 615 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 616 */ 617 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 618 619 /** 620 * Whether the package parser cache is enabled. 621 */ 622 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 623 624 /** 625 * Permissions required in order to receive instant application lifecycle broadcasts. 626 */ 627 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 628 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 629 630 final ServiceThread mHandlerThread; 631 632 final PackageHandler mHandler; 633 634 private final ProcessLoggingHandler mProcessLoggingHandler; 635 636 /** 637 * Messages for {@link #mHandler} that need to wait for system ready before 638 * being dispatched. 639 */ 640 private ArrayList<Message> mPostSystemReadyMessages; 641 642 final int mSdkVersion = Build.VERSION.SDK_INT; 643 644 final Context mContext; 645 final boolean mFactoryTest; 646 final boolean mOnlyCore; 647 final DisplayMetrics mMetrics; 648 final int mDefParseFlags; 649 final String[] mSeparateProcesses; 650 final boolean mIsUpgrade; 651 final boolean mIsPreNUpgrade; 652 final boolean mIsPreNMR1Upgrade; 653 654 // Have we told the Activity Manager to whitelist the default container service by uid yet? 655 @GuardedBy("mPackages") 656 boolean mDefaultContainerWhitelisted = false; 657 658 @GuardedBy("mPackages") 659 private boolean mDexOptDialogShown; 660 661 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 662 // LOCK HELD. Can be called with mInstallLock held. 663 @GuardedBy("mInstallLock") 664 final Installer mInstaller; 665 666 /** Directory where installed applications are stored */ 667 private static final File sAppInstallDir = 668 new File(Environment.getDataDirectory(), "app"); 669 /** Directory where installed application's 32-bit native libraries are copied. */ 670 private static final File sAppLib32InstallDir = 671 new File(Environment.getDataDirectory(), "app-lib"); 672 /** Directory where code and non-resource assets of forward-locked applications are stored */ 673 private static final File sDrmAppPrivateInstallDir = 674 new File(Environment.getDataDirectory(), "app-private"); 675 676 // ---------------------------------------------------------------- 677 678 // Lock for state used when installing and doing other long running 679 // operations. Methods that must be called with this lock held have 680 // the suffix "LI". 681 final Object mInstallLock = new Object(); 682 683 // ---------------------------------------------------------------- 684 685 // Keys are String (package name), values are Package. This also serves 686 // as the lock for the global state. Methods that must be called with 687 // this lock held have the prefix "LP". 688 @GuardedBy("mPackages") 689 final ArrayMap<String, PackageParser.Package> mPackages = 690 new ArrayMap<String, PackageParser.Package>(); 691 692 final ArrayMap<String, Set<String>> mKnownCodebase = 693 new ArrayMap<String, Set<String>>(); 694 695 // Keys are isolated uids and values are the uid of the application 696 // that created the isolated proccess. 697 @GuardedBy("mPackages") 698 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 699 700 /** 701 * Tracks new system packages [received in an OTA] that we expect to 702 * find updated user-installed versions. Keys are package name, values 703 * are package location. 704 */ 705 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 706 /** 707 * Tracks high priority intent filters for protected actions. During boot, certain 708 * filter actions are protected and should never be allowed to have a high priority 709 * intent filter for them. However, there is one, and only one exception -- the 710 * setup wizard. It must be able to define a high priority intent filter for these 711 * actions to ensure there are no escapes from the wizard. We need to delay processing 712 * of these during boot as we need to look at all of the system packages in order 713 * to know which component is the setup wizard. 714 */ 715 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 716 /** 717 * Whether or not processing protected filters should be deferred. 718 */ 719 private boolean mDeferProtectedFilters = true; 720 721 /** 722 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 723 */ 724 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 725 /** 726 * Whether or not system app permissions should be promoted from install to runtime. 727 */ 728 boolean mPromoteSystemApps; 729 730 @GuardedBy("mPackages") 731 final Settings mSettings; 732 733 /** 734 * Set of package names that are currently "frozen", which means active 735 * surgery is being done on the code/data for that package. The platform 736 * will refuse to launch frozen packages to avoid race conditions. 737 * 738 * @see PackageFreezer 739 */ 740 @GuardedBy("mPackages") 741 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 742 743 final ProtectedPackages mProtectedPackages; 744 745 @GuardedBy("mLoadedVolumes") 746 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 747 748 boolean mFirstBoot; 749 750 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 751 752 @GuardedBy("mAvailableFeatures") 753 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 754 755 private final InstantAppRegistry mInstantAppRegistry; 756 757 @GuardedBy("mPackages") 758 int mChangedPackagesSequenceNumber; 759 /** 760 * List of changed [installed, removed or updated] packages. 761 * mapping from user id -> sequence number -> package name 762 */ 763 @GuardedBy("mPackages") 764 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 765 /** 766 * The sequence number of the last change to a package. 767 * mapping from user id -> package name -> sequence number 768 */ 769 @GuardedBy("mPackages") 770 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 771 772 @GuardedBy("mPackages") 773 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 774 775 class PackageParserCallback implements PackageParser.Callback { 776 @Override public final boolean hasFeature(String feature) { 777 return PackageManagerService.this.hasSystemFeature(feature, 0); 778 } 779 780 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 781 Collection<PackageParser.Package> allPackages, String targetPackageName) { 782 List<PackageParser.Package> overlayPackages = null; 783 for (PackageParser.Package p : allPackages) { 784 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 785 if (overlayPackages == null) { 786 overlayPackages = new ArrayList<PackageParser.Package>(); 787 } 788 overlayPackages.add(p); 789 } 790 } 791 if (overlayPackages != null) { 792 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 793 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 794 return p1.mOverlayPriority - p2.mOverlayPriority; 795 } 796 }; 797 Collections.sort(overlayPackages, cmp); 798 } 799 return overlayPackages; 800 } 801 802 @GuardedBy("mInstallLock") 803 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 804 String targetPackageName, String targetPath) { 805 if ("android".equals(targetPackageName)) { 806 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 807 // native AssetManager. 808 return null; 809 } 810 List<PackageParser.Package> overlayPackages = 811 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 812 if (overlayPackages == null || overlayPackages.isEmpty()) { 813 return null; 814 } 815 List<String> overlayPathList = null; 816 for (PackageParser.Package overlayPackage : overlayPackages) { 817 if (targetPath == null) { 818 if (overlayPathList == null) { 819 overlayPathList = new ArrayList<String>(); 820 } 821 overlayPathList.add(overlayPackage.baseCodePath); 822 continue; 823 } 824 825 try { 826 // Creates idmaps for system to parse correctly the Android manifest of the 827 // target package. 828 // 829 // OverlayManagerService will update each of them with a correct gid from its 830 // target package app id. 831 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 832 UserHandle.getSharedAppGid( 833 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 834 if (overlayPathList == null) { 835 overlayPathList = new ArrayList<String>(); 836 } 837 overlayPathList.add(overlayPackage.baseCodePath); 838 } catch (InstallerException e) { 839 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 840 overlayPackage.baseCodePath); 841 } 842 } 843 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 844 } 845 846 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 847 synchronized (mPackages) { 848 return getStaticOverlayPathsLocked( 849 mPackages.values(), targetPackageName, targetPath); 850 } 851 } 852 853 @Override public final String[] getOverlayApks(String targetPackageName) { 854 return getStaticOverlayPaths(targetPackageName, null); 855 } 856 857 @Override public final String[] getOverlayPaths(String targetPackageName, 858 String targetPath) { 859 return getStaticOverlayPaths(targetPackageName, targetPath); 860 } 861 } 862 863 class ParallelPackageParserCallback extends PackageParserCallback { 864 List<PackageParser.Package> mOverlayPackages = null; 865 866 void findStaticOverlayPackages() { 867 synchronized (mPackages) { 868 for (PackageParser.Package p : mPackages.values()) { 869 if (p.mOverlayIsStatic) { 870 if (mOverlayPackages == null) { 871 mOverlayPackages = new ArrayList<PackageParser.Package>(); 872 } 873 mOverlayPackages.add(p); 874 } 875 } 876 } 877 } 878 879 @Override 880 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 881 // We can trust mOverlayPackages without holding mPackages because package uninstall 882 // can't happen while running parallel parsing. 883 // Moreover holding mPackages on each parsing thread causes dead-lock. 884 return mOverlayPackages == null ? null : 885 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 886 } 887 } 888 889 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 890 final ParallelPackageParserCallback mParallelPackageParserCallback = 891 new ParallelPackageParserCallback(); 892 893 public static final class SharedLibraryEntry { 894 public final @Nullable String path; 895 public final @Nullable String apk; 896 public final @NonNull SharedLibraryInfo info; 897 898 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 899 String declaringPackageName, long declaringPackageVersionCode) { 900 path = _path; 901 apk = _apk; 902 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 903 declaringPackageName, declaringPackageVersionCode), null); 904 } 905 } 906 907 // Currently known shared libraries. 908 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 909 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 910 new ArrayMap<>(); 911 912 // All available activities, for your resolving pleasure. 913 final ActivityIntentResolver mActivities = 914 new ActivityIntentResolver(); 915 916 // All available receivers, for your resolving pleasure. 917 final ActivityIntentResolver mReceivers = 918 new ActivityIntentResolver(); 919 920 // All available services, for your resolving pleasure. 921 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 922 923 // All available providers, for your resolving pleasure. 924 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 925 926 // Mapping from provider base names (first directory in content URI codePath) 927 // to the provider information. 928 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 929 new ArrayMap<String, PackageParser.Provider>(); 930 931 // Mapping from instrumentation class names to info about them. 932 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 933 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 934 935 // Packages whose data we have transfered into another package, thus 936 // should no longer exist. 937 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 938 939 // Broadcast actions that are only available to the system. 940 @GuardedBy("mProtectedBroadcasts") 941 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 942 943 /** List of packages waiting for verification. */ 944 final SparseArray<PackageVerificationState> mPendingVerification 945 = new SparseArray<PackageVerificationState>(); 946 947 final PackageInstallerService mInstallerService; 948 949 final ArtManagerService mArtManagerService; 950 951 private final PackageDexOptimizer mPackageDexOptimizer; 952 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 953 // is used by other apps). 954 private final DexManager mDexManager; 955 956 private AtomicInteger mNextMoveId = new AtomicInteger(); 957 private final MoveCallbacks mMoveCallbacks; 958 959 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 960 961 // Cache of users who need badging. 962 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 963 964 /** Token for keys in mPendingVerification. */ 965 private int mPendingVerificationToken = 0; 966 967 volatile boolean mSystemReady; 968 volatile boolean mSafeMode; 969 volatile boolean mHasSystemUidErrors; 970 private volatile boolean mWebInstantAppsDisabled; 971 972 ApplicationInfo mAndroidApplication; 973 final ActivityInfo mResolveActivity = new ActivityInfo(); 974 final ResolveInfo mResolveInfo = new ResolveInfo(); 975 ComponentName mResolveComponentName; 976 PackageParser.Package mPlatformPackage; 977 ComponentName mCustomResolverComponentName; 978 979 boolean mResolverReplaced = false; 980 981 private final @Nullable ComponentName mIntentFilterVerifierComponent; 982 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 983 984 private int mIntentFilterVerificationToken = 0; 985 986 /** The service connection to the ephemeral resolver */ 987 final InstantAppResolverConnection mInstantAppResolverConnection; 988 /** Component used to show resolver settings for Instant Apps */ 989 final ComponentName mInstantAppResolverSettingsComponent; 990 991 /** Activity used to install instant applications */ 992 ActivityInfo mInstantAppInstallerActivity; 993 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 994 995 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 996 = new SparseArray<IntentFilterVerificationState>(); 997 998 // TODO remove this and go through mPermissonManager directly 999 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1000 private final PermissionManagerInternal mPermissionManager; 1001 1002 // List of packages names to keep cached, even if they are uninstalled for all users 1003 private List<String> mKeepUninstalledPackages; 1004 1005 private UserManagerInternal mUserManagerInternal; 1006 private ActivityManagerInternal mActivityManagerInternal; 1007 1008 private DeviceIdleController.LocalService mDeviceIdleController; 1009 1010 private File mCacheDir; 1011 1012 private Future<?> mPrepareAppDataFuture; 1013 1014 private static class IFVerificationParams { 1015 PackageParser.Package pkg; 1016 boolean replacing; 1017 int userId; 1018 int verifierUid; 1019 1020 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1021 int _userId, int _verifierUid) { 1022 pkg = _pkg; 1023 replacing = _replacing; 1024 userId = _userId; 1025 replacing = _replacing; 1026 verifierUid = _verifierUid; 1027 } 1028 } 1029 1030 private interface IntentFilterVerifier<T extends IntentFilter> { 1031 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1032 T filter, String packageName); 1033 void startVerifications(int userId); 1034 void receiveVerificationResponse(int verificationId); 1035 } 1036 1037 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1038 private Context mContext; 1039 private ComponentName mIntentFilterVerifierComponent; 1040 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1041 1042 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1043 mContext = context; 1044 mIntentFilterVerifierComponent = verifierComponent; 1045 } 1046 1047 private String getDefaultScheme() { 1048 return IntentFilter.SCHEME_HTTPS; 1049 } 1050 1051 @Override 1052 public void startVerifications(int userId) { 1053 // Launch verifications requests 1054 int count = mCurrentIntentFilterVerifications.size(); 1055 for (int n=0; n<count; n++) { 1056 int verificationId = mCurrentIntentFilterVerifications.get(n); 1057 final IntentFilterVerificationState ivs = 1058 mIntentFilterVerificationStates.get(verificationId); 1059 1060 String packageName = ivs.getPackageName(); 1061 1062 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1063 final int filterCount = filters.size(); 1064 ArraySet<String> domainsSet = new ArraySet<>(); 1065 for (int m=0; m<filterCount; m++) { 1066 PackageParser.ActivityIntentInfo filter = filters.get(m); 1067 domainsSet.addAll(filter.getHostsList()); 1068 } 1069 synchronized (mPackages) { 1070 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1071 packageName, domainsSet) != null) { 1072 scheduleWriteSettingsLocked(); 1073 } 1074 } 1075 sendVerificationRequest(verificationId, ivs); 1076 } 1077 mCurrentIntentFilterVerifications.clear(); 1078 } 1079 1080 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1081 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1082 verificationIntent.putExtra( 1083 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1084 verificationId); 1085 verificationIntent.putExtra( 1086 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1087 getDefaultScheme()); 1088 verificationIntent.putExtra( 1089 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1090 ivs.getHostsString()); 1091 verificationIntent.putExtra( 1092 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1093 ivs.getPackageName()); 1094 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1095 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1096 1097 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1098 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1099 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1100 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1101 1102 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1103 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1104 "Sending IntentFilter verification broadcast"); 1105 } 1106 1107 public void receiveVerificationResponse(int verificationId) { 1108 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1109 1110 final boolean verified = ivs.isVerified(); 1111 1112 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1113 final int count = filters.size(); 1114 if (DEBUG_DOMAIN_VERIFICATION) { 1115 Slog.i(TAG, "Received verification response " + verificationId 1116 + " for " + count + " filters, verified=" + verified); 1117 } 1118 for (int n=0; n<count; n++) { 1119 PackageParser.ActivityIntentInfo filter = filters.get(n); 1120 filter.setVerified(verified); 1121 1122 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1123 + " verified with result:" + verified + " and hosts:" 1124 + ivs.getHostsString()); 1125 } 1126 1127 mIntentFilterVerificationStates.remove(verificationId); 1128 1129 final String packageName = ivs.getPackageName(); 1130 IntentFilterVerificationInfo ivi = null; 1131 1132 synchronized (mPackages) { 1133 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1134 } 1135 if (ivi == null) { 1136 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1137 + verificationId + " packageName:" + packageName); 1138 return; 1139 } 1140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1141 "Updating IntentFilterVerificationInfo for package " + packageName 1142 +" verificationId:" + verificationId); 1143 1144 synchronized (mPackages) { 1145 if (verified) { 1146 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1147 } else { 1148 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1149 } 1150 scheduleWriteSettingsLocked(); 1151 1152 final int userId = ivs.getUserId(); 1153 if (userId != UserHandle.USER_ALL) { 1154 final int userStatus = 1155 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1156 1157 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1158 boolean needUpdate = false; 1159 1160 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1161 // already been set by the User thru the Disambiguation dialog 1162 switch (userStatus) { 1163 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1164 if (verified) { 1165 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1166 } else { 1167 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1168 } 1169 needUpdate = true; 1170 break; 1171 1172 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1173 if (verified) { 1174 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1175 needUpdate = true; 1176 } 1177 break; 1178 1179 default: 1180 // Nothing to do 1181 } 1182 1183 if (needUpdate) { 1184 mSettings.updateIntentFilterVerificationStatusLPw( 1185 packageName, updatedStatus, userId); 1186 scheduleWritePackageRestrictionsLocked(userId); 1187 } 1188 } 1189 } 1190 } 1191 1192 @Override 1193 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1194 ActivityIntentInfo filter, String packageName) { 1195 if (!hasValidDomains(filter)) { 1196 return false; 1197 } 1198 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1199 if (ivs == null) { 1200 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1201 packageName); 1202 } 1203 if (DEBUG_DOMAIN_VERIFICATION) { 1204 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1205 } 1206 ivs.addFilter(filter); 1207 return true; 1208 } 1209 1210 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1211 int userId, int verificationId, String packageName) { 1212 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1213 verifierUid, userId, packageName); 1214 ivs.setPendingState(); 1215 synchronized (mPackages) { 1216 mIntentFilterVerificationStates.append(verificationId, ivs); 1217 mCurrentIntentFilterVerifications.add(verificationId); 1218 } 1219 return ivs; 1220 } 1221 } 1222 1223 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1224 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1225 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1226 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1227 } 1228 1229 // Set of pending broadcasts for aggregating enable/disable of components. 1230 static class PendingPackageBroadcasts { 1231 // for each user id, a map of <package name -> components within that package> 1232 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1233 1234 public PendingPackageBroadcasts() { 1235 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1236 } 1237 1238 public ArrayList<String> get(int userId, String packageName) { 1239 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1240 return packages.get(packageName); 1241 } 1242 1243 public void put(int userId, String packageName, ArrayList<String> components) { 1244 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1245 packages.put(packageName, components); 1246 } 1247 1248 public void remove(int userId, String packageName) { 1249 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1250 if (packages != null) { 1251 packages.remove(packageName); 1252 } 1253 } 1254 1255 public void remove(int userId) { 1256 mUidMap.remove(userId); 1257 } 1258 1259 public int userIdCount() { 1260 return mUidMap.size(); 1261 } 1262 1263 public int userIdAt(int n) { 1264 return mUidMap.keyAt(n); 1265 } 1266 1267 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1268 return mUidMap.get(userId); 1269 } 1270 1271 public int size() { 1272 // total number of pending broadcast entries across all userIds 1273 int num = 0; 1274 for (int i = 0; i< mUidMap.size(); i++) { 1275 num += mUidMap.valueAt(i).size(); 1276 } 1277 return num; 1278 } 1279 1280 public void clear() { 1281 mUidMap.clear(); 1282 } 1283 1284 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1285 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1286 if (map == null) { 1287 map = new ArrayMap<String, ArrayList<String>>(); 1288 mUidMap.put(userId, map); 1289 } 1290 return map; 1291 } 1292 } 1293 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1294 1295 // Service Connection to remote media container service to copy 1296 // package uri's from external media onto secure containers 1297 // or internal storage. 1298 private IMediaContainerService mContainerService = null; 1299 1300 static final int SEND_PENDING_BROADCAST = 1; 1301 static final int MCS_BOUND = 3; 1302 static final int END_COPY = 4; 1303 static final int INIT_COPY = 5; 1304 static final int MCS_UNBIND = 6; 1305 static final int START_CLEANING_PACKAGE = 7; 1306 static final int FIND_INSTALL_LOC = 8; 1307 static final int POST_INSTALL = 9; 1308 static final int MCS_RECONNECT = 10; 1309 static final int MCS_GIVE_UP = 11; 1310 static final int WRITE_SETTINGS = 13; 1311 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1312 static final int PACKAGE_VERIFIED = 15; 1313 static final int CHECK_PENDING_VERIFICATION = 16; 1314 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1315 static final int INTENT_FILTER_VERIFIED = 18; 1316 static final int WRITE_PACKAGE_LIST = 19; 1317 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1318 1319 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1320 1321 // Delay time in millisecs 1322 static final int BROADCAST_DELAY = 10 * 1000; 1323 1324 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1325 2 * 60 * 60 * 1000L; /* two hours */ 1326 1327 static UserManagerService sUserManager; 1328 1329 // Stores a list of users whose package restrictions file needs to be updated 1330 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1331 1332 final private DefaultContainerConnection mDefContainerConn = 1333 new DefaultContainerConnection(); 1334 class DefaultContainerConnection implements ServiceConnection { 1335 public void onServiceConnected(ComponentName name, IBinder service) { 1336 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1337 final IMediaContainerService imcs = IMediaContainerService.Stub 1338 .asInterface(Binder.allowBlocking(service)); 1339 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1340 } 1341 1342 public void onServiceDisconnected(ComponentName name) { 1343 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1344 } 1345 } 1346 1347 // Recordkeeping of restore-after-install operations that are currently in flight 1348 // between the Package Manager and the Backup Manager 1349 static class PostInstallData { 1350 public InstallArgs args; 1351 public PackageInstalledInfo res; 1352 1353 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1354 args = _a; 1355 res = _r; 1356 } 1357 } 1358 1359 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1360 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1361 1362 // XML tags for backup/restore of various bits of state 1363 private static final String TAG_PREFERRED_BACKUP = "pa"; 1364 private static final String TAG_DEFAULT_APPS = "da"; 1365 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1366 1367 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1368 private static final String TAG_ALL_GRANTS = "rt-grants"; 1369 private static final String TAG_GRANT = "grant"; 1370 private static final String ATTR_PACKAGE_NAME = "pkg"; 1371 1372 private static final String TAG_PERMISSION = "perm"; 1373 private static final String ATTR_PERMISSION_NAME = "name"; 1374 private static final String ATTR_IS_GRANTED = "g"; 1375 private static final String ATTR_USER_SET = "set"; 1376 private static final String ATTR_USER_FIXED = "fixed"; 1377 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1378 1379 // System/policy permission grants are not backed up 1380 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1381 FLAG_PERMISSION_POLICY_FIXED 1382 | FLAG_PERMISSION_SYSTEM_FIXED 1383 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1384 1385 // And we back up these user-adjusted states 1386 private static final int USER_RUNTIME_GRANT_MASK = 1387 FLAG_PERMISSION_USER_SET 1388 | FLAG_PERMISSION_USER_FIXED 1389 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1390 1391 final @Nullable String mRequiredVerifierPackage; 1392 final @NonNull String mRequiredInstallerPackage; 1393 final @NonNull String mRequiredUninstallerPackage; 1394 final @Nullable String mSetupWizardPackage; 1395 final @Nullable String mStorageManagerPackage; 1396 final @Nullable String mSystemTextClassifierPackage; 1397 final @NonNull String mServicesSystemSharedLibraryPackageName; 1398 final @NonNull String mSharedSystemSharedLibraryPackageName; 1399 1400 private final PackageUsage mPackageUsage = new PackageUsage(); 1401 private final CompilerStats mCompilerStats = new CompilerStats(); 1402 1403 class PackageHandler extends Handler { 1404 private boolean mBound = false; 1405 final ArrayList<HandlerParams> mPendingInstalls = 1406 new ArrayList<HandlerParams>(); 1407 1408 private boolean connectToService() { 1409 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1410 " DefaultContainerService"); 1411 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1412 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1413 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1414 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 mBound = true; 1417 return true; 1418 } 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1420 return false; 1421 } 1422 1423 private void disconnectService() { 1424 mContainerService = null; 1425 mBound = false; 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1427 mContext.unbindService(mDefContainerConn); 1428 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1429 } 1430 1431 PackageHandler(Looper looper) { 1432 super(looper); 1433 } 1434 1435 public void handleMessage(Message msg) { 1436 try { 1437 doHandleMessage(msg); 1438 } finally { 1439 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1440 } 1441 } 1442 1443 void doHandleMessage(Message msg) { 1444 switch (msg.what) { 1445 case INIT_COPY: { 1446 HandlerParams params = (HandlerParams) msg.obj; 1447 int idx = mPendingInstalls.size(); 1448 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1449 // If a bind was already initiated we dont really 1450 // need to do anything. The pending install 1451 // will be processed later on. 1452 if (!mBound) { 1453 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1454 System.identityHashCode(mHandler)); 1455 // If this is the only one pending we might 1456 // have to bind to the service again. 1457 if (!connectToService()) { 1458 Slog.e(TAG, "Failed to bind to media container service"); 1459 params.serviceError(); 1460 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1461 System.identityHashCode(mHandler)); 1462 if (params.traceMethod != null) { 1463 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1464 params.traceCookie); 1465 } 1466 return; 1467 } else { 1468 // Once we bind to the service, the first 1469 // pending request will be processed. 1470 mPendingInstalls.add(idx, params); 1471 } 1472 } else { 1473 mPendingInstalls.add(idx, params); 1474 // Already bound to the service. Just make 1475 // sure we trigger off processing the first request. 1476 if (idx == 0) { 1477 mHandler.sendEmptyMessage(MCS_BOUND); 1478 } 1479 } 1480 break; 1481 } 1482 case MCS_BOUND: { 1483 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1484 if (msg.obj != null) { 1485 mContainerService = (IMediaContainerService) msg.obj; 1486 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1487 System.identityHashCode(mHandler)); 1488 } 1489 if (mContainerService == null) { 1490 if (!mBound) { 1491 // Something seriously wrong since we are not bound and we are not 1492 // waiting for connection. Bail out. 1493 Slog.e(TAG, "Cannot bind to media container service"); 1494 for (HandlerParams params : mPendingInstalls) { 1495 // Indicate service bind error 1496 params.serviceError(); 1497 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1498 System.identityHashCode(params)); 1499 if (params.traceMethod != null) { 1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1501 params.traceMethod, params.traceCookie); 1502 } 1503 return; 1504 } 1505 mPendingInstalls.clear(); 1506 } else { 1507 Slog.w(TAG, "Waiting to connect to media container service"); 1508 } 1509 } else if (mPendingInstalls.size() > 0) { 1510 HandlerParams params = mPendingInstalls.get(0); 1511 if (params != null) { 1512 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1513 System.identityHashCode(params)); 1514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1515 if (params.startCopy()) { 1516 // We are done... look for more work or to 1517 // go idle. 1518 if (DEBUG_SD_INSTALL) Log.i(TAG, 1519 "Checking for more work or unbind..."); 1520 // Delete pending install 1521 if (mPendingInstalls.size() > 0) { 1522 mPendingInstalls.remove(0); 1523 } 1524 if (mPendingInstalls.size() == 0) { 1525 if (mBound) { 1526 if (DEBUG_SD_INSTALL) Log.i(TAG, 1527 "Posting delayed MCS_UNBIND"); 1528 removeMessages(MCS_UNBIND); 1529 Message ubmsg = obtainMessage(MCS_UNBIND); 1530 // Unbind after a little delay, to avoid 1531 // continual thrashing. 1532 sendMessageDelayed(ubmsg, 10000); 1533 } 1534 } else { 1535 // There are more pending requests in queue. 1536 // Just post MCS_BOUND message to trigger processing 1537 // of next pending install. 1538 if (DEBUG_SD_INSTALL) Log.i(TAG, 1539 "Posting MCS_BOUND for next work"); 1540 mHandler.sendEmptyMessage(MCS_BOUND); 1541 } 1542 } 1543 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1544 } 1545 } else { 1546 // Should never happen ideally. 1547 Slog.w(TAG, "Empty queue"); 1548 } 1549 break; 1550 } 1551 case MCS_RECONNECT: { 1552 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1553 if (mPendingInstalls.size() > 0) { 1554 if (mBound) { 1555 disconnectService(); 1556 } 1557 if (!connectToService()) { 1558 Slog.e(TAG, "Failed to bind to media container service"); 1559 for (HandlerParams params : mPendingInstalls) { 1560 // Indicate service bind error 1561 params.serviceError(); 1562 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1563 System.identityHashCode(params)); 1564 } 1565 mPendingInstalls.clear(); 1566 } 1567 } 1568 break; 1569 } 1570 case MCS_UNBIND: { 1571 // If there is no actual work left, then time to unbind. 1572 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1573 1574 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1575 if (mBound) { 1576 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1577 1578 disconnectService(); 1579 } 1580 } else if (mPendingInstalls.size() > 0) { 1581 // There are more pending requests in queue. 1582 // Just post MCS_BOUND message to trigger processing 1583 // of next pending install. 1584 mHandler.sendEmptyMessage(MCS_BOUND); 1585 } 1586 1587 break; 1588 } 1589 case MCS_GIVE_UP: { 1590 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1591 HandlerParams params = mPendingInstalls.remove(0); 1592 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1593 System.identityHashCode(params)); 1594 break; 1595 } 1596 case SEND_PENDING_BROADCAST: { 1597 String packages[]; 1598 ArrayList<String> components[]; 1599 int size = 0; 1600 int uids[]; 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1602 synchronized (mPackages) { 1603 if (mPendingBroadcasts == null) { 1604 return; 1605 } 1606 size = mPendingBroadcasts.size(); 1607 if (size <= 0) { 1608 // Nothing to be done. Just return 1609 return; 1610 } 1611 packages = new String[size]; 1612 components = new ArrayList[size]; 1613 uids = new int[size]; 1614 int i = 0; // filling out the above arrays 1615 1616 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1617 int packageUserId = mPendingBroadcasts.userIdAt(n); 1618 Iterator<Map.Entry<String, ArrayList<String>>> it 1619 = mPendingBroadcasts.packagesForUserId(packageUserId) 1620 .entrySet().iterator(); 1621 while (it.hasNext() && i < size) { 1622 Map.Entry<String, ArrayList<String>> ent = it.next(); 1623 packages[i] = ent.getKey(); 1624 components[i] = ent.getValue(); 1625 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1626 uids[i] = (ps != null) 1627 ? UserHandle.getUid(packageUserId, ps.appId) 1628 : -1; 1629 i++; 1630 } 1631 } 1632 size = i; 1633 mPendingBroadcasts.clear(); 1634 } 1635 // Send broadcasts 1636 for (int i = 0; i < size; i++) { 1637 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1638 } 1639 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1640 break; 1641 } 1642 case START_CLEANING_PACKAGE: { 1643 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1644 final String packageName = (String)msg.obj; 1645 final int userId = msg.arg1; 1646 final boolean andCode = msg.arg2 != 0; 1647 synchronized (mPackages) { 1648 if (userId == UserHandle.USER_ALL) { 1649 int[] users = sUserManager.getUserIds(); 1650 for (int user : users) { 1651 mSettings.addPackageToCleanLPw( 1652 new PackageCleanItem(user, packageName, andCode)); 1653 } 1654 } else { 1655 mSettings.addPackageToCleanLPw( 1656 new PackageCleanItem(userId, packageName, andCode)); 1657 } 1658 } 1659 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1660 startCleaningPackages(); 1661 } break; 1662 case POST_INSTALL: { 1663 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1664 1665 PostInstallData data = mRunningInstalls.get(msg.arg1); 1666 final boolean didRestore = (msg.arg2 != 0); 1667 mRunningInstalls.delete(msg.arg1); 1668 1669 if (data != null) { 1670 InstallArgs args = data.args; 1671 PackageInstalledInfo parentRes = data.res; 1672 1673 final boolean grantPermissions = (args.installFlags 1674 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1675 final boolean killApp = (args.installFlags 1676 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1677 final boolean virtualPreload = ((args.installFlags 1678 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1679 final String[] grantedPermissions = args.installGrantPermissions; 1680 1681 // Handle the parent package 1682 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1683 virtualPreload, grantedPermissions, didRestore, 1684 args.installerPackageName, args.observer); 1685 1686 // Handle the child packages 1687 final int childCount = (parentRes.addedChildPackages != null) 1688 ? parentRes.addedChildPackages.size() : 0; 1689 for (int i = 0; i < childCount; i++) { 1690 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1691 handlePackagePostInstall(childRes, grantPermissions, killApp, 1692 virtualPreload, grantedPermissions, false /*didRestore*/, 1693 args.installerPackageName, args.observer); 1694 } 1695 1696 // Log tracing if needed 1697 if (args.traceMethod != null) { 1698 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1699 args.traceCookie); 1700 } 1701 } else { 1702 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1703 } 1704 1705 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1706 } break; 1707 case WRITE_SETTINGS: { 1708 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1709 synchronized (mPackages) { 1710 removeMessages(WRITE_SETTINGS); 1711 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1712 mSettings.writeLPr(); 1713 mDirtyUsers.clear(); 1714 } 1715 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1716 } break; 1717 case WRITE_PACKAGE_RESTRICTIONS: { 1718 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1719 synchronized (mPackages) { 1720 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1721 for (int userId : mDirtyUsers) { 1722 mSettings.writePackageRestrictionsLPr(userId); 1723 } 1724 mDirtyUsers.clear(); 1725 } 1726 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1727 } break; 1728 case WRITE_PACKAGE_LIST: { 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1730 synchronized (mPackages) { 1731 removeMessages(WRITE_PACKAGE_LIST); 1732 mSettings.writePackageListLPr(msg.arg1); 1733 } 1734 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1735 } break; 1736 case CHECK_PENDING_VERIFICATION: { 1737 final int verificationId = msg.arg1; 1738 final PackageVerificationState state = mPendingVerification.get(verificationId); 1739 1740 if ((state != null) && !state.timeoutExtended()) { 1741 final InstallArgs args = state.getInstallArgs(); 1742 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1743 1744 Slog.i(TAG, "Verification timed out for " + originUri); 1745 mPendingVerification.remove(verificationId); 1746 1747 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1748 1749 final UserHandle user = args.getUser(); 1750 if (getDefaultVerificationResponse(user) 1751 == PackageManager.VERIFICATION_ALLOW) { 1752 Slog.i(TAG, "Continuing with installation of " + originUri); 1753 state.setVerifierResponse(Binder.getCallingUid(), 1754 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1755 broadcastPackageVerified(verificationId, originUri, 1756 PackageManager.VERIFICATION_ALLOW, user); 1757 try { 1758 ret = args.copyApk(mContainerService, true); 1759 } catch (RemoteException e) { 1760 Slog.e(TAG, "Could not contact the ContainerService"); 1761 } 1762 } else { 1763 broadcastPackageVerified(verificationId, originUri, 1764 PackageManager.VERIFICATION_REJECT, user); 1765 } 1766 1767 Trace.asyncTraceEnd( 1768 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1769 1770 processPendingInstall(args, ret); 1771 mHandler.sendEmptyMessage(MCS_UNBIND); 1772 } 1773 break; 1774 } 1775 case PACKAGE_VERIFIED: { 1776 final int verificationId = msg.arg1; 1777 1778 final PackageVerificationState state = mPendingVerification.get(verificationId); 1779 if (state == null) { 1780 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1781 break; 1782 } 1783 1784 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1785 1786 state.setVerifierResponse(response.callerUid, response.code); 1787 1788 if (state.isVerificationComplete()) { 1789 mPendingVerification.remove(verificationId); 1790 1791 final InstallArgs args = state.getInstallArgs(); 1792 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1793 1794 int ret; 1795 if (state.isInstallAllowed()) { 1796 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1797 broadcastPackageVerified(verificationId, originUri, 1798 response.code, state.getInstallArgs().getUser()); 1799 try { 1800 ret = args.copyApk(mContainerService, true); 1801 } catch (RemoteException e) { 1802 Slog.e(TAG, "Could not contact the ContainerService"); 1803 } 1804 } else { 1805 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1806 } 1807 1808 Trace.asyncTraceEnd( 1809 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1810 1811 processPendingInstall(args, ret); 1812 mHandler.sendEmptyMessage(MCS_UNBIND); 1813 } 1814 1815 break; 1816 } 1817 case START_INTENT_FILTER_VERIFICATIONS: { 1818 IFVerificationParams params = (IFVerificationParams) msg.obj; 1819 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1820 params.replacing, params.pkg); 1821 break; 1822 } 1823 case INTENT_FILTER_VERIFIED: { 1824 final int verificationId = msg.arg1; 1825 1826 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1827 verificationId); 1828 if (state == null) { 1829 Slog.w(TAG, "Invalid IntentFilter verification token " 1830 + verificationId + " received"); 1831 break; 1832 } 1833 1834 final int userId = state.getUserId(); 1835 1836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1837 "Processing IntentFilter verification with token:" 1838 + verificationId + " and userId:" + userId); 1839 1840 final IntentFilterVerificationResponse response = 1841 (IntentFilterVerificationResponse) msg.obj; 1842 1843 state.setVerifierResponse(response.callerUid, response.code); 1844 1845 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1846 "IntentFilter verification with token:" + verificationId 1847 + " and userId:" + userId 1848 + " is settings verifier response with response code:" 1849 + response.code); 1850 1851 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1852 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1853 + response.getFailedDomainsString()); 1854 } 1855 1856 if (state.isVerificationComplete()) { 1857 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1858 } else { 1859 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1860 "IntentFilter verification with token:" + verificationId 1861 + " was not said to be complete"); 1862 } 1863 1864 break; 1865 } 1866 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1867 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1868 mInstantAppResolverConnection, 1869 (InstantAppRequest) msg.obj, 1870 mInstantAppInstallerActivity, 1871 mHandler); 1872 } 1873 } 1874 } 1875 } 1876 1877 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1878 @Override 1879 public void onGidsChanged(int appId, int userId) { 1880 mHandler.post(new Runnable() { 1881 @Override 1882 public void run() { 1883 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1884 } 1885 }); 1886 } 1887 @Override 1888 public void onPermissionGranted(int uid, int userId) { 1889 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1890 1891 // Not critical; if this is lost, the application has to request again. 1892 synchronized (mPackages) { 1893 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1894 } 1895 } 1896 @Override 1897 public void onInstallPermissionGranted() { 1898 synchronized (mPackages) { 1899 scheduleWriteSettingsLocked(); 1900 } 1901 } 1902 @Override 1903 public void onPermissionRevoked(int uid, int userId) { 1904 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1905 1906 synchronized (mPackages) { 1907 // Critical; after this call the application should never have the permission 1908 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1909 } 1910 1911 final int appId = UserHandle.getAppId(uid); 1912 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1913 } 1914 @Override 1915 public void onInstallPermissionRevoked() { 1916 synchronized (mPackages) { 1917 scheduleWriteSettingsLocked(); 1918 } 1919 } 1920 @Override 1921 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1922 synchronized (mPackages) { 1923 for (int userId : updatedUserIds) { 1924 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1925 } 1926 } 1927 } 1928 @Override 1929 public void onInstallPermissionUpdated() { 1930 synchronized (mPackages) { 1931 scheduleWriteSettingsLocked(); 1932 } 1933 } 1934 @Override 1935 public void onPermissionRemoved() { 1936 synchronized (mPackages) { 1937 mSettings.writeLPr(); 1938 } 1939 } 1940 }; 1941 1942 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1943 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1944 boolean launchedForRestore, String installerPackage, 1945 IPackageInstallObserver2 installObserver) { 1946 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1947 // Send the removed broadcasts 1948 if (res.removedInfo != null) { 1949 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1950 } 1951 1952 // Now that we successfully installed the package, grant runtime 1953 // permissions if requested before broadcasting the install. Also 1954 // for legacy apps in permission review mode we clear the permission 1955 // review flag which is used to emulate runtime permissions for 1956 // legacy apps. 1957 if (grantPermissions) { 1958 final int callingUid = Binder.getCallingUid(); 1959 mPermissionManager.grantRequestedRuntimePermissions( 1960 res.pkg, res.newUsers, grantedPermissions, callingUid, 1961 mPermissionCallback); 1962 } 1963 1964 final boolean update = res.removedInfo != null 1965 && res.removedInfo.removedPackage != null; 1966 final String installerPackageName = 1967 res.installerPackageName != null 1968 ? res.installerPackageName 1969 : res.removedInfo != null 1970 ? res.removedInfo.installerPackageName 1971 : null; 1972 1973 // If this is the first time we have child packages for a disabled privileged 1974 // app that had no children, we grant requested runtime permissions to the new 1975 // children if the parent on the system image had them already granted. 1976 if (res.pkg.parentPackage != null) { 1977 final int callingUid = Binder.getCallingUid(); 1978 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1979 res.pkg, callingUid, mPermissionCallback); 1980 } 1981 1982 synchronized (mPackages) { 1983 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1984 } 1985 1986 final String packageName = res.pkg.applicationInfo.packageName; 1987 1988 // Determine the set of users who are adding this package for 1989 // the first time vs. those who are seeing an update. 1990 int[] firstUserIds = EMPTY_INT_ARRAY; 1991 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1992 int[] updateUserIds = EMPTY_INT_ARRAY; 1993 int[] instantUserIds = EMPTY_INT_ARRAY; 1994 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1995 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1996 for (int newUser : res.newUsers) { 1997 final boolean isInstantApp = ps.getInstantApp(newUser); 1998 if (allNewUsers) { 1999 if (isInstantApp) { 2000 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2001 } else { 2002 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2003 } 2004 continue; 2005 } 2006 boolean isNew = true; 2007 for (int origUser : res.origUsers) { 2008 if (origUser == newUser) { 2009 isNew = false; 2010 break; 2011 } 2012 } 2013 if (isNew) { 2014 if (isInstantApp) { 2015 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2016 } else { 2017 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2018 } 2019 } else { 2020 if (isInstantApp) { 2021 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2022 } else { 2023 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2024 } 2025 } 2026 } 2027 2028 // Send installed broadcasts if the package is not a static shared lib. 2029 if (res.pkg.staticSharedLibName == null) { 2030 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2031 2032 // Send added for users that see the package for the first time 2033 // sendPackageAddedForNewUsers also deals with system apps 2034 int appId = UserHandle.getAppId(res.uid); 2035 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2036 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2037 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2038 2039 // Send added for users that don't see the package for the first time 2040 Bundle extras = new Bundle(1); 2041 extras.putInt(Intent.EXTRA_UID, res.uid); 2042 if (update) { 2043 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2044 } 2045 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2046 extras, 0 /*flags*/, 2047 null /*targetPackage*/, null /*finishedReceiver*/, 2048 updateUserIds, instantUserIds); 2049 if (installerPackageName != null) { 2050 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2051 extras, 0 /*flags*/, 2052 installerPackageName, null /*finishedReceiver*/, 2053 updateUserIds, instantUserIds); 2054 } 2055 2056 // Send replaced for users that don't see the package for the first time 2057 if (update) { 2058 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2059 packageName, extras, 0 /*flags*/, 2060 null /*targetPackage*/, null /*finishedReceiver*/, 2061 updateUserIds, instantUserIds); 2062 if (installerPackageName != null) { 2063 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2064 extras, 0 /*flags*/, 2065 installerPackageName, null /*finishedReceiver*/, 2066 updateUserIds, instantUserIds); 2067 } 2068 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2069 null /*package*/, null /*extras*/, 0 /*flags*/, 2070 packageName /*targetPackage*/, 2071 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2072 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2073 // First-install and we did a restore, so we're responsible for the 2074 // first-launch broadcast. 2075 if (DEBUG_BACKUP) { 2076 Slog.i(TAG, "Post-restore of " + packageName 2077 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2078 } 2079 sendFirstLaunchBroadcast(packageName, installerPackage, 2080 firstUserIds, firstInstantUserIds); 2081 } 2082 2083 // Send broadcast package appeared if forward locked/external for all users 2084 // treat asec-hosted packages like removable media on upgrade 2085 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2086 if (DEBUG_INSTALL) { 2087 Slog.i(TAG, "upgrading pkg " + res.pkg 2088 + " is ASEC-hosted -> AVAILABLE"); 2089 } 2090 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2091 ArrayList<String> pkgList = new ArrayList<>(1); 2092 pkgList.add(packageName); 2093 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2094 } 2095 } 2096 2097 // Work that needs to happen on first install within each user 2098 if (firstUserIds != null && firstUserIds.length > 0) { 2099 synchronized (mPackages) { 2100 for (int userId : firstUserIds) { 2101 // If this app is a browser and it's newly-installed for some 2102 // users, clear any default-browser state in those users. The 2103 // app's nature doesn't depend on the user, so we can just check 2104 // its browser nature in any user and generalize. 2105 if (packageIsBrowser(packageName, userId)) { 2106 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2107 } 2108 2109 // We may also need to apply pending (restored) runtime 2110 // permission grants within these users. 2111 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2112 } 2113 } 2114 } 2115 2116 if (allNewUsers && !update) { 2117 notifyPackageAdded(packageName); 2118 } 2119 2120 // Log current value of "unknown sources" setting 2121 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2122 getUnknownSourcesSettings()); 2123 2124 // Remove the replaced package's older resources safely now 2125 // We delete after a gc for applications on sdcard. 2126 if (res.removedInfo != null && res.removedInfo.args != null) { 2127 Runtime.getRuntime().gc(); 2128 synchronized (mInstallLock) { 2129 res.removedInfo.args.doPostDeleteLI(true); 2130 } 2131 } else { 2132 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2133 // and not block here. 2134 VMRuntime.getRuntime().requestConcurrentGC(); 2135 } 2136 2137 // Notify DexManager that the package was installed for new users. 2138 // The updated users should already be indexed and the package code paths 2139 // should not change. 2140 // Don't notify the manager for ephemeral apps as they are not expected to 2141 // survive long enough to benefit of background optimizations. 2142 for (int userId : firstUserIds) { 2143 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2144 // There's a race currently where some install events may interleave with an uninstall. 2145 // This can lead to package info being null (b/36642664). 2146 if (info != null) { 2147 mDexManager.notifyPackageInstalled(info, userId); 2148 } 2149 } 2150 } 2151 2152 // If someone is watching installs - notify them 2153 if (installObserver != null) { 2154 try { 2155 Bundle extras = extrasForInstallResult(res); 2156 installObserver.onPackageInstalled(res.name, res.returnCode, 2157 res.returnMsg, extras); 2158 } catch (RemoteException e) { 2159 Slog.i(TAG, "Observer no longer exists."); 2160 } 2161 } 2162 } 2163 2164 private StorageEventListener mStorageListener = new StorageEventListener() { 2165 @Override 2166 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2167 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2168 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2169 final String volumeUuid = vol.getFsUuid(); 2170 2171 // Clean up any users or apps that were removed or recreated 2172 // while this volume was missing 2173 sUserManager.reconcileUsers(volumeUuid); 2174 reconcileApps(volumeUuid); 2175 2176 // Clean up any install sessions that expired or were 2177 // cancelled while this volume was missing 2178 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2179 2180 loadPrivatePackages(vol); 2181 2182 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2183 unloadPrivatePackages(vol); 2184 } 2185 } 2186 } 2187 2188 @Override 2189 public void onVolumeForgotten(String fsUuid) { 2190 if (TextUtils.isEmpty(fsUuid)) { 2191 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2192 return; 2193 } 2194 2195 // Remove any apps installed on the forgotten volume 2196 synchronized (mPackages) { 2197 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2198 for (PackageSetting ps : packages) { 2199 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2200 deletePackageVersioned(new VersionedPackage(ps.name, 2201 PackageManager.VERSION_CODE_HIGHEST), 2202 new LegacyPackageDeleteObserver(null).getBinder(), 2203 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2204 // Try very hard to release any references to this package 2205 // so we don't risk the system server being killed due to 2206 // open FDs 2207 AttributeCache.instance().removePackage(ps.name); 2208 } 2209 2210 mSettings.onVolumeForgotten(fsUuid); 2211 mSettings.writeLPr(); 2212 } 2213 } 2214 }; 2215 2216 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2217 Bundle extras = null; 2218 switch (res.returnCode) { 2219 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2220 extras = new Bundle(); 2221 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2222 res.origPermission); 2223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2224 res.origPackage); 2225 break; 2226 } 2227 case PackageManager.INSTALL_SUCCEEDED: { 2228 extras = new Bundle(); 2229 extras.putBoolean(Intent.EXTRA_REPLACING, 2230 res.removedInfo != null && res.removedInfo.removedPackage != null); 2231 break; 2232 } 2233 } 2234 return extras; 2235 } 2236 2237 void scheduleWriteSettingsLocked() { 2238 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2239 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2240 } 2241 } 2242 2243 void scheduleWritePackageListLocked(int userId) { 2244 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2245 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2246 msg.arg1 = userId; 2247 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2248 } 2249 } 2250 2251 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2252 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2253 scheduleWritePackageRestrictionsLocked(userId); 2254 } 2255 2256 void scheduleWritePackageRestrictionsLocked(int userId) { 2257 final int[] userIds = (userId == UserHandle.USER_ALL) 2258 ? sUserManager.getUserIds() : new int[]{userId}; 2259 for (int nextUserId : userIds) { 2260 if (!sUserManager.exists(nextUserId)) return; 2261 mDirtyUsers.add(nextUserId); 2262 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2263 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2264 } 2265 } 2266 } 2267 2268 public static PackageManagerService main(Context context, Installer installer, 2269 boolean factoryTest, boolean onlyCore) { 2270 // Self-check for initial settings. 2271 PackageManagerServiceCompilerMapping.checkProperties(); 2272 2273 PackageManagerService m = new PackageManagerService(context, installer, 2274 factoryTest, onlyCore); 2275 m.enableSystemUserPackages(); 2276 ServiceManager.addService("package", m); 2277 final PackageManagerNative pmn = m.new PackageManagerNative(); 2278 ServiceManager.addService("package_native", pmn); 2279 return m; 2280 } 2281 2282 private void enableSystemUserPackages() { 2283 if (!UserManager.isSplitSystemUser()) { 2284 return; 2285 } 2286 // For system user, enable apps based on the following conditions: 2287 // - app is whitelisted or belong to one of these groups: 2288 // -- system app which has no launcher icons 2289 // -- system app which has INTERACT_ACROSS_USERS permission 2290 // -- system IME app 2291 // - app is not in the blacklist 2292 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2293 Set<String> enableApps = new ArraySet<>(); 2294 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2295 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2296 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2297 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2298 enableApps.addAll(wlApps); 2299 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2300 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2301 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2302 enableApps.removeAll(blApps); 2303 Log.i(TAG, "Applications installed for system user: " + enableApps); 2304 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2305 UserHandle.SYSTEM); 2306 final int allAppsSize = allAps.size(); 2307 synchronized (mPackages) { 2308 for (int i = 0; i < allAppsSize; i++) { 2309 String pName = allAps.get(i); 2310 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2311 // Should not happen, but we shouldn't be failing if it does 2312 if (pkgSetting == null) { 2313 continue; 2314 } 2315 boolean install = enableApps.contains(pName); 2316 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2317 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2318 + " for system user"); 2319 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2320 } 2321 } 2322 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2323 } 2324 } 2325 2326 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2327 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2328 Context.DISPLAY_SERVICE); 2329 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2330 } 2331 2332 /** 2333 * Requests that files preopted on a secondary system partition be copied to the data partition 2334 * if possible. Note that the actual copying of the files is accomplished by init for security 2335 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2336 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2337 */ 2338 private static void requestCopyPreoptedFiles() { 2339 final int WAIT_TIME_MS = 100; 2340 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2341 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2342 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2343 // We will wait for up to 100 seconds. 2344 final long timeStart = SystemClock.uptimeMillis(); 2345 final long timeEnd = timeStart + 100 * 1000; 2346 long timeNow = timeStart; 2347 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2348 try { 2349 Thread.sleep(WAIT_TIME_MS); 2350 } catch (InterruptedException e) { 2351 // Do nothing 2352 } 2353 timeNow = SystemClock.uptimeMillis(); 2354 if (timeNow > timeEnd) { 2355 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2356 Slog.wtf(TAG, "cppreopt did not finish!"); 2357 break; 2358 } 2359 } 2360 2361 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2362 } 2363 } 2364 2365 public PackageManagerService(Context context, Installer installer, 2366 boolean factoryTest, boolean onlyCore) { 2367 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2368 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2370 SystemClock.uptimeMillis()); 2371 2372 if (mSdkVersion <= 0) { 2373 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2374 } 2375 2376 mContext = context; 2377 2378 mFactoryTest = factoryTest; 2379 mOnlyCore = onlyCore; 2380 mMetrics = new DisplayMetrics(); 2381 mInstaller = installer; 2382 2383 // Create sub-components that provide services / data. Order here is important. 2384 synchronized (mInstallLock) { 2385 synchronized (mPackages) { 2386 // Expose private service for system components to use. 2387 LocalServices.addService( 2388 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2389 sUserManager = new UserManagerService(context, this, 2390 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2391 mPermissionManager = PermissionManagerService.create(context, 2392 new DefaultPermissionGrantedCallback() { 2393 @Override 2394 public void onDefaultRuntimePermissionsGranted(int userId) { 2395 synchronized(mPackages) { 2396 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2397 } 2398 } 2399 }, mPackages /*externalLock*/); 2400 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2401 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2402 } 2403 } 2404 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2407 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2408 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2409 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2410 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2411 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2412 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2413 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2414 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2415 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2416 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2417 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2418 2419 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2420 if (separateProcesses != null && separateProcesses.length() > 0) { 2421 if ("*".equals(separateProcesses)) { 2422 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2423 mSeparateProcesses = null; 2424 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2425 } else { 2426 mDefParseFlags = 0; 2427 mSeparateProcesses = separateProcesses.split(","); 2428 Slog.w(TAG, "Running with debug.separate_processes: " 2429 + separateProcesses); 2430 } 2431 } else { 2432 mDefParseFlags = 0; 2433 mSeparateProcesses = null; 2434 } 2435 2436 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2437 "*dexopt*"); 2438 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2439 installer, mInstallLock); 2440 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2441 dexManagerListener); 2442 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2443 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2444 2445 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2446 FgThread.get().getLooper()); 2447 2448 getDefaultDisplayMetrics(context, mMetrics); 2449 2450 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2451 SystemConfig systemConfig = SystemConfig.getInstance(); 2452 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2453 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2454 2455 mProtectedPackages = new ProtectedPackages(mContext); 2456 2457 synchronized (mInstallLock) { 2458 // writer 2459 synchronized (mPackages) { 2460 mHandlerThread = new ServiceThread(TAG, 2461 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2462 mHandlerThread.start(); 2463 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2464 mProcessLoggingHandler = new ProcessLoggingHandler(); 2465 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2466 mInstantAppRegistry = new InstantAppRegistry(this); 2467 2468 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2469 final int builtInLibCount = libConfig.size(); 2470 for (int i = 0; i < builtInLibCount; i++) { 2471 String name = libConfig.keyAt(i); 2472 String path = libConfig.valueAt(i); 2473 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2474 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2475 } 2476 2477 SELinuxMMAC.readInstallPolicy(); 2478 2479 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2480 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2482 2483 // Clean up orphaned packages for which the code path doesn't exist 2484 // and they are an update to a system app - caused by bug/32321269 2485 final int packageSettingCount = mSettings.mPackages.size(); 2486 for (int i = packageSettingCount - 1; i >= 0; i--) { 2487 PackageSetting ps = mSettings.mPackages.valueAt(i); 2488 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2489 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2490 mSettings.mPackages.removeAt(i); 2491 mSettings.enableSystemPackageLPw(ps.name); 2492 } 2493 } 2494 2495 if (mFirstBoot) { 2496 requestCopyPreoptedFiles(); 2497 } 2498 2499 String customResolverActivity = Resources.getSystem().getString( 2500 R.string.config_customResolverActivity); 2501 if (TextUtils.isEmpty(customResolverActivity)) { 2502 customResolverActivity = null; 2503 } else { 2504 mCustomResolverComponentName = ComponentName.unflattenFromString( 2505 customResolverActivity); 2506 } 2507 2508 long startTime = SystemClock.uptimeMillis(); 2509 2510 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2511 startTime); 2512 2513 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2514 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2515 2516 if (bootClassPath == null) { 2517 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2518 } 2519 2520 if (systemServerClassPath == null) { 2521 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2522 } 2523 2524 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2525 2526 final VersionInfo ver = mSettings.getInternalVersion(); 2527 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2528 if (mIsUpgrade) { 2529 logCriticalInfo(Log.INFO, 2530 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2531 } 2532 2533 // when upgrading from pre-M, promote system app permissions from install to runtime 2534 mPromoteSystemApps = 2535 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2536 2537 // When upgrading from pre-N, we need to handle package extraction like first boot, 2538 // as there is no profiling data available. 2539 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2540 2541 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2542 2543 // save off the names of pre-existing system packages prior to scanning; we don't 2544 // want to automatically grant runtime permissions for new system apps 2545 if (mPromoteSystemApps) { 2546 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2547 while (pkgSettingIter.hasNext()) { 2548 PackageSetting ps = pkgSettingIter.next(); 2549 if (isSystemApp(ps)) { 2550 mExistingSystemPackages.add(ps.name); 2551 } 2552 } 2553 } 2554 2555 mCacheDir = preparePackageParserCache(mIsUpgrade); 2556 2557 // Set flag to monitor and not change apk file paths when 2558 // scanning install directories. 2559 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2560 2561 if (mIsUpgrade || mFirstBoot) { 2562 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2563 } 2564 2565 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2566 // For security and version matching reason, only consider 2567 // overlay packages if they reside in the right directory. 2568 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2569 mDefParseFlags 2570 | PackageParser.PARSE_IS_SYSTEM_DIR, 2571 scanFlags 2572 | SCAN_AS_SYSTEM 2573 | SCAN_AS_VENDOR, 2574 0); 2575 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2576 mDefParseFlags 2577 | PackageParser.PARSE_IS_SYSTEM_DIR, 2578 scanFlags 2579 | SCAN_AS_SYSTEM 2580 | SCAN_AS_PRODUCT, 2581 0); 2582 2583 mParallelPackageParserCallback.findStaticOverlayPackages(); 2584 2585 // Find base frameworks (resource packages without code). 2586 scanDirTracedLI(frameworkDir, 2587 mDefParseFlags 2588 | PackageParser.PARSE_IS_SYSTEM_DIR, 2589 scanFlags 2590 | SCAN_NO_DEX 2591 | SCAN_AS_SYSTEM 2592 | SCAN_AS_PRIVILEGED, 2593 0); 2594 2595 // Collected privileged system packages. 2596 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2597 scanDirTracedLI(privilegedAppDir, 2598 mDefParseFlags 2599 | PackageParser.PARSE_IS_SYSTEM_DIR, 2600 scanFlags 2601 | SCAN_AS_SYSTEM 2602 | SCAN_AS_PRIVILEGED, 2603 0); 2604 2605 // Collect ordinary system packages. 2606 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2607 scanDirTracedLI(systemAppDir, 2608 mDefParseFlags 2609 | PackageParser.PARSE_IS_SYSTEM_DIR, 2610 scanFlags 2611 | SCAN_AS_SYSTEM, 2612 0); 2613 2614 // Collected privileged vendor packages. 2615 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2616 try { 2617 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2618 } catch (IOException e) { 2619 // failed to look up canonical path, continue with original one 2620 } 2621 scanDirTracedLI(privilegedVendorAppDir, 2622 mDefParseFlags 2623 | PackageParser.PARSE_IS_SYSTEM_DIR, 2624 scanFlags 2625 | SCAN_AS_SYSTEM 2626 | SCAN_AS_VENDOR 2627 | SCAN_AS_PRIVILEGED, 2628 0); 2629 2630 // Collect ordinary vendor packages. 2631 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2632 try { 2633 vendorAppDir = vendorAppDir.getCanonicalFile(); 2634 } catch (IOException e) { 2635 // failed to look up canonical path, continue with original one 2636 } 2637 scanDirTracedLI(vendorAppDir, 2638 mDefParseFlags 2639 | PackageParser.PARSE_IS_SYSTEM_DIR, 2640 scanFlags 2641 | SCAN_AS_SYSTEM 2642 | SCAN_AS_VENDOR, 2643 0); 2644 2645 // Collect all OEM packages. 2646 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2647 scanDirTracedLI(oemAppDir, 2648 mDefParseFlags 2649 | PackageParser.PARSE_IS_SYSTEM_DIR, 2650 scanFlags 2651 | SCAN_AS_SYSTEM 2652 | SCAN_AS_OEM, 2653 0); 2654 2655 // Collected privileged product packages. 2656 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2657 try { 2658 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2659 } catch (IOException e) { 2660 // failed to look up canonical path, continue with original one 2661 } 2662 scanDirTracedLI(privilegedProductAppDir, 2663 mDefParseFlags 2664 | PackageParser.PARSE_IS_SYSTEM_DIR, 2665 scanFlags 2666 | SCAN_AS_SYSTEM 2667 | SCAN_AS_PRODUCT 2668 | SCAN_AS_PRIVILEGED, 2669 0); 2670 2671 // Collect ordinary product packages. 2672 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2673 try { 2674 productAppDir = productAppDir.getCanonicalFile(); 2675 } catch (IOException e) { 2676 // failed to look up canonical path, continue with original one 2677 } 2678 scanDirTracedLI(productAppDir, 2679 mDefParseFlags 2680 | PackageParser.PARSE_IS_SYSTEM_DIR, 2681 scanFlags 2682 | SCAN_AS_SYSTEM 2683 | SCAN_AS_PRODUCT, 2684 0); 2685 2686 // Prune any system packages that no longer exist. 2687 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2688 // Stub packages must either be replaced with full versions in the /data 2689 // partition or be disabled. 2690 final List<String> stubSystemApps = new ArrayList<>(); 2691 if (!mOnlyCore) { 2692 // do this first before mucking with mPackages for the "expecting better" case 2693 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2694 while (pkgIterator.hasNext()) { 2695 final PackageParser.Package pkg = pkgIterator.next(); 2696 if (pkg.isStub) { 2697 stubSystemApps.add(pkg.packageName); 2698 } 2699 } 2700 2701 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2702 while (psit.hasNext()) { 2703 PackageSetting ps = psit.next(); 2704 2705 /* 2706 * If this is not a system app, it can't be a 2707 * disable system app. 2708 */ 2709 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2710 continue; 2711 } 2712 2713 /* 2714 * If the package is scanned, it's not erased. 2715 */ 2716 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2717 if (scannedPkg != null) { 2718 /* 2719 * If the system app is both scanned and in the 2720 * disabled packages list, then it must have been 2721 * added via OTA. Remove it from the currently 2722 * scanned package so the previously user-installed 2723 * application can be scanned. 2724 */ 2725 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2726 logCriticalInfo(Log.WARN, 2727 "Expecting better updated system app for " + ps.name 2728 + "; removing system app. Last known" 2729 + " codePath=" + ps.codePathString 2730 + ", versionCode=" + ps.versionCode 2731 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2732 removePackageLI(scannedPkg, true); 2733 mExpectingBetter.put(ps.name, ps.codePath); 2734 } 2735 2736 continue; 2737 } 2738 2739 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2740 psit.remove(); 2741 logCriticalInfo(Log.WARN, "System package " + ps.name 2742 + " no longer exists; it's data will be wiped"); 2743 // Actual deletion of code and data will be handled by later 2744 // reconciliation step 2745 } else { 2746 // we still have a disabled system package, but, it still might have 2747 // been removed. check the code path still exists and check there's 2748 // still a package. the latter can happen if an OTA keeps the same 2749 // code path, but, changes the package name. 2750 final PackageSetting disabledPs = 2751 mSettings.getDisabledSystemPkgLPr(ps.name); 2752 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2753 || disabledPs.pkg == null) { 2754 possiblyDeletedUpdatedSystemApps.add(ps.name); 2755 } 2756 } 2757 } 2758 } 2759 2760 //delete tmp files 2761 deleteTempPackageFiles(); 2762 2763 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2764 2765 // Remove any shared userIDs that have no associated packages 2766 mSettings.pruneSharedUsersLPw(); 2767 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2768 final int systemPackagesCount = mPackages.size(); 2769 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2770 + " ms, packageCount: " + systemPackagesCount 2771 + " , timePerPackage: " 2772 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2773 + " , cached: " + cachedSystemApps); 2774 if (mIsUpgrade && systemPackagesCount > 0) { 2775 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2776 ((int) systemScanTime) / systemPackagesCount); 2777 } 2778 if (!mOnlyCore) { 2779 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2780 SystemClock.uptimeMillis()); 2781 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2782 2783 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2784 | PackageParser.PARSE_FORWARD_LOCK, 2785 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2786 2787 // Remove disable package settings for updated system apps that were 2788 // removed via an OTA. If the update is no longer present, remove the 2789 // app completely. Otherwise, revoke their system privileges. 2790 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2791 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2792 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2793 final String msg; 2794 if (deletedPkg == null) { 2795 // should have found an update, but, we didn't; remove everything 2796 msg = "Updated system package " + deletedAppName 2797 + " no longer exists; removing its data"; 2798 // Actual deletion of code and data will be handled by later 2799 // reconciliation step 2800 } else { 2801 // found an update; revoke system privileges 2802 msg = "Updated system package + " + deletedAppName 2803 + " no longer exists; revoking system privileges"; 2804 2805 // Don't do anything if a stub is removed from the system image. If 2806 // we were to remove the uncompressed version from the /data partition, 2807 // this is where it'd be done. 2808 2809 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2810 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2811 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2812 } 2813 logCriticalInfo(Log.WARN, msg); 2814 } 2815 2816 /* 2817 * Make sure all system apps that we expected to appear on 2818 * the userdata partition actually showed up. If they never 2819 * appeared, crawl back and revive the system version. 2820 */ 2821 for (int i = 0; i < mExpectingBetter.size(); i++) { 2822 final String packageName = mExpectingBetter.keyAt(i); 2823 if (!mPackages.containsKey(packageName)) { 2824 final File scanFile = mExpectingBetter.valueAt(i); 2825 2826 logCriticalInfo(Log.WARN, "Expected better " + packageName 2827 + " but never showed up; reverting to system"); 2828 2829 final @ParseFlags int reparseFlags; 2830 final @ScanFlags int rescanFlags; 2831 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2832 reparseFlags = 2833 mDefParseFlags | 2834 PackageParser.PARSE_IS_SYSTEM_DIR; 2835 rescanFlags = 2836 scanFlags 2837 | SCAN_AS_SYSTEM 2838 | SCAN_AS_PRIVILEGED; 2839 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2840 reparseFlags = 2841 mDefParseFlags | 2842 PackageParser.PARSE_IS_SYSTEM_DIR; 2843 rescanFlags = 2844 scanFlags 2845 | SCAN_AS_SYSTEM; 2846 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2847 reparseFlags = 2848 mDefParseFlags | 2849 PackageParser.PARSE_IS_SYSTEM_DIR; 2850 rescanFlags = 2851 scanFlags 2852 | SCAN_AS_SYSTEM 2853 | SCAN_AS_VENDOR 2854 | SCAN_AS_PRIVILEGED; 2855 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2856 reparseFlags = 2857 mDefParseFlags | 2858 PackageParser.PARSE_IS_SYSTEM_DIR; 2859 rescanFlags = 2860 scanFlags 2861 | SCAN_AS_SYSTEM 2862 | SCAN_AS_VENDOR; 2863 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2864 reparseFlags = 2865 mDefParseFlags | 2866 PackageParser.PARSE_IS_SYSTEM_DIR; 2867 rescanFlags = 2868 scanFlags 2869 | SCAN_AS_SYSTEM 2870 | SCAN_AS_OEM; 2871 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2872 reparseFlags = 2873 mDefParseFlags | 2874 PackageParser.PARSE_IS_SYSTEM_DIR; 2875 rescanFlags = 2876 scanFlags 2877 | SCAN_AS_SYSTEM 2878 | SCAN_AS_PRODUCT 2879 | SCAN_AS_PRIVILEGED; 2880 } else if (FileUtils.contains(productAppDir, scanFile)) { 2881 reparseFlags = 2882 mDefParseFlags | 2883 PackageParser.PARSE_IS_SYSTEM_DIR; 2884 rescanFlags = 2885 scanFlags 2886 | SCAN_AS_SYSTEM 2887 | SCAN_AS_PRODUCT; 2888 } else { 2889 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2890 continue; 2891 } 2892 2893 mSettings.enableSystemPackageLPw(packageName); 2894 2895 try { 2896 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2897 } catch (PackageManagerException e) { 2898 Slog.e(TAG, "Failed to parse original system package: " 2899 + e.getMessage()); 2900 } 2901 } 2902 } 2903 2904 // Uncompress and install any stubbed system applications. 2905 // This must be done last to ensure all stubs are replaced or disabled. 2906 decompressSystemApplications(stubSystemApps, scanFlags); 2907 2908 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2909 - cachedSystemApps; 2910 2911 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2912 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2913 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2914 + " ms, packageCount: " + dataPackagesCount 2915 + " , timePerPackage: " 2916 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2917 + " , cached: " + cachedNonSystemApps); 2918 if (mIsUpgrade && dataPackagesCount > 0) { 2919 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2920 ((int) dataScanTime) / dataPackagesCount); 2921 } 2922 } 2923 mExpectingBetter.clear(); 2924 2925 // Resolve the storage manager. 2926 mStorageManagerPackage = getStorageManagerPackageName(); 2927 2928 // Resolve protected action filters. Only the setup wizard is allowed to 2929 // have a high priority filter for these actions. 2930 mSetupWizardPackage = getSetupWizardPackageName(); 2931 if (mProtectedFilters.size() > 0) { 2932 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2933 Slog.i(TAG, "No setup wizard;" 2934 + " All protected intents capped to priority 0"); 2935 } 2936 for (ActivityIntentInfo filter : mProtectedFilters) { 2937 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2938 if (DEBUG_FILTERS) { 2939 Slog.i(TAG, "Found setup wizard;" 2940 + " allow priority " + filter.getPriority() + ";" 2941 + " package: " + filter.activity.info.packageName 2942 + " activity: " + filter.activity.className 2943 + " priority: " + filter.getPriority()); 2944 } 2945 // skip setup wizard; allow it to keep the high priority filter 2946 continue; 2947 } 2948 if (DEBUG_FILTERS) { 2949 Slog.i(TAG, "Protected action; cap priority to 0;" 2950 + " package: " + filter.activity.info.packageName 2951 + " activity: " + filter.activity.className 2952 + " origPrio: " + filter.getPriority()); 2953 } 2954 filter.setPriority(0); 2955 } 2956 } 2957 2958 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 2959 2960 mDeferProtectedFilters = false; 2961 mProtectedFilters.clear(); 2962 2963 // Now that we know all of the shared libraries, update all clients to have 2964 // the correct library paths. 2965 updateAllSharedLibrariesLPw(null); 2966 2967 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2968 // NOTE: We ignore potential failures here during a system scan (like 2969 // the rest of the commands above) because there's precious little we 2970 // can do about it. A settings error is reported, though. 2971 final List<String> changedAbiCodePath = 2972 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2973 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2974 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2975 final String codePathString = changedAbiCodePath.get(i); 2976 try { 2977 mInstaller.rmdex(codePathString, 2978 getDexCodeInstructionSet(getPreferredInstructionSet())); 2979 } catch (InstallerException ignored) { 2980 } 2981 } 2982 } 2983 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 2984 // SELinux domain. 2985 setting.fixSeInfoLocked(); 2986 } 2987 2988 // Now that we know all the packages we are keeping, 2989 // read and update their last usage times. 2990 mPackageUsage.read(mPackages); 2991 mCompilerStats.read(); 2992 2993 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2994 SystemClock.uptimeMillis()); 2995 Slog.i(TAG, "Time to scan packages: " 2996 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2997 + " seconds"); 2998 2999 // If the platform SDK has changed since the last time we booted, 3000 // we need to re-grant app permission to catch any new ones that 3001 // appear. This is really a hack, and means that apps can in some 3002 // cases get permissions that the user didn't initially explicitly 3003 // allow... it would be nice to have some better way to handle 3004 // this situation. 3005 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3006 if (sdkUpdated) { 3007 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3008 + mSdkVersion + "; regranting permissions for internal storage"); 3009 } 3010 mPermissionManager.updateAllPermissions( 3011 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3012 mPermissionCallback); 3013 ver.sdkVersion = mSdkVersion; 3014 3015 // If this is the first boot or an update from pre-M, and it is a normal 3016 // boot, then we need to initialize the default preferred apps across 3017 // all defined users. 3018 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3019 for (UserInfo user : sUserManager.getUsers(true)) { 3020 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3021 applyFactoryDefaultBrowserLPw(user.id); 3022 primeDomainVerificationsLPw(user.id); 3023 } 3024 } 3025 3026 // Prepare storage for system user really early during boot, 3027 // since core system apps like SettingsProvider and SystemUI 3028 // can't wait for user to start 3029 final int storageFlags; 3030 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3031 storageFlags = StorageManager.FLAG_STORAGE_DE; 3032 } else { 3033 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3034 } 3035 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3036 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3037 true /* onlyCoreApps */); 3038 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3039 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3040 Trace.TRACE_TAG_PACKAGE_MANAGER); 3041 traceLog.traceBegin("AppDataFixup"); 3042 try { 3043 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3044 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3045 } catch (InstallerException e) { 3046 Slog.w(TAG, "Trouble fixing GIDs", e); 3047 } 3048 traceLog.traceEnd(); 3049 3050 traceLog.traceBegin("AppDataPrepare"); 3051 if (deferPackages == null || deferPackages.isEmpty()) { 3052 return; 3053 } 3054 int count = 0; 3055 for (String pkgName : deferPackages) { 3056 PackageParser.Package pkg = null; 3057 synchronized (mPackages) { 3058 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3059 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3060 pkg = ps.pkg; 3061 } 3062 } 3063 if (pkg != null) { 3064 synchronized (mInstallLock) { 3065 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3066 true /* maybeMigrateAppData */); 3067 } 3068 count++; 3069 } 3070 } 3071 traceLog.traceEnd(); 3072 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3073 }, "prepareAppData"); 3074 3075 // If this is first boot after an OTA, and a normal boot, then 3076 // we need to clear code cache directories. 3077 // Note that we do *not* clear the application profiles. These remain valid 3078 // across OTAs and are used to drive profile verification (post OTA) and 3079 // profile compilation (without waiting to collect a fresh set of profiles). 3080 if (mIsUpgrade && !onlyCore) { 3081 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3082 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3083 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3084 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3085 // No apps are running this early, so no need to freeze 3086 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3087 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3088 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3089 } 3090 } 3091 ver.fingerprint = Build.FINGERPRINT; 3092 } 3093 3094 checkDefaultBrowser(); 3095 3096 // clear only after permissions and other defaults have been updated 3097 mExistingSystemPackages.clear(); 3098 mPromoteSystemApps = false; 3099 3100 // All the changes are done during package scanning. 3101 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3102 3103 // can downgrade to reader 3104 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3105 mSettings.writeLPr(); 3106 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3107 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3108 SystemClock.uptimeMillis()); 3109 3110 if (!mOnlyCore) { 3111 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3112 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3113 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3114 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3115 if (mIntentFilterVerifierComponent != null) { 3116 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3117 mIntentFilterVerifierComponent); 3118 } else { 3119 mIntentFilterVerifier = null; 3120 } 3121 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3122 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3123 SharedLibraryInfo.VERSION_UNDEFINED); 3124 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3125 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3126 SharedLibraryInfo.VERSION_UNDEFINED); 3127 } else { 3128 mRequiredVerifierPackage = null; 3129 mRequiredInstallerPackage = null; 3130 mRequiredUninstallerPackage = null; 3131 mIntentFilterVerifierComponent = null; 3132 mIntentFilterVerifier = null; 3133 mServicesSystemSharedLibraryPackageName = null; 3134 mSharedSystemSharedLibraryPackageName = null; 3135 } 3136 3137 mInstallerService = new PackageInstallerService(context, this); 3138 final Pair<ComponentName, String> instantAppResolverComponent = 3139 getInstantAppResolverLPr(); 3140 if (instantAppResolverComponent != null) { 3141 if (DEBUG_INSTANT) { 3142 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3143 } 3144 mInstantAppResolverConnection = new InstantAppResolverConnection( 3145 mContext, instantAppResolverComponent.first, 3146 instantAppResolverComponent.second); 3147 mInstantAppResolverSettingsComponent = 3148 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3149 } else { 3150 mInstantAppResolverConnection = null; 3151 mInstantAppResolverSettingsComponent = null; 3152 } 3153 updateInstantAppInstallerLocked(null); 3154 3155 // Read and update the usage of dex files. 3156 // Do this at the end of PM init so that all the packages have their 3157 // data directory reconciled. 3158 // At this point we know the code paths of the packages, so we can validate 3159 // the disk file and build the internal cache. 3160 // The usage file is expected to be small so loading and verifying it 3161 // should take a fairly small time compare to the other activities (e.g. package 3162 // scanning). 3163 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3164 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3165 for (int userId : currentUserIds) { 3166 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3167 } 3168 mDexManager.load(userPackages); 3169 if (mIsUpgrade) { 3170 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3171 (int) (SystemClock.uptimeMillis() - startTime)); 3172 } 3173 } // synchronized (mPackages) 3174 } // synchronized (mInstallLock) 3175 3176 // Now after opening every single application zip, make sure they 3177 // are all flushed. Not really needed, but keeps things nice and 3178 // tidy. 3179 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3180 Runtime.getRuntime().gc(); 3181 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3182 3183 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3184 FallbackCategoryProvider.loadFallbacks(); 3185 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3186 3187 // The initial scanning above does many calls into installd while 3188 // holding the mPackages lock, but we're mostly interested in yelling 3189 // once we have a booted system. 3190 mInstaller.setWarnIfHeld(mPackages); 3191 3192 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3193 } 3194 3195 /** 3196 * Uncompress and install stub applications. 3197 * <p>In order to save space on the system partition, some applications are shipped in a 3198 * compressed form. In addition the compressed bits for the full application, the 3199 * system image contains a tiny stub comprised of only the Android manifest. 3200 * <p>During the first boot, attempt to uncompress and install the full application. If 3201 * the application can't be installed for any reason, disable the stub and prevent 3202 * uncompressing the full application during future boots. 3203 * <p>In order to forcefully attempt an installation of a full application, go to app 3204 * settings and enable the application. 3205 */ 3206 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3207 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3208 final String pkgName = stubSystemApps.get(i); 3209 // skip if the system package is already disabled 3210 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3211 stubSystemApps.remove(i); 3212 continue; 3213 } 3214 // skip if the package isn't installed (?!); this should never happen 3215 final PackageParser.Package pkg = mPackages.get(pkgName); 3216 if (pkg == null) { 3217 stubSystemApps.remove(i); 3218 continue; 3219 } 3220 // skip if the package has been disabled by the user 3221 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3222 if (ps != null) { 3223 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3224 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3225 stubSystemApps.remove(i); 3226 continue; 3227 } 3228 } 3229 3230 if (DEBUG_COMPRESSION) { 3231 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3232 } 3233 3234 // uncompress the binary to its eventual destination on /data 3235 final File scanFile = decompressPackage(pkg); 3236 if (scanFile == null) { 3237 continue; 3238 } 3239 3240 // install the package to replace the stub on /system 3241 try { 3242 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3243 removePackageLI(pkg, true /*chatty*/); 3244 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3245 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3246 UserHandle.USER_SYSTEM, "android"); 3247 stubSystemApps.remove(i); 3248 continue; 3249 } catch (PackageManagerException e) { 3250 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3251 } 3252 3253 // any failed attempt to install the package will be cleaned up later 3254 } 3255 3256 // disable any stub still left; these failed to install the full application 3257 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3258 final String pkgName = stubSystemApps.get(i); 3259 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3260 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3261 UserHandle.USER_SYSTEM, "android"); 3262 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3263 } 3264 } 3265 3266 /** 3267 * Decompresses the given package on the system image onto 3268 * the /data partition. 3269 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3270 */ 3271 private File decompressPackage(PackageParser.Package pkg) { 3272 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3273 if (compressedFiles == null || compressedFiles.length == 0) { 3274 if (DEBUG_COMPRESSION) { 3275 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3276 } 3277 return null; 3278 } 3279 final File dstCodePath = 3280 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3281 int ret = PackageManager.INSTALL_SUCCEEDED; 3282 try { 3283 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3284 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3285 for (File srcFile : compressedFiles) { 3286 final String srcFileName = srcFile.getName(); 3287 final String dstFileName = srcFileName.substring( 3288 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3289 final File dstFile = new File(dstCodePath, dstFileName); 3290 ret = decompressFile(srcFile, dstFile); 3291 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3292 logCriticalInfo(Log.ERROR, "Failed to decompress" 3293 + "; pkg: " + pkg.packageName 3294 + ", file: " + dstFileName); 3295 break; 3296 } 3297 } 3298 } catch (ErrnoException e) { 3299 logCriticalInfo(Log.ERROR, "Failed to decompress" 3300 + "; pkg: " + pkg.packageName 3301 + ", err: " + e.errno); 3302 } 3303 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3304 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3305 NativeLibraryHelper.Handle handle = null; 3306 try { 3307 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3308 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3309 null /*abiOverride*/); 3310 } catch (IOException e) { 3311 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3312 + "; pkg: " + pkg.packageName); 3313 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3314 } finally { 3315 IoUtils.closeQuietly(handle); 3316 } 3317 } 3318 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3319 if (dstCodePath == null || !dstCodePath.exists()) { 3320 return null; 3321 } 3322 removeCodePathLI(dstCodePath); 3323 return null; 3324 } 3325 3326 return dstCodePath; 3327 } 3328 3329 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3330 // we're only interested in updating the installer appliction when 1) it's not 3331 // already set or 2) the modified package is the installer 3332 if (mInstantAppInstallerActivity != null 3333 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3334 .equals(modifiedPackage)) { 3335 return; 3336 } 3337 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3338 } 3339 3340 private static File preparePackageParserCache(boolean isUpgrade) { 3341 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3342 return null; 3343 } 3344 3345 // Disable package parsing on eng builds to allow for faster incremental development. 3346 if (Build.IS_ENG) { 3347 return null; 3348 } 3349 3350 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3351 Slog.i(TAG, "Disabling package parser cache due to system property."); 3352 return null; 3353 } 3354 3355 // The base directory for the package parser cache lives under /data/system/. 3356 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3357 "package_cache"); 3358 if (cacheBaseDir == null) { 3359 return null; 3360 } 3361 3362 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3363 // This also serves to "GC" unused entries when the package cache version changes (which 3364 // can only happen during upgrades). 3365 if (isUpgrade) { 3366 FileUtils.deleteContents(cacheBaseDir); 3367 } 3368 3369 3370 // Return the versioned package cache directory. This is something like 3371 // "/data/system/package_cache/1" 3372 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3373 3374 // The following is a workaround to aid development on non-numbered userdebug 3375 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3376 // the system partition is newer. 3377 // 3378 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3379 // that starts with "eng." to signify that this is an engineering build and not 3380 // destined for release. 3381 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3382 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3383 3384 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3385 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3386 // in general and should not be used for production changes. In this specific case, 3387 // we know that they will work. 3388 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3389 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3390 FileUtils.deleteContents(cacheBaseDir); 3391 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3392 } 3393 } 3394 3395 return cacheDir; 3396 } 3397 3398 @Override 3399 public boolean isFirstBoot() { 3400 // allow instant applications 3401 return mFirstBoot; 3402 } 3403 3404 @Override 3405 public boolean isOnlyCoreApps() { 3406 // allow instant applications 3407 return mOnlyCore; 3408 } 3409 3410 @Override 3411 public boolean isUpgrade() { 3412 // allow instant applications 3413 // The system property allows testing ota flow when upgraded to the same image. 3414 return mIsUpgrade || SystemProperties.getBoolean( 3415 "persist.pm.mock-upgrade", false /* default */); 3416 } 3417 3418 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3419 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3420 3421 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3422 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3423 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3424 if (matches.size() == 1) { 3425 return matches.get(0).getComponentInfo().packageName; 3426 } else if (matches.size() == 0) { 3427 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3428 return null; 3429 } 3430 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3431 } 3432 3433 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3434 synchronized (mPackages) { 3435 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3436 if (libraryEntry == null) { 3437 throw new IllegalStateException("Missing required shared library:" + name); 3438 } 3439 return libraryEntry.apk; 3440 } 3441 } 3442 3443 private @NonNull String getRequiredInstallerLPr() { 3444 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3445 intent.addCategory(Intent.CATEGORY_DEFAULT); 3446 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3447 3448 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3449 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3450 UserHandle.USER_SYSTEM); 3451 if (matches.size() == 1) { 3452 ResolveInfo resolveInfo = matches.get(0); 3453 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3454 throw new RuntimeException("The installer must be a privileged app"); 3455 } 3456 return matches.get(0).getComponentInfo().packageName; 3457 } else { 3458 throw new RuntimeException("There must be exactly one installer; found " + matches); 3459 } 3460 } 3461 3462 private @NonNull String getRequiredUninstallerLPr() { 3463 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3464 intent.addCategory(Intent.CATEGORY_DEFAULT); 3465 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3466 3467 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3468 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3469 UserHandle.USER_SYSTEM); 3470 if (resolveInfo == null || 3471 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3472 throw new RuntimeException("There must be exactly one uninstaller; found " 3473 + resolveInfo); 3474 } 3475 return resolveInfo.getComponentInfo().packageName; 3476 } 3477 3478 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3479 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3480 3481 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3482 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3483 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3484 ResolveInfo best = null; 3485 final int N = matches.size(); 3486 for (int i = 0; i < N; i++) { 3487 final ResolveInfo cur = matches.get(i); 3488 final String packageName = cur.getComponentInfo().packageName; 3489 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3490 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3491 continue; 3492 } 3493 3494 if (best == null || cur.priority > best.priority) { 3495 best = cur; 3496 } 3497 } 3498 3499 if (best != null) { 3500 return best.getComponentInfo().getComponentName(); 3501 } 3502 Slog.w(TAG, "Intent filter verifier not found"); 3503 return null; 3504 } 3505 3506 @Override 3507 public @Nullable ComponentName getInstantAppResolverComponent() { 3508 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3509 return null; 3510 } 3511 synchronized (mPackages) { 3512 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3513 if (instantAppResolver == null) { 3514 return null; 3515 } 3516 return instantAppResolver.first; 3517 } 3518 } 3519 3520 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3521 final String[] packageArray = 3522 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3523 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3524 if (DEBUG_INSTANT) { 3525 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3526 } 3527 return null; 3528 } 3529 3530 final int callingUid = Binder.getCallingUid(); 3531 final int resolveFlags = 3532 MATCH_DIRECT_BOOT_AWARE 3533 | MATCH_DIRECT_BOOT_UNAWARE 3534 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3535 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3536 final Intent resolverIntent = new Intent(actionName); 3537 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3538 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3539 final int N = resolvers.size(); 3540 if (N == 0) { 3541 if (DEBUG_INSTANT) { 3542 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3543 } 3544 return null; 3545 } 3546 3547 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3548 for (int i = 0; i < N; i++) { 3549 final ResolveInfo info = resolvers.get(i); 3550 3551 if (info.serviceInfo == null) { 3552 continue; 3553 } 3554 3555 final String packageName = info.serviceInfo.packageName; 3556 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3557 if (DEBUG_INSTANT) { 3558 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3559 + " pkg: " + packageName + ", info:" + info); 3560 } 3561 continue; 3562 } 3563 3564 if (DEBUG_INSTANT) { 3565 Slog.v(TAG, "Ephemeral resolver found;" 3566 + " pkg: " + packageName + ", info:" + info); 3567 } 3568 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3569 } 3570 if (DEBUG_INSTANT) { 3571 Slog.v(TAG, "Ephemeral resolver NOT found"); 3572 } 3573 return null; 3574 } 3575 3576 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3577 String[] orderedActions = Build.IS_ENG 3578 ? new String[]{ 3579 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3580 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3581 : new String[]{ 3582 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3583 3584 final int resolveFlags = 3585 MATCH_DIRECT_BOOT_AWARE 3586 | MATCH_DIRECT_BOOT_UNAWARE 3587 | Intent.FLAG_IGNORE_EPHEMERAL 3588 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3589 final Intent intent = new Intent(); 3590 intent.addCategory(Intent.CATEGORY_DEFAULT); 3591 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3592 List<ResolveInfo> matches = null; 3593 for (String action : orderedActions) { 3594 intent.setAction(action); 3595 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3596 resolveFlags, UserHandle.USER_SYSTEM); 3597 if (matches.isEmpty()) { 3598 if (DEBUG_INSTANT) { 3599 Slog.d(TAG, "Instant App installer not found with " + action); 3600 } 3601 } else { 3602 break; 3603 } 3604 } 3605 Iterator<ResolveInfo> iter = matches.iterator(); 3606 while (iter.hasNext()) { 3607 final ResolveInfo rInfo = iter.next(); 3608 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3609 if (ps != null) { 3610 final PermissionsState permissionsState = ps.getPermissionsState(); 3611 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3612 || Build.IS_ENG) { 3613 continue; 3614 } 3615 } 3616 iter.remove(); 3617 } 3618 if (matches.size() == 0) { 3619 return null; 3620 } else if (matches.size() == 1) { 3621 return (ActivityInfo) matches.get(0).getComponentInfo(); 3622 } else { 3623 throw new RuntimeException( 3624 "There must be at most one ephemeral installer; found " + matches); 3625 } 3626 } 3627 3628 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3629 @NonNull ComponentName resolver) { 3630 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3631 .addCategory(Intent.CATEGORY_DEFAULT) 3632 .setPackage(resolver.getPackageName()); 3633 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3634 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3635 UserHandle.USER_SYSTEM); 3636 if (matches.isEmpty()) { 3637 return null; 3638 } 3639 return matches.get(0).getComponentInfo().getComponentName(); 3640 } 3641 3642 private void primeDomainVerificationsLPw(int userId) { 3643 if (DEBUG_DOMAIN_VERIFICATION) { 3644 Slog.d(TAG, "Priming domain verifications in user " + userId); 3645 } 3646 3647 SystemConfig systemConfig = SystemConfig.getInstance(); 3648 ArraySet<String> packages = systemConfig.getLinkedApps(); 3649 3650 for (String packageName : packages) { 3651 PackageParser.Package pkg = mPackages.get(packageName); 3652 if (pkg != null) { 3653 if (!pkg.isSystem()) { 3654 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3655 continue; 3656 } 3657 3658 ArraySet<String> domains = null; 3659 for (PackageParser.Activity a : pkg.activities) { 3660 for (ActivityIntentInfo filter : a.intents) { 3661 if (hasValidDomains(filter)) { 3662 if (domains == null) { 3663 domains = new ArraySet<String>(); 3664 } 3665 domains.addAll(filter.getHostsList()); 3666 } 3667 } 3668 } 3669 3670 if (domains != null && domains.size() > 0) { 3671 if (DEBUG_DOMAIN_VERIFICATION) { 3672 Slog.v(TAG, " + " + packageName); 3673 } 3674 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3675 // state w.r.t. the formal app-linkage "no verification attempted" state; 3676 // and then 'always' in the per-user state actually used for intent resolution. 3677 final IntentFilterVerificationInfo ivi; 3678 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3679 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3680 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3681 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3682 } else { 3683 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3684 + "' does not handle web links"); 3685 } 3686 } else { 3687 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3688 } 3689 } 3690 3691 scheduleWritePackageRestrictionsLocked(userId); 3692 scheduleWriteSettingsLocked(); 3693 } 3694 3695 private void applyFactoryDefaultBrowserLPw(int userId) { 3696 // The default browser app's package name is stored in a string resource, 3697 // with a product-specific overlay used for vendor customization. 3698 String browserPkg = mContext.getResources().getString( 3699 com.android.internal.R.string.default_browser); 3700 if (!TextUtils.isEmpty(browserPkg)) { 3701 // non-empty string => required to be a known package 3702 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3703 if (ps == null) { 3704 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3705 browserPkg = null; 3706 } else { 3707 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3708 } 3709 } 3710 3711 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3712 // default. If there's more than one, just leave everything alone. 3713 if (browserPkg == null) { 3714 calculateDefaultBrowserLPw(userId); 3715 } 3716 } 3717 3718 private void calculateDefaultBrowserLPw(int userId) { 3719 List<String> allBrowsers = resolveAllBrowserApps(userId); 3720 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3721 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3722 } 3723 3724 private List<String> resolveAllBrowserApps(int userId) { 3725 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3726 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3727 PackageManager.MATCH_ALL, userId); 3728 3729 final int count = list.size(); 3730 List<String> result = new ArrayList<String>(count); 3731 for (int i=0; i<count; i++) { 3732 ResolveInfo info = list.get(i); 3733 if (info.activityInfo == null 3734 || !info.handleAllWebDataURI 3735 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3736 || result.contains(info.activityInfo.packageName)) { 3737 continue; 3738 } 3739 result.add(info.activityInfo.packageName); 3740 } 3741 3742 return result; 3743 } 3744 3745 private boolean packageIsBrowser(String packageName, int userId) { 3746 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3747 PackageManager.MATCH_ALL, userId); 3748 final int N = list.size(); 3749 for (int i = 0; i < N; i++) { 3750 ResolveInfo info = list.get(i); 3751 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3752 return true; 3753 } 3754 } 3755 return false; 3756 } 3757 3758 private void checkDefaultBrowser() { 3759 final int myUserId = UserHandle.myUserId(); 3760 final String packageName = getDefaultBrowserPackageName(myUserId); 3761 if (packageName != null) { 3762 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3763 if (info == null) { 3764 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3765 synchronized (mPackages) { 3766 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3767 } 3768 } 3769 } 3770 } 3771 3772 @Override 3773 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3774 throws RemoteException { 3775 try { 3776 return super.onTransact(code, data, reply, flags); 3777 } catch (RuntimeException e) { 3778 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3779 Slog.wtf(TAG, "Package Manager Crash", e); 3780 } 3781 throw e; 3782 } 3783 } 3784 3785 static int[] appendInts(int[] cur, int[] add) { 3786 if (add == null) return cur; 3787 if (cur == null) return add; 3788 final int N = add.length; 3789 for (int i=0; i<N; i++) { 3790 cur = appendInt(cur, add[i]); 3791 } 3792 return cur; 3793 } 3794 3795 /** 3796 * Returns whether or not a full application can see an instant application. 3797 * <p> 3798 * Currently, there are three cases in which this can occur: 3799 * <ol> 3800 * <li>The calling application is a "special" process. Special processes 3801 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3802 * <li>The calling application has the permission 3803 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3804 * <li>The calling application is the default launcher on the 3805 * system partition.</li> 3806 * </ol> 3807 */ 3808 private boolean canViewInstantApps(int callingUid, int userId) { 3809 if (callingUid < Process.FIRST_APPLICATION_UID) { 3810 return true; 3811 } 3812 if (mContext.checkCallingOrSelfPermission( 3813 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3814 return true; 3815 } 3816 if (mContext.checkCallingOrSelfPermission( 3817 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3818 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3819 if (homeComponent != null 3820 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3821 return true; 3822 } 3823 } 3824 return false; 3825 } 3826 3827 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3828 if (!sUserManager.exists(userId)) return null; 3829 if (ps == null) { 3830 return null; 3831 } 3832 final int callingUid = Binder.getCallingUid(); 3833 // Filter out ephemeral app metadata: 3834 // * The system/shell/root can see metadata for any app 3835 // * An installed app can see metadata for 1) other installed apps 3836 // and 2) ephemeral apps that have explicitly interacted with it 3837 // * Ephemeral apps can only see their own data and exposed installed apps 3838 // * Holding a signature permission allows seeing instant apps 3839 if (filterAppAccessLPr(ps, callingUid, userId)) { 3840 return null; 3841 } 3842 3843 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3844 && ps.isSystem()) { 3845 flags |= MATCH_ANY_USER; 3846 } 3847 3848 final PackageUserState state = ps.readUserState(userId); 3849 PackageParser.Package p = ps.pkg; 3850 if (p != null) { 3851 final PermissionsState permissionsState = ps.getPermissionsState(); 3852 3853 // Compute GIDs only if requested 3854 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3855 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3856 // Compute granted permissions only if package has requested permissions 3857 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3858 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3859 3860 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3861 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3862 3863 if (packageInfo == null) { 3864 return null; 3865 } 3866 3867 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3868 resolveExternalPackageNameLPr(p); 3869 3870 return packageInfo; 3871 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 3872 PackageInfo pi = new PackageInfo(); 3873 pi.packageName = ps.name; 3874 pi.setLongVersionCode(ps.versionCode); 3875 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 3876 pi.firstInstallTime = ps.firstInstallTime; 3877 pi.lastUpdateTime = ps.lastUpdateTime; 3878 3879 ApplicationInfo ai = new ApplicationInfo(); 3880 ai.packageName = ps.name; 3881 ai.uid = UserHandle.getUid(userId, ps.appId); 3882 ai.primaryCpuAbi = ps.primaryCpuAbiString; 3883 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 3884 ai.versionCode = ps.versionCode; 3885 ai.flags = ps.pkgFlags; 3886 ai.privateFlags = ps.pkgPrivateFlags; 3887 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 3888 3889 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 3890 + ps.name + "]. Provides a minimum info."); 3891 return pi; 3892 } else { 3893 return null; 3894 } 3895 } 3896 3897 @Override 3898 public void checkPackageStartable(String packageName, int userId) { 3899 final int callingUid = Binder.getCallingUid(); 3900 if (getInstantAppPackageName(callingUid) != null) { 3901 throw new SecurityException("Instant applications don't have access to this method"); 3902 } 3903 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3904 synchronized (mPackages) { 3905 final PackageSetting ps = mSettings.mPackages.get(packageName); 3906 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3907 throw new SecurityException("Package " + packageName + " was not found!"); 3908 } 3909 3910 if (!ps.getInstalled(userId)) { 3911 throw new SecurityException( 3912 "Package " + packageName + " was not installed for user " + userId + "!"); 3913 } 3914 3915 if (mSafeMode && !ps.isSystem()) { 3916 throw new SecurityException("Package " + packageName + " not a system app!"); 3917 } 3918 3919 if (mFrozenPackages.contains(packageName)) { 3920 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3921 } 3922 3923 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3924 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3925 } 3926 } 3927 } 3928 3929 @Override 3930 public boolean isPackageAvailable(String packageName, int userId) { 3931 if (!sUserManager.exists(userId)) return false; 3932 final int callingUid = Binder.getCallingUid(); 3933 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3934 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3935 synchronized (mPackages) { 3936 PackageParser.Package p = mPackages.get(packageName); 3937 if (p != null) { 3938 final PackageSetting ps = (PackageSetting) p.mExtras; 3939 if (filterAppAccessLPr(ps, callingUid, userId)) { 3940 return false; 3941 } 3942 if (ps != null) { 3943 final PackageUserState state = ps.readUserState(userId); 3944 if (state != null) { 3945 return PackageParser.isAvailable(state); 3946 } 3947 } 3948 } 3949 } 3950 return false; 3951 } 3952 3953 @Override 3954 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3955 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3956 flags, Binder.getCallingUid(), userId); 3957 } 3958 3959 @Override 3960 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3961 int flags, int userId) { 3962 return getPackageInfoInternal(versionedPackage.getPackageName(), 3963 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3964 } 3965 3966 /** 3967 * Important: The provided filterCallingUid is used exclusively to filter out packages 3968 * that can be seen based on user state. It's typically the original caller uid prior 3969 * to clearing. Because it can only be provided by trusted code, it's value can be 3970 * trusted and will be used as-is; unlike userId which will be validated by this method. 3971 */ 3972 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3973 int flags, int filterCallingUid, int userId) { 3974 if (!sUserManager.exists(userId)) return null; 3975 flags = updateFlagsForPackage(flags, userId, packageName); 3976 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3977 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3978 3979 // reader 3980 synchronized (mPackages) { 3981 // Normalize package name to handle renamed packages and static libs 3982 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3983 3984 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3985 if (matchFactoryOnly) { 3986 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3987 if (ps != null) { 3988 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3989 return null; 3990 } 3991 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3992 return null; 3993 } 3994 return generatePackageInfo(ps, flags, userId); 3995 } 3996 } 3997 3998 PackageParser.Package p = mPackages.get(packageName); 3999 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4000 return null; 4001 } 4002 if (DEBUG_PACKAGE_INFO) 4003 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4004 if (p != null) { 4005 final PackageSetting ps = (PackageSetting) p.mExtras; 4006 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4007 return null; 4008 } 4009 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4010 return null; 4011 } 4012 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4013 } 4014 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4015 final PackageSetting ps = mSettings.mPackages.get(packageName); 4016 if (ps == null) return null; 4017 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4018 return null; 4019 } 4020 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4021 return null; 4022 } 4023 return generatePackageInfo(ps, flags, userId); 4024 } 4025 } 4026 return null; 4027 } 4028 4029 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4030 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4031 return true; 4032 } 4033 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4034 return true; 4035 } 4036 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4037 return true; 4038 } 4039 return false; 4040 } 4041 4042 private boolean isComponentVisibleToInstantApp( 4043 @Nullable ComponentName component, @ComponentType int type) { 4044 if (type == TYPE_ACTIVITY) { 4045 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4046 return activity != null 4047 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4048 : false; 4049 } else if (type == TYPE_RECEIVER) { 4050 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4051 return activity != null 4052 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4053 : false; 4054 } else if (type == TYPE_SERVICE) { 4055 final PackageParser.Service service = mServices.mServices.get(component); 4056 return service != null 4057 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4058 : false; 4059 } else if (type == TYPE_PROVIDER) { 4060 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4061 return provider != null 4062 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4063 : false; 4064 } else if (type == TYPE_UNKNOWN) { 4065 return isComponentVisibleToInstantApp(component); 4066 } 4067 return false; 4068 } 4069 4070 /** 4071 * Returns whether or not access to the application should be filtered. 4072 * <p> 4073 * Access may be limited based upon whether the calling or target applications 4074 * are instant applications. 4075 * 4076 * @see #canAccessInstantApps(int) 4077 */ 4078 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4079 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4080 // if we're in an isolated process, get the real calling UID 4081 if (Process.isIsolated(callingUid)) { 4082 callingUid = mIsolatedOwners.get(callingUid); 4083 } 4084 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4085 final boolean callerIsInstantApp = instantAppPkgName != null; 4086 if (ps == null) { 4087 if (callerIsInstantApp) { 4088 // pretend the application exists, but, needs to be filtered 4089 return true; 4090 } 4091 return false; 4092 } 4093 // if the target and caller are the same application, don't filter 4094 if (isCallerSameApp(ps.name, callingUid)) { 4095 return false; 4096 } 4097 if (callerIsInstantApp) { 4098 // request for a specific component; if it hasn't been explicitly exposed, filter 4099 if (component != null) { 4100 return !isComponentVisibleToInstantApp(component, componentType); 4101 } 4102 // request for application; if no components have been explicitly exposed, filter 4103 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4104 } 4105 if (ps.getInstantApp(userId)) { 4106 // caller can see all components of all instant applications, don't filter 4107 if (canViewInstantApps(callingUid, userId)) { 4108 return false; 4109 } 4110 // request for a specific instant application component, filter 4111 if (component != null) { 4112 return true; 4113 } 4114 // request for an instant application; if the caller hasn't been granted access, filter 4115 return !mInstantAppRegistry.isInstantAccessGranted( 4116 userId, UserHandle.getAppId(callingUid), ps.appId); 4117 } 4118 return false; 4119 } 4120 4121 /** 4122 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4123 */ 4124 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4125 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4126 } 4127 4128 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4129 int flags) { 4130 // Callers can access only the libs they depend on, otherwise they need to explicitly 4131 // ask for the shared libraries given the caller is allowed to access all static libs. 4132 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4133 // System/shell/root get to see all static libs 4134 final int appId = UserHandle.getAppId(uid); 4135 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4136 || appId == Process.ROOT_UID) { 4137 return false; 4138 } 4139 } 4140 4141 // No package means no static lib as it is always on internal storage 4142 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4143 return false; 4144 } 4145 4146 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4147 ps.pkg.staticSharedLibVersion); 4148 if (libEntry == null) { 4149 return false; 4150 } 4151 4152 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4153 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4154 if (uidPackageNames == null) { 4155 return true; 4156 } 4157 4158 for (String uidPackageName : uidPackageNames) { 4159 if (ps.name.equals(uidPackageName)) { 4160 return false; 4161 } 4162 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4163 if (uidPs != null) { 4164 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4165 libEntry.info.getName()); 4166 if (index < 0) { 4167 continue; 4168 } 4169 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4170 return false; 4171 } 4172 } 4173 } 4174 return true; 4175 } 4176 4177 @Override 4178 public String[] currentToCanonicalPackageNames(String[] names) { 4179 final int callingUid = Binder.getCallingUid(); 4180 if (getInstantAppPackageName(callingUid) != null) { 4181 return names; 4182 } 4183 final String[] out = new String[names.length]; 4184 // reader 4185 synchronized (mPackages) { 4186 final int callingUserId = UserHandle.getUserId(callingUid); 4187 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4188 for (int i=names.length-1; i>=0; i--) { 4189 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4190 boolean translateName = false; 4191 if (ps != null && ps.realName != null) { 4192 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4193 translateName = !targetIsInstantApp 4194 || canViewInstantApps 4195 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4196 UserHandle.getAppId(callingUid), ps.appId); 4197 } 4198 out[i] = translateName ? ps.realName : names[i]; 4199 } 4200 } 4201 return out; 4202 } 4203 4204 @Override 4205 public String[] canonicalToCurrentPackageNames(String[] names) { 4206 final int callingUid = Binder.getCallingUid(); 4207 if (getInstantAppPackageName(callingUid) != null) { 4208 return names; 4209 } 4210 final String[] out = new String[names.length]; 4211 // reader 4212 synchronized (mPackages) { 4213 final int callingUserId = UserHandle.getUserId(callingUid); 4214 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4215 for (int i=names.length-1; i>=0; i--) { 4216 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4217 boolean translateName = false; 4218 if (cur != null) { 4219 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4220 final boolean targetIsInstantApp = 4221 ps != null && ps.getInstantApp(callingUserId); 4222 translateName = !targetIsInstantApp 4223 || canViewInstantApps 4224 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4225 UserHandle.getAppId(callingUid), ps.appId); 4226 } 4227 out[i] = translateName ? cur : names[i]; 4228 } 4229 } 4230 return out; 4231 } 4232 4233 @Override 4234 public int getPackageUid(String packageName, int flags, int userId) { 4235 if (!sUserManager.exists(userId)) return -1; 4236 final int callingUid = Binder.getCallingUid(); 4237 flags = updateFlagsForPackage(flags, userId, packageName); 4238 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4239 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4240 4241 // reader 4242 synchronized (mPackages) { 4243 final PackageParser.Package p = mPackages.get(packageName); 4244 if (p != null && p.isMatch(flags)) { 4245 PackageSetting ps = (PackageSetting) p.mExtras; 4246 if (filterAppAccessLPr(ps, callingUid, userId)) { 4247 return -1; 4248 } 4249 return UserHandle.getUid(userId, p.applicationInfo.uid); 4250 } 4251 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4252 final PackageSetting ps = mSettings.mPackages.get(packageName); 4253 if (ps != null && ps.isMatch(flags) 4254 && !filterAppAccessLPr(ps, callingUid, userId)) { 4255 return UserHandle.getUid(userId, ps.appId); 4256 } 4257 } 4258 } 4259 4260 return -1; 4261 } 4262 4263 @Override 4264 public int[] getPackageGids(String packageName, int flags, int userId) { 4265 if (!sUserManager.exists(userId)) return null; 4266 final int callingUid = Binder.getCallingUid(); 4267 flags = updateFlagsForPackage(flags, userId, packageName); 4268 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4269 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4270 4271 // reader 4272 synchronized (mPackages) { 4273 final PackageParser.Package p = mPackages.get(packageName); 4274 if (p != null && p.isMatch(flags)) { 4275 PackageSetting ps = (PackageSetting) p.mExtras; 4276 if (filterAppAccessLPr(ps, callingUid, userId)) { 4277 return null; 4278 } 4279 // TODO: Shouldn't this be checking for package installed state for userId and 4280 // return null? 4281 return ps.getPermissionsState().computeGids(userId); 4282 } 4283 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4284 final PackageSetting ps = mSettings.mPackages.get(packageName); 4285 if (ps != null && ps.isMatch(flags) 4286 && !filterAppAccessLPr(ps, callingUid, userId)) { 4287 return ps.getPermissionsState().computeGids(userId); 4288 } 4289 } 4290 } 4291 4292 return null; 4293 } 4294 4295 @Override 4296 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4297 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4298 } 4299 4300 @Override 4301 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4302 int flags) { 4303 final List<PermissionInfo> permissionList = 4304 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4305 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4306 } 4307 4308 @Override 4309 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4310 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4311 } 4312 4313 @Override 4314 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4315 final List<PermissionGroupInfo> permissionList = 4316 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4317 return (permissionList == null) 4318 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4319 } 4320 4321 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4322 int filterCallingUid, int userId) { 4323 if (!sUserManager.exists(userId)) return null; 4324 PackageSetting ps = mSettings.mPackages.get(packageName); 4325 if (ps != null) { 4326 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4327 return null; 4328 } 4329 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4330 return null; 4331 } 4332 if (ps.pkg == null) { 4333 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4334 if (pInfo != null) { 4335 return pInfo.applicationInfo; 4336 } 4337 return null; 4338 } 4339 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4340 ps.readUserState(userId), userId); 4341 if (ai != null) { 4342 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4343 } 4344 return ai; 4345 } 4346 return null; 4347 } 4348 4349 @Override 4350 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4351 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4352 } 4353 4354 /** 4355 * Important: The provided filterCallingUid is used exclusively to filter out applications 4356 * that can be seen based on user state. It's typically the original caller uid prior 4357 * to clearing. Because it can only be provided by trusted code, it's value can be 4358 * trusted and will be used as-is; unlike userId which will be validated by this method. 4359 */ 4360 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4361 int filterCallingUid, int userId) { 4362 if (!sUserManager.exists(userId)) return null; 4363 flags = updateFlagsForApplication(flags, userId, packageName); 4364 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4365 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4366 4367 // writer 4368 synchronized (mPackages) { 4369 // Normalize package name to handle renamed packages and static libs 4370 packageName = resolveInternalPackageNameLPr(packageName, 4371 PackageManager.VERSION_CODE_HIGHEST); 4372 4373 PackageParser.Package p = mPackages.get(packageName); 4374 if (DEBUG_PACKAGE_INFO) Log.v( 4375 TAG, "getApplicationInfo " + packageName 4376 + ": " + p); 4377 if (p != null) { 4378 PackageSetting ps = mSettings.mPackages.get(packageName); 4379 if (ps == null) return null; 4380 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4381 return null; 4382 } 4383 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4384 return null; 4385 } 4386 // Note: isEnabledLP() does not apply here - always return info 4387 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4388 p, flags, ps.readUserState(userId), userId); 4389 if (ai != null) { 4390 ai.packageName = resolveExternalPackageNameLPr(p); 4391 } 4392 return ai; 4393 } 4394 if ("android".equals(packageName)||"system".equals(packageName)) { 4395 return mAndroidApplication; 4396 } 4397 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4398 // Already generates the external package name 4399 return generateApplicationInfoFromSettingsLPw(packageName, 4400 flags, filterCallingUid, userId); 4401 } 4402 } 4403 return null; 4404 } 4405 4406 private String normalizePackageNameLPr(String packageName) { 4407 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4408 return normalizedPackageName != null ? normalizedPackageName : packageName; 4409 } 4410 4411 @Override 4412 public void deletePreloadsFileCache() { 4413 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4414 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4415 } 4416 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4417 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4418 FileUtils.deleteContents(dir); 4419 } 4420 4421 @Override 4422 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4423 final int storageFlags, final IPackageDataObserver observer) { 4424 mContext.enforceCallingOrSelfPermission( 4425 android.Manifest.permission.CLEAR_APP_CACHE, null); 4426 mHandler.post(() -> { 4427 boolean success = false; 4428 try { 4429 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4430 success = true; 4431 } catch (IOException e) { 4432 Slog.w(TAG, e); 4433 } 4434 if (observer != null) { 4435 try { 4436 observer.onRemoveCompleted(null, success); 4437 } catch (RemoteException e) { 4438 Slog.w(TAG, e); 4439 } 4440 } 4441 }); 4442 } 4443 4444 @Override 4445 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4446 final int storageFlags, final IntentSender pi) { 4447 mContext.enforceCallingOrSelfPermission( 4448 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4449 mHandler.post(() -> { 4450 boolean success = false; 4451 try { 4452 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4453 success = true; 4454 } catch (IOException e) { 4455 Slog.w(TAG, e); 4456 } 4457 if (pi != null) { 4458 try { 4459 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4460 } catch (SendIntentException e) { 4461 Slog.w(TAG, e); 4462 } 4463 } 4464 }); 4465 } 4466 4467 /** 4468 * Blocking call to clear various types of cached data across the system 4469 * until the requested bytes are available. 4470 */ 4471 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4472 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4473 final File file = storage.findPathForUuid(volumeUuid); 4474 if (file.getUsableSpace() >= bytes) return; 4475 4476 if (ENABLE_FREE_CACHE_V2) { 4477 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4478 volumeUuid); 4479 final boolean aggressive = (storageFlags 4480 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4481 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4482 4483 // 1. Pre-flight to determine if we have any chance to succeed 4484 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4485 if (internalVolume && (aggressive || SystemProperties 4486 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4487 deletePreloadsFileCache(); 4488 if (file.getUsableSpace() >= bytes) return; 4489 } 4490 4491 // 3. Consider parsed APK data (aggressive only) 4492 if (internalVolume && aggressive) { 4493 FileUtils.deleteContents(mCacheDir); 4494 if (file.getUsableSpace() >= bytes) return; 4495 } 4496 4497 // 4. Consider cached app data (above quotas) 4498 try { 4499 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4500 Installer.FLAG_FREE_CACHE_V2); 4501 } catch (InstallerException ignored) { 4502 } 4503 if (file.getUsableSpace() >= bytes) return; 4504 4505 // 5. Consider shared libraries with refcount=0 and age>min cache period 4506 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4507 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4508 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4509 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4510 return; 4511 } 4512 4513 // 6. Consider dexopt output (aggressive only) 4514 // TODO: Implement 4515 4516 // 7. Consider installed instant apps unused longer than min cache period 4517 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4518 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4519 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4520 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4521 return; 4522 } 4523 4524 // 8. Consider cached app data (below quotas) 4525 try { 4526 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4527 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4528 } catch (InstallerException ignored) { 4529 } 4530 if (file.getUsableSpace() >= bytes) return; 4531 4532 // 9. Consider DropBox entries 4533 // TODO: Implement 4534 4535 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4536 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4537 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4538 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4539 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4540 return; 4541 } 4542 } else { 4543 try { 4544 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4545 } catch (InstallerException ignored) { 4546 } 4547 if (file.getUsableSpace() >= bytes) return; 4548 } 4549 4550 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4551 } 4552 4553 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4554 throws IOException { 4555 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4556 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4557 4558 List<VersionedPackage> packagesToDelete = null; 4559 final long now = System.currentTimeMillis(); 4560 4561 synchronized (mPackages) { 4562 final int[] allUsers = sUserManager.getUserIds(); 4563 final int libCount = mSharedLibraries.size(); 4564 for (int i = 0; i < libCount; i++) { 4565 final LongSparseArray<SharedLibraryEntry> versionedLib 4566 = mSharedLibraries.valueAt(i); 4567 if (versionedLib == null) { 4568 continue; 4569 } 4570 final int versionCount = versionedLib.size(); 4571 for (int j = 0; j < versionCount; j++) { 4572 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4573 // Skip packages that are not static shared libs. 4574 if (!libInfo.isStatic()) { 4575 break; 4576 } 4577 // Important: We skip static shared libs used for some user since 4578 // in such a case we need to keep the APK on the device. The check for 4579 // a lib being used for any user is performed by the uninstall call. 4580 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4581 // Resolve the package name - we use synthetic package names internally 4582 final String internalPackageName = resolveInternalPackageNameLPr( 4583 declaringPackage.getPackageName(), 4584 declaringPackage.getLongVersionCode()); 4585 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4586 // Skip unused static shared libs cached less than the min period 4587 // to prevent pruning a lib needed by a subsequently installed package. 4588 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4589 continue; 4590 } 4591 if (packagesToDelete == null) { 4592 packagesToDelete = new ArrayList<>(); 4593 } 4594 packagesToDelete.add(new VersionedPackage(internalPackageName, 4595 declaringPackage.getLongVersionCode())); 4596 } 4597 } 4598 } 4599 4600 if (packagesToDelete != null) { 4601 final int packageCount = packagesToDelete.size(); 4602 for (int i = 0; i < packageCount; i++) { 4603 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4604 // Delete the package synchronously (will fail of the lib used for any user). 4605 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4606 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4607 == PackageManager.DELETE_SUCCEEDED) { 4608 if (volume.getUsableSpace() >= neededSpace) { 4609 return true; 4610 } 4611 } 4612 } 4613 } 4614 4615 return false; 4616 } 4617 4618 /** 4619 * Update given flags based on encryption status of current user. 4620 */ 4621 private int updateFlags(int flags, int userId) { 4622 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4623 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4624 // Caller expressed an explicit opinion about what encryption 4625 // aware/unaware components they want to see, so fall through and 4626 // give them what they want 4627 } else { 4628 // Caller expressed no opinion, so match based on user state 4629 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4630 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4631 } else { 4632 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4633 } 4634 } 4635 return flags; 4636 } 4637 4638 private UserManagerInternal getUserManagerInternal() { 4639 if (mUserManagerInternal == null) { 4640 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4641 } 4642 return mUserManagerInternal; 4643 } 4644 4645 private ActivityManagerInternal getActivityManagerInternal() { 4646 if (mActivityManagerInternal == null) { 4647 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4648 } 4649 return mActivityManagerInternal; 4650 } 4651 4652 4653 private DeviceIdleController.LocalService getDeviceIdleController() { 4654 if (mDeviceIdleController == null) { 4655 mDeviceIdleController = 4656 LocalServices.getService(DeviceIdleController.LocalService.class); 4657 } 4658 return mDeviceIdleController; 4659 } 4660 4661 /** 4662 * Update given flags when being used to request {@link PackageInfo}. 4663 */ 4664 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4665 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4666 boolean triaged = true; 4667 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4668 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4669 // Caller is asking for component details, so they'd better be 4670 // asking for specific encryption matching behavior, or be triaged 4671 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4672 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4673 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4674 triaged = false; 4675 } 4676 } 4677 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4678 | PackageManager.MATCH_SYSTEM_ONLY 4679 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4680 triaged = false; 4681 } 4682 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4683 mPermissionManager.enforceCrossUserPermission( 4684 Binder.getCallingUid(), userId, false, false, 4685 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4686 + Debug.getCallers(5)); 4687 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4688 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4689 // If the caller wants all packages and has a restricted profile associated with it, 4690 // then match all users. This is to make sure that launchers that need to access work 4691 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4692 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4693 flags |= PackageManager.MATCH_ANY_USER; 4694 } 4695 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4696 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4697 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4698 } 4699 return updateFlags(flags, userId); 4700 } 4701 4702 /** 4703 * Update given flags when being used to request {@link ApplicationInfo}. 4704 */ 4705 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4706 return updateFlagsForPackage(flags, userId, cookie); 4707 } 4708 4709 /** 4710 * Update given flags when being used to request {@link ComponentInfo}. 4711 */ 4712 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4713 if (cookie instanceof Intent) { 4714 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4715 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4716 } 4717 } 4718 4719 boolean triaged = true; 4720 // Caller is asking for component details, so they'd better be 4721 // asking for specific encryption matching behavior, or be triaged 4722 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4723 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4724 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4725 triaged = false; 4726 } 4727 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4728 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4729 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4730 } 4731 4732 return updateFlags(flags, userId); 4733 } 4734 4735 /** 4736 * Update given intent when being used to request {@link ResolveInfo}. 4737 */ 4738 private Intent updateIntentForResolve(Intent intent) { 4739 if (intent.getSelector() != null) { 4740 intent = intent.getSelector(); 4741 } 4742 if (DEBUG_PREFERRED) { 4743 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4744 } 4745 return intent; 4746 } 4747 4748 /** 4749 * Update given flags when being used to request {@link ResolveInfo}. 4750 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4751 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4752 * flag set. However, this flag is only honoured in three circumstances: 4753 * <ul> 4754 * <li>when called from a system process</li> 4755 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4756 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4757 * action and a {@code android.intent.category.BROWSABLE} category</li> 4758 * </ul> 4759 */ 4760 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4761 return updateFlagsForResolve(flags, userId, intent, callingUid, 4762 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4763 } 4764 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4765 boolean wantInstantApps) { 4766 return updateFlagsForResolve(flags, userId, intent, callingUid, 4767 wantInstantApps, false /*onlyExposedExplicitly*/); 4768 } 4769 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4770 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4771 // Safe mode means we shouldn't match any third-party components 4772 if (mSafeMode) { 4773 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4774 } 4775 if (getInstantAppPackageName(callingUid) != null) { 4776 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4777 if (onlyExposedExplicitly) { 4778 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4779 } 4780 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4781 flags |= PackageManager.MATCH_INSTANT; 4782 } else { 4783 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4784 final boolean allowMatchInstant = wantInstantApps 4785 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4786 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4787 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4788 if (!allowMatchInstant) { 4789 flags &= ~PackageManager.MATCH_INSTANT; 4790 } 4791 } 4792 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4793 } 4794 4795 @Override 4796 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4797 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4798 } 4799 4800 /** 4801 * Important: The provided filterCallingUid is used exclusively to filter out activities 4802 * that can be seen based on user state. It's typically the original caller uid prior 4803 * to clearing. Because it can only be provided by trusted code, it's value can be 4804 * trusted and will be used as-is; unlike userId which will be validated by this method. 4805 */ 4806 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4807 int filterCallingUid, int userId) { 4808 if (!sUserManager.exists(userId)) return null; 4809 flags = updateFlagsForComponent(flags, userId, component); 4810 4811 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4812 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4813 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4814 } 4815 4816 synchronized (mPackages) { 4817 PackageParser.Activity a = mActivities.mActivities.get(component); 4818 4819 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4820 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4821 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4822 if (ps == null) return null; 4823 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4824 return null; 4825 } 4826 return PackageParser.generateActivityInfo( 4827 a, flags, ps.readUserState(userId), userId); 4828 } 4829 if (mResolveComponentName.equals(component)) { 4830 return PackageParser.generateActivityInfo( 4831 mResolveActivity, flags, new PackageUserState(), userId); 4832 } 4833 } 4834 return null; 4835 } 4836 4837 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4838 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4839 return false; 4840 } 4841 final long token = Binder.clearCallingIdentity(); 4842 try { 4843 final int callingUserId = UserHandle.getUserId(callingUid); 4844 if (ActivityManager.getCurrentUser() != callingUserId) { 4845 return false; 4846 } 4847 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4848 } finally { 4849 Binder.restoreCallingIdentity(token); 4850 } 4851 } 4852 4853 @Override 4854 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4855 String resolvedType) { 4856 synchronized (mPackages) { 4857 if (component.equals(mResolveComponentName)) { 4858 // The resolver supports EVERYTHING! 4859 return true; 4860 } 4861 final int callingUid = Binder.getCallingUid(); 4862 final int callingUserId = UserHandle.getUserId(callingUid); 4863 PackageParser.Activity a = mActivities.mActivities.get(component); 4864 if (a == null) { 4865 return false; 4866 } 4867 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4868 if (ps == null) { 4869 return false; 4870 } 4871 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4872 return false; 4873 } 4874 for (int i=0; i<a.intents.size(); i++) { 4875 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4876 intent.getData(), intent.getCategories(), TAG) >= 0) { 4877 return true; 4878 } 4879 } 4880 return false; 4881 } 4882 } 4883 4884 @Override 4885 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4886 if (!sUserManager.exists(userId)) return null; 4887 final int callingUid = Binder.getCallingUid(); 4888 flags = updateFlagsForComponent(flags, userId, component); 4889 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4890 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4891 synchronized (mPackages) { 4892 PackageParser.Activity a = mReceivers.mActivities.get(component); 4893 if (DEBUG_PACKAGE_INFO) Log.v( 4894 TAG, "getReceiverInfo " + component + ": " + a); 4895 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4896 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4897 if (ps == null) return null; 4898 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4899 return null; 4900 } 4901 return PackageParser.generateActivityInfo( 4902 a, flags, ps.readUserState(userId), userId); 4903 } 4904 } 4905 return null; 4906 } 4907 4908 @Override 4909 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4910 int flags, int userId) { 4911 if (!sUserManager.exists(userId)) return null; 4912 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4913 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4914 return null; 4915 } 4916 4917 flags = updateFlagsForPackage(flags, userId, null); 4918 4919 final boolean canSeeStaticLibraries = 4920 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4921 == PERMISSION_GRANTED 4922 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4923 == PERMISSION_GRANTED 4924 || canRequestPackageInstallsInternal(packageName, 4925 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4926 false /* throwIfPermNotDeclared*/) 4927 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4928 == PERMISSION_GRANTED; 4929 4930 synchronized (mPackages) { 4931 List<SharedLibraryInfo> result = null; 4932 4933 final int libCount = mSharedLibraries.size(); 4934 for (int i = 0; i < libCount; i++) { 4935 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4936 if (versionedLib == null) { 4937 continue; 4938 } 4939 4940 final int versionCount = versionedLib.size(); 4941 for (int j = 0; j < versionCount; j++) { 4942 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4943 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4944 break; 4945 } 4946 final long identity = Binder.clearCallingIdentity(); 4947 try { 4948 PackageInfo packageInfo = getPackageInfoVersioned( 4949 libInfo.getDeclaringPackage(), flags 4950 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4951 if (packageInfo == null) { 4952 continue; 4953 } 4954 } finally { 4955 Binder.restoreCallingIdentity(identity); 4956 } 4957 4958 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4959 libInfo.getLongVersion(), libInfo.getType(), 4960 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4961 flags, userId)); 4962 4963 if (result == null) { 4964 result = new ArrayList<>(); 4965 } 4966 result.add(resLibInfo); 4967 } 4968 } 4969 4970 return result != null ? new ParceledListSlice<>(result) : null; 4971 } 4972 } 4973 4974 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4975 SharedLibraryInfo libInfo, int flags, int userId) { 4976 List<VersionedPackage> versionedPackages = null; 4977 final int packageCount = mSettings.mPackages.size(); 4978 for (int i = 0; i < packageCount; i++) { 4979 PackageSetting ps = mSettings.mPackages.valueAt(i); 4980 4981 if (ps == null) { 4982 continue; 4983 } 4984 4985 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4986 continue; 4987 } 4988 4989 final String libName = libInfo.getName(); 4990 if (libInfo.isStatic()) { 4991 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4992 if (libIdx < 0) { 4993 continue; 4994 } 4995 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4996 continue; 4997 } 4998 if (versionedPackages == null) { 4999 versionedPackages = new ArrayList<>(); 5000 } 5001 // If the dependent is a static shared lib, use the public package name 5002 String dependentPackageName = ps.name; 5003 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5004 dependentPackageName = ps.pkg.manifestPackageName; 5005 } 5006 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5007 } else if (ps.pkg != null) { 5008 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5009 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5010 if (versionedPackages == null) { 5011 versionedPackages = new ArrayList<>(); 5012 } 5013 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5014 } 5015 } 5016 } 5017 5018 return versionedPackages; 5019 } 5020 5021 @Override 5022 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5023 if (!sUserManager.exists(userId)) return null; 5024 final int callingUid = Binder.getCallingUid(); 5025 flags = updateFlagsForComponent(flags, userId, component); 5026 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5027 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5028 synchronized (mPackages) { 5029 PackageParser.Service s = mServices.mServices.get(component); 5030 if (DEBUG_PACKAGE_INFO) Log.v( 5031 TAG, "getServiceInfo " + component + ": " + s); 5032 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5033 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5034 if (ps == null) return null; 5035 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5036 return null; 5037 } 5038 return PackageParser.generateServiceInfo( 5039 s, flags, ps.readUserState(userId), userId); 5040 } 5041 } 5042 return null; 5043 } 5044 5045 @Override 5046 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5047 if (!sUserManager.exists(userId)) return null; 5048 final int callingUid = Binder.getCallingUid(); 5049 flags = updateFlagsForComponent(flags, userId, component); 5050 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5051 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5052 synchronized (mPackages) { 5053 PackageParser.Provider p = mProviders.mProviders.get(component); 5054 if (DEBUG_PACKAGE_INFO) Log.v( 5055 TAG, "getProviderInfo " + component + ": " + p); 5056 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5057 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5058 if (ps == null) return null; 5059 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5060 return null; 5061 } 5062 return PackageParser.generateProviderInfo( 5063 p, flags, ps.readUserState(userId), userId); 5064 } 5065 } 5066 return null; 5067 } 5068 5069 @Override 5070 public String[] getSystemSharedLibraryNames() { 5071 // allow instant applications 5072 synchronized (mPackages) { 5073 Set<String> libs = null; 5074 final int libCount = mSharedLibraries.size(); 5075 for (int i = 0; i < libCount; i++) { 5076 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5077 if (versionedLib == null) { 5078 continue; 5079 } 5080 final int versionCount = versionedLib.size(); 5081 for (int j = 0; j < versionCount; j++) { 5082 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5083 if (!libEntry.info.isStatic()) { 5084 if (libs == null) { 5085 libs = new ArraySet<>(); 5086 } 5087 libs.add(libEntry.info.getName()); 5088 break; 5089 } 5090 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5091 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5092 UserHandle.getUserId(Binder.getCallingUid()), 5093 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5094 if (libs == null) { 5095 libs = new ArraySet<>(); 5096 } 5097 libs.add(libEntry.info.getName()); 5098 break; 5099 } 5100 } 5101 } 5102 5103 if (libs != null) { 5104 String[] libsArray = new String[libs.size()]; 5105 libs.toArray(libsArray); 5106 return libsArray; 5107 } 5108 5109 return null; 5110 } 5111 } 5112 5113 @Override 5114 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5115 // allow instant applications 5116 synchronized (mPackages) { 5117 return mServicesSystemSharedLibraryPackageName; 5118 } 5119 } 5120 5121 @Override 5122 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5123 // allow instant applications 5124 synchronized (mPackages) { 5125 return mSharedSystemSharedLibraryPackageName; 5126 } 5127 } 5128 5129 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5130 for (int i = userList.length - 1; i >= 0; --i) { 5131 final int userId = userList[i]; 5132 // don't add instant app to the list of updates 5133 if (pkgSetting.getInstantApp(userId)) { 5134 continue; 5135 } 5136 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5137 if (changedPackages == null) { 5138 changedPackages = new SparseArray<>(); 5139 mChangedPackages.put(userId, changedPackages); 5140 } 5141 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5142 if (sequenceNumbers == null) { 5143 sequenceNumbers = new HashMap<>(); 5144 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5145 } 5146 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5147 if (sequenceNumber != null) { 5148 changedPackages.remove(sequenceNumber); 5149 } 5150 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5151 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5152 } 5153 mChangedPackagesSequenceNumber++; 5154 } 5155 5156 @Override 5157 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5158 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5159 return null; 5160 } 5161 synchronized (mPackages) { 5162 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5163 return null; 5164 } 5165 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5166 if (changedPackages == null) { 5167 return null; 5168 } 5169 final List<String> packageNames = 5170 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5171 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5172 final String packageName = changedPackages.get(i); 5173 if (packageName != null) { 5174 packageNames.add(packageName); 5175 } 5176 } 5177 return packageNames.isEmpty() 5178 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5179 } 5180 } 5181 5182 @Override 5183 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5184 // allow instant applications 5185 ArrayList<FeatureInfo> res; 5186 synchronized (mAvailableFeatures) { 5187 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5188 res.addAll(mAvailableFeatures.values()); 5189 } 5190 final FeatureInfo fi = new FeatureInfo(); 5191 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5192 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5193 res.add(fi); 5194 5195 return new ParceledListSlice<>(res); 5196 } 5197 5198 @Override 5199 public boolean hasSystemFeature(String name, int version) { 5200 // allow instant applications 5201 synchronized (mAvailableFeatures) { 5202 final FeatureInfo feat = mAvailableFeatures.get(name); 5203 if (feat == null) { 5204 return false; 5205 } else { 5206 return feat.version >= version; 5207 } 5208 } 5209 } 5210 5211 @Override 5212 public int checkPermission(String permName, String pkgName, int userId) { 5213 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5214 } 5215 5216 @Override 5217 public int checkUidPermission(String permName, int uid) { 5218 synchronized (mPackages) { 5219 final String[] packageNames = getPackagesForUid(uid); 5220 final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0) 5221 ? mPackages.get(packageNames[0]) 5222 : null; 5223 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5224 } 5225 } 5226 5227 @Override 5228 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5229 if (UserHandle.getCallingUserId() != userId) { 5230 mContext.enforceCallingPermission( 5231 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5232 "isPermissionRevokedByPolicy for user " + userId); 5233 } 5234 5235 if (checkPermission(permission, packageName, userId) 5236 == PackageManager.PERMISSION_GRANTED) { 5237 return false; 5238 } 5239 5240 final int callingUid = Binder.getCallingUid(); 5241 if (getInstantAppPackageName(callingUid) != null) { 5242 if (!isCallerSameApp(packageName, callingUid)) { 5243 return false; 5244 } 5245 } else { 5246 if (isInstantApp(packageName, userId)) { 5247 return false; 5248 } 5249 } 5250 5251 final long identity = Binder.clearCallingIdentity(); 5252 try { 5253 final int flags = getPermissionFlags(permission, packageName, userId); 5254 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5255 } finally { 5256 Binder.restoreCallingIdentity(identity); 5257 } 5258 } 5259 5260 @Override 5261 public String getPermissionControllerPackageName() { 5262 synchronized (mPackages) { 5263 return mRequiredInstallerPackage; 5264 } 5265 } 5266 5267 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5268 return mPermissionManager.addDynamicPermission( 5269 info, async, getCallingUid(), new PermissionCallback() { 5270 @Override 5271 public void onPermissionChanged() { 5272 if (!async) { 5273 mSettings.writeLPr(); 5274 } else { 5275 scheduleWriteSettingsLocked(); 5276 } 5277 } 5278 }); 5279 } 5280 5281 @Override 5282 public boolean addPermission(PermissionInfo info) { 5283 synchronized (mPackages) { 5284 return addDynamicPermission(info, false); 5285 } 5286 } 5287 5288 @Override 5289 public boolean addPermissionAsync(PermissionInfo info) { 5290 synchronized (mPackages) { 5291 return addDynamicPermission(info, true); 5292 } 5293 } 5294 5295 @Override 5296 public void removePermission(String permName) { 5297 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5298 } 5299 5300 @Override 5301 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5302 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5303 getCallingUid(), userId, mPermissionCallback); 5304 } 5305 5306 @Override 5307 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5308 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5309 getCallingUid(), userId, mPermissionCallback); 5310 } 5311 5312 @Override 5313 public void resetRuntimePermissions() { 5314 mContext.enforceCallingOrSelfPermission( 5315 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5316 "revokeRuntimePermission"); 5317 5318 int callingUid = Binder.getCallingUid(); 5319 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5320 mContext.enforceCallingOrSelfPermission( 5321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5322 "resetRuntimePermissions"); 5323 } 5324 5325 synchronized (mPackages) { 5326 mPermissionManager.updateAllPermissions( 5327 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5328 mPermissionCallback); 5329 for (int userId : UserManagerService.getInstance().getUserIds()) { 5330 final int packageCount = mPackages.size(); 5331 for (int i = 0; i < packageCount; i++) { 5332 PackageParser.Package pkg = mPackages.valueAt(i); 5333 if (!(pkg.mExtras instanceof PackageSetting)) { 5334 continue; 5335 } 5336 PackageSetting ps = (PackageSetting) pkg.mExtras; 5337 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5338 } 5339 } 5340 } 5341 } 5342 5343 @Override 5344 public int getPermissionFlags(String permName, String packageName, int userId) { 5345 return mPermissionManager.getPermissionFlags( 5346 permName, packageName, getCallingUid(), userId); 5347 } 5348 5349 @Override 5350 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5351 int flagValues, int userId) { 5352 mPermissionManager.updatePermissionFlags( 5353 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5354 mPermissionCallback); 5355 } 5356 5357 /** 5358 * Update the permission flags for all packages and runtime permissions of a user in order 5359 * to allow device or profile owner to remove POLICY_FIXED. 5360 */ 5361 @Override 5362 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5363 synchronized (mPackages) { 5364 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5365 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5366 mPermissionCallback); 5367 if (changed) { 5368 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5369 } 5370 } 5371 } 5372 5373 @Override 5374 public boolean shouldShowRequestPermissionRationale(String permissionName, 5375 String packageName, int userId) { 5376 if (UserHandle.getCallingUserId() != userId) { 5377 mContext.enforceCallingPermission( 5378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5379 "canShowRequestPermissionRationale for user " + userId); 5380 } 5381 5382 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5383 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5384 return false; 5385 } 5386 5387 if (checkPermission(permissionName, packageName, userId) 5388 == PackageManager.PERMISSION_GRANTED) { 5389 return false; 5390 } 5391 5392 final int flags; 5393 5394 final long identity = Binder.clearCallingIdentity(); 5395 try { 5396 flags = getPermissionFlags(permissionName, 5397 packageName, userId); 5398 } finally { 5399 Binder.restoreCallingIdentity(identity); 5400 } 5401 5402 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5403 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5404 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5405 5406 if ((flags & fixedFlags) != 0) { 5407 return false; 5408 } 5409 5410 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5411 } 5412 5413 @Override 5414 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5415 mContext.enforceCallingOrSelfPermission( 5416 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5417 "addOnPermissionsChangeListener"); 5418 5419 synchronized (mPackages) { 5420 mOnPermissionChangeListeners.addListenerLocked(listener); 5421 } 5422 } 5423 5424 @Override 5425 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5426 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5427 throw new SecurityException("Instant applications don't have access to this method"); 5428 } 5429 synchronized (mPackages) { 5430 mOnPermissionChangeListeners.removeListenerLocked(listener); 5431 } 5432 } 5433 5434 @Override 5435 public boolean isProtectedBroadcast(String actionName) { 5436 // allow instant applications 5437 synchronized (mProtectedBroadcasts) { 5438 if (mProtectedBroadcasts.contains(actionName)) { 5439 return true; 5440 } else if (actionName != null) { 5441 // TODO: remove these terrible hacks 5442 if (actionName.startsWith("android.net.netmon.lingerExpired") 5443 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5444 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5445 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5446 return true; 5447 } 5448 } 5449 } 5450 return false; 5451 } 5452 5453 @Override 5454 public int checkSignatures(String pkg1, String pkg2) { 5455 synchronized (mPackages) { 5456 final PackageParser.Package p1 = mPackages.get(pkg1); 5457 final PackageParser.Package p2 = mPackages.get(pkg2); 5458 if (p1 == null || p1.mExtras == null 5459 || p2 == null || p2.mExtras == null) { 5460 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5461 } 5462 final int callingUid = Binder.getCallingUid(); 5463 final int callingUserId = UserHandle.getUserId(callingUid); 5464 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5465 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5466 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5467 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5468 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5469 } 5470 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5471 } 5472 } 5473 5474 @Override 5475 public int checkUidSignatures(int uid1, int uid2) { 5476 final int callingUid = Binder.getCallingUid(); 5477 final int callingUserId = UserHandle.getUserId(callingUid); 5478 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5479 // Map to base uids. 5480 uid1 = UserHandle.getAppId(uid1); 5481 uid2 = UserHandle.getAppId(uid2); 5482 // reader 5483 synchronized (mPackages) { 5484 Signature[] s1; 5485 Signature[] s2; 5486 Object obj = mSettings.getUserIdLPr(uid1); 5487 if (obj != null) { 5488 if (obj instanceof SharedUserSetting) { 5489 if (isCallerInstantApp) { 5490 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5491 } 5492 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5493 } else if (obj instanceof PackageSetting) { 5494 final PackageSetting ps = (PackageSetting) obj; 5495 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5496 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5497 } 5498 s1 = ps.signatures.mSigningDetails.signatures; 5499 } else { 5500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5501 } 5502 } else { 5503 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5504 } 5505 obj = mSettings.getUserIdLPr(uid2); 5506 if (obj != null) { 5507 if (obj instanceof SharedUserSetting) { 5508 if (isCallerInstantApp) { 5509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5510 } 5511 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5512 } else if (obj instanceof PackageSetting) { 5513 final PackageSetting ps = (PackageSetting) obj; 5514 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5515 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5516 } 5517 s2 = ps.signatures.mSigningDetails.signatures; 5518 } else { 5519 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5520 } 5521 } else { 5522 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5523 } 5524 return compareSignatures(s1, s2); 5525 } 5526 } 5527 5528 @Override 5529 public boolean hasSigningCertificate( 5530 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5531 5532 synchronized (mPackages) { 5533 final PackageParser.Package p = mPackages.get(packageName); 5534 if (p == null || p.mExtras == null) { 5535 return false; 5536 } 5537 final int callingUid = Binder.getCallingUid(); 5538 final int callingUserId = UserHandle.getUserId(callingUid); 5539 final PackageSetting ps = (PackageSetting) p.mExtras; 5540 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5541 return false; 5542 } 5543 switch (type) { 5544 case CERT_INPUT_RAW_X509: 5545 return p.mSigningDetails.hasCertificate(certificate); 5546 case CERT_INPUT_SHA256: 5547 return p.mSigningDetails.hasSha256Certificate(certificate); 5548 default: 5549 return false; 5550 } 5551 } 5552 } 5553 5554 @Override 5555 public boolean hasUidSigningCertificate( 5556 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5557 final int callingUid = Binder.getCallingUid(); 5558 final int callingUserId = UserHandle.getUserId(callingUid); 5559 // Map to base uids. 5560 uid = UserHandle.getAppId(uid); 5561 // reader 5562 synchronized (mPackages) { 5563 final PackageParser.SigningDetails signingDetails; 5564 final Object obj = mSettings.getUserIdLPr(uid); 5565 if (obj != null) { 5566 if (obj instanceof SharedUserSetting) { 5567 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5568 if (isCallerInstantApp) { 5569 return false; 5570 } 5571 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5572 } else if (obj instanceof PackageSetting) { 5573 final PackageSetting ps = (PackageSetting) obj; 5574 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5575 return false; 5576 } 5577 signingDetails = ps.signatures.mSigningDetails; 5578 } else { 5579 return false; 5580 } 5581 } else { 5582 return false; 5583 } 5584 switch (type) { 5585 case CERT_INPUT_RAW_X509: 5586 return signingDetails.hasCertificate(certificate); 5587 case CERT_INPUT_SHA256: 5588 return signingDetails.hasSha256Certificate(certificate); 5589 default: 5590 return false; 5591 } 5592 } 5593 } 5594 5595 /** 5596 * This method should typically only be used when granting or revoking 5597 * permissions, since the app may immediately restart after this call. 5598 * <p> 5599 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5600 * guard your work against the app being relaunched. 5601 */ 5602 private void killUid(int appId, int userId, String reason) { 5603 final long identity = Binder.clearCallingIdentity(); 5604 try { 5605 IActivityManager am = ActivityManager.getService(); 5606 if (am != null) { 5607 try { 5608 am.killUid(appId, userId, reason); 5609 } catch (RemoteException e) { 5610 /* ignore - same process */ 5611 } 5612 } 5613 } finally { 5614 Binder.restoreCallingIdentity(identity); 5615 } 5616 } 5617 5618 /** 5619 * If the database version for this type of package (internal storage or 5620 * external storage) is less than the version where package signatures 5621 * were updated, return true. 5622 */ 5623 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5624 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5625 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5626 } 5627 5628 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5629 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5630 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5631 } 5632 5633 @Override 5634 public List<String> getAllPackages() { 5635 final int callingUid = Binder.getCallingUid(); 5636 final int callingUserId = UserHandle.getUserId(callingUid); 5637 synchronized (mPackages) { 5638 if (canViewInstantApps(callingUid, callingUserId)) { 5639 return new ArrayList<String>(mPackages.keySet()); 5640 } 5641 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5642 final List<String> result = new ArrayList<>(); 5643 if (instantAppPkgName != null) { 5644 // caller is an instant application; filter unexposed applications 5645 for (PackageParser.Package pkg : mPackages.values()) { 5646 if (!pkg.visibleToInstantApps) { 5647 continue; 5648 } 5649 result.add(pkg.packageName); 5650 } 5651 } else { 5652 // caller is a normal application; filter instant applications 5653 for (PackageParser.Package pkg : mPackages.values()) { 5654 final PackageSetting ps = 5655 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5656 if (ps != null 5657 && ps.getInstantApp(callingUserId) 5658 && !mInstantAppRegistry.isInstantAccessGranted( 5659 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5660 continue; 5661 } 5662 result.add(pkg.packageName); 5663 } 5664 } 5665 return result; 5666 } 5667 } 5668 5669 @Override 5670 public String[] getPackagesForUid(int uid) { 5671 final int callingUid = Binder.getCallingUid(); 5672 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5673 final int userId = UserHandle.getUserId(uid); 5674 uid = UserHandle.getAppId(uid); 5675 // reader 5676 synchronized (mPackages) { 5677 Object obj = mSettings.getUserIdLPr(uid); 5678 if (obj instanceof SharedUserSetting) { 5679 if (isCallerInstantApp) { 5680 return null; 5681 } 5682 final SharedUserSetting sus = (SharedUserSetting) obj; 5683 final int N = sus.packages.size(); 5684 String[] res = new String[N]; 5685 final Iterator<PackageSetting> it = sus.packages.iterator(); 5686 int i = 0; 5687 while (it.hasNext()) { 5688 PackageSetting ps = it.next(); 5689 if (ps.getInstalled(userId)) { 5690 res[i++] = ps.name; 5691 } else { 5692 res = ArrayUtils.removeElement(String.class, res, res[i]); 5693 } 5694 } 5695 return res; 5696 } else if (obj instanceof PackageSetting) { 5697 final PackageSetting ps = (PackageSetting) obj; 5698 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5699 return new String[]{ps.name}; 5700 } 5701 } 5702 } 5703 return null; 5704 } 5705 5706 @Override 5707 public String getNameForUid(int uid) { 5708 final int callingUid = Binder.getCallingUid(); 5709 if (getInstantAppPackageName(callingUid) != null) { 5710 return null; 5711 } 5712 synchronized (mPackages) { 5713 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5714 if (obj instanceof SharedUserSetting) { 5715 final SharedUserSetting sus = (SharedUserSetting) obj; 5716 return sus.name + ":" + sus.userId; 5717 } else if (obj instanceof PackageSetting) { 5718 final PackageSetting ps = (PackageSetting) obj; 5719 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5720 return null; 5721 } 5722 return ps.name; 5723 } 5724 return null; 5725 } 5726 } 5727 5728 @Override 5729 public String[] getNamesForUids(int[] uids) { 5730 if (uids == null || uids.length == 0) { 5731 return null; 5732 } 5733 final int callingUid = Binder.getCallingUid(); 5734 if (getInstantAppPackageName(callingUid) != null) { 5735 return null; 5736 } 5737 final String[] names = new String[uids.length]; 5738 synchronized (mPackages) { 5739 for (int i = uids.length - 1; i >= 0; i--) { 5740 final int uid = uids[i]; 5741 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5742 if (obj instanceof SharedUserSetting) { 5743 final SharedUserSetting sus = (SharedUserSetting) obj; 5744 names[i] = "shared:" + sus.name; 5745 } else if (obj instanceof PackageSetting) { 5746 final PackageSetting ps = (PackageSetting) obj; 5747 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5748 names[i] = null; 5749 } else { 5750 names[i] = ps.name; 5751 } 5752 } else { 5753 names[i] = null; 5754 } 5755 } 5756 } 5757 return names; 5758 } 5759 5760 @Override 5761 public int getUidForSharedUser(String sharedUserName) { 5762 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5763 return -1; 5764 } 5765 if (sharedUserName == null) { 5766 return -1; 5767 } 5768 // reader 5769 synchronized (mPackages) { 5770 SharedUserSetting suid; 5771 try { 5772 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5773 if (suid != null) { 5774 return suid.userId; 5775 } 5776 } catch (PackageManagerException ignore) { 5777 // can't happen, but, still need to catch it 5778 } 5779 return -1; 5780 } 5781 } 5782 5783 @Override 5784 public int getFlagsForUid(int uid) { 5785 final int callingUid = Binder.getCallingUid(); 5786 if (getInstantAppPackageName(callingUid) != null) { 5787 return 0; 5788 } 5789 synchronized (mPackages) { 5790 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5791 if (obj instanceof SharedUserSetting) { 5792 final SharedUserSetting sus = (SharedUserSetting) obj; 5793 return sus.pkgFlags; 5794 } else if (obj instanceof PackageSetting) { 5795 final PackageSetting ps = (PackageSetting) obj; 5796 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5797 return 0; 5798 } 5799 return ps.pkgFlags; 5800 } 5801 } 5802 return 0; 5803 } 5804 5805 @Override 5806 public int getPrivateFlagsForUid(int uid) { 5807 final int callingUid = Binder.getCallingUid(); 5808 if (getInstantAppPackageName(callingUid) != null) { 5809 return 0; 5810 } 5811 synchronized (mPackages) { 5812 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5813 if (obj instanceof SharedUserSetting) { 5814 final SharedUserSetting sus = (SharedUserSetting) obj; 5815 return sus.pkgPrivateFlags; 5816 } else if (obj instanceof PackageSetting) { 5817 final PackageSetting ps = (PackageSetting) obj; 5818 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5819 return 0; 5820 } 5821 return ps.pkgPrivateFlags; 5822 } 5823 } 5824 return 0; 5825 } 5826 5827 @Override 5828 public boolean isUidPrivileged(int uid) { 5829 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5830 return false; 5831 } 5832 uid = UserHandle.getAppId(uid); 5833 // reader 5834 synchronized (mPackages) { 5835 Object obj = mSettings.getUserIdLPr(uid); 5836 if (obj instanceof SharedUserSetting) { 5837 final SharedUserSetting sus = (SharedUserSetting) obj; 5838 final Iterator<PackageSetting> it = sus.packages.iterator(); 5839 while (it.hasNext()) { 5840 if (it.next().isPrivileged()) { 5841 return true; 5842 } 5843 } 5844 } else if (obj instanceof PackageSetting) { 5845 final PackageSetting ps = (PackageSetting) obj; 5846 return ps.isPrivileged(); 5847 } 5848 } 5849 return false; 5850 } 5851 5852 @Override 5853 public String[] getAppOpPermissionPackages(String permName) { 5854 return mPermissionManager.getAppOpPermissionPackages(permName); 5855 } 5856 5857 @Override 5858 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5859 int flags, int userId) { 5860 return resolveIntentInternal( 5861 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5862 } 5863 5864 /** 5865 * Normally instant apps can only be resolved when they're visible to the caller. 5866 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5867 * since we need to allow the system to start any installed application. 5868 */ 5869 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5870 int flags, int userId, boolean resolveForStart) { 5871 try { 5872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5873 5874 if (!sUserManager.exists(userId)) return null; 5875 final int callingUid = Binder.getCallingUid(); 5876 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5877 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5878 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5879 5880 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5881 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5882 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5883 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5884 5885 final ResolveInfo bestChoice = 5886 chooseBestActivity(intent, resolvedType, flags, query, userId); 5887 return bestChoice; 5888 } finally { 5889 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5890 } 5891 } 5892 5893 @Override 5894 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5895 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5896 throw new SecurityException( 5897 "findPersistentPreferredActivity can only be run by the system"); 5898 } 5899 if (!sUserManager.exists(userId)) { 5900 return null; 5901 } 5902 final int callingUid = Binder.getCallingUid(); 5903 intent = updateIntentForResolve(intent); 5904 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5905 final int flags = updateFlagsForResolve( 5906 0, userId, intent, callingUid, false /*includeInstantApps*/); 5907 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5908 userId); 5909 synchronized (mPackages) { 5910 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5911 userId); 5912 } 5913 } 5914 5915 @Override 5916 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5917 IntentFilter filter, int match, ComponentName activity) { 5918 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5919 return; 5920 } 5921 final int userId = UserHandle.getCallingUserId(); 5922 if (DEBUG_PREFERRED) { 5923 Log.v(TAG, "setLastChosenActivity intent=" + intent 5924 + " resolvedType=" + resolvedType 5925 + " flags=" + flags 5926 + " filter=" + filter 5927 + " match=" + match 5928 + " activity=" + activity); 5929 filter.dump(new PrintStreamPrinter(System.out), " "); 5930 } 5931 intent.setComponent(null); 5932 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5933 userId); 5934 // Find any earlier preferred or last chosen entries and nuke them 5935 findPreferredActivity(intent, resolvedType, 5936 flags, query, 0, false, true, false, userId); 5937 // Add the new activity as the last chosen for this filter 5938 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5939 "Setting last chosen"); 5940 } 5941 5942 @Override 5943 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5944 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5945 return null; 5946 } 5947 final int userId = UserHandle.getCallingUserId(); 5948 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5949 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5950 userId); 5951 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5952 false, false, false, userId); 5953 } 5954 5955 /** 5956 * Returns whether or not instant apps have been disabled remotely. 5957 */ 5958 private boolean areWebInstantAppsDisabled() { 5959 return mWebInstantAppsDisabled; 5960 } 5961 5962 private boolean isInstantAppResolutionAllowed( 5963 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5964 boolean skipPackageCheck) { 5965 if (mInstantAppResolverConnection == null) { 5966 return false; 5967 } 5968 if (mInstantAppInstallerActivity == null) { 5969 return false; 5970 } 5971 if (intent.getComponent() != null) { 5972 return false; 5973 } 5974 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5975 return false; 5976 } 5977 if (!skipPackageCheck && intent.getPackage() != null) { 5978 return false; 5979 } 5980 if (!intent.isWebIntent()) { 5981 // for non web intents, we should not resolve externally if an app already exists to 5982 // handle it or if the caller didn't explicitly request it. 5983 if ((resolvedActivities != null && resolvedActivities.size() != 0) 5984 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 5985 return false; 5986 } 5987 } else { 5988 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 5989 return false; 5990 } else if (areWebInstantAppsDisabled()) { 5991 return false; 5992 } 5993 } 5994 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5995 // Or if there's already an ephemeral app installed that handles the action 5996 synchronized (mPackages) { 5997 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5998 for (int n = 0; n < count; n++) { 5999 final ResolveInfo info = resolvedActivities.get(n); 6000 final String packageName = info.activityInfo.packageName; 6001 final PackageSetting ps = mSettings.mPackages.get(packageName); 6002 if (ps != null) { 6003 // only check domain verification status if the app is not a browser 6004 if (!info.handleAllWebDataURI) { 6005 // Try to get the status from User settings first 6006 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6007 final int status = (int) (packedStatus >> 32); 6008 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6009 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6010 if (DEBUG_INSTANT) { 6011 Slog.v(TAG, "DENY instant app;" 6012 + " pkg: " + packageName + ", status: " + status); 6013 } 6014 return false; 6015 } 6016 } 6017 if (ps.getInstantApp(userId)) { 6018 if (DEBUG_INSTANT) { 6019 Slog.v(TAG, "DENY instant app installed;" 6020 + " pkg: " + packageName); 6021 } 6022 return false; 6023 } 6024 } 6025 } 6026 } 6027 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6028 return true; 6029 } 6030 6031 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6032 Intent origIntent, String resolvedType, String callingPackage, 6033 Bundle verificationBundle, int userId) { 6034 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6035 new InstantAppRequest(responseObj, origIntent, resolvedType, 6036 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6037 mHandler.sendMessage(msg); 6038 } 6039 6040 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6041 int flags, List<ResolveInfo> query, int userId) { 6042 if (query != null) { 6043 final int N = query.size(); 6044 if (N == 1) { 6045 return query.get(0); 6046 } else if (N > 1) { 6047 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6048 // If there is more than one activity with the same priority, 6049 // then let the user decide between them. 6050 ResolveInfo r0 = query.get(0); 6051 ResolveInfo r1 = query.get(1); 6052 if (DEBUG_INTENT_MATCHING || debug) { 6053 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6054 + r1.activityInfo.name + "=" + r1.priority); 6055 } 6056 // If the first activity has a higher priority, or a different 6057 // default, then it is always desirable to pick it. 6058 if (r0.priority != r1.priority 6059 || r0.preferredOrder != r1.preferredOrder 6060 || r0.isDefault != r1.isDefault) { 6061 return query.get(0); 6062 } 6063 // If we have saved a preference for a preferred activity for 6064 // this Intent, use that. 6065 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6066 flags, query, r0.priority, true, false, debug, userId); 6067 if (ri != null) { 6068 return ri; 6069 } 6070 // If we have an ephemeral app, use it 6071 for (int i = 0; i < N; i++) { 6072 ri = query.get(i); 6073 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6074 final String packageName = ri.activityInfo.packageName; 6075 final PackageSetting ps = mSettings.mPackages.get(packageName); 6076 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6077 final int status = (int)(packedStatus >> 32); 6078 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6079 return ri; 6080 } 6081 } 6082 } 6083 ri = new ResolveInfo(mResolveInfo); 6084 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6085 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6086 // If all of the options come from the same package, show the application's 6087 // label and icon instead of the generic resolver's. 6088 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6089 // and then throw away the ResolveInfo itself, meaning that the caller loses 6090 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6091 // a fallback for this case; we only set the target package's resources on 6092 // the ResolveInfo, not the ActivityInfo. 6093 final String intentPackage = intent.getPackage(); 6094 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6095 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6096 ri.resolvePackageName = intentPackage; 6097 if (userNeedsBadging(userId)) { 6098 ri.noResourceId = true; 6099 } else { 6100 ri.icon = appi.icon; 6101 } 6102 ri.iconResourceId = appi.icon; 6103 ri.labelRes = appi.labelRes; 6104 } 6105 ri.activityInfo.applicationInfo = new ApplicationInfo( 6106 ri.activityInfo.applicationInfo); 6107 if (userId != 0) { 6108 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6109 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6110 } 6111 // Make sure that the resolver is displayable in car mode 6112 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6113 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6114 return ri; 6115 } 6116 } 6117 return null; 6118 } 6119 6120 /** 6121 * Return true if the given list is not empty and all of its contents have 6122 * an activityInfo with the given package name. 6123 */ 6124 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6125 if (ArrayUtils.isEmpty(list)) { 6126 return false; 6127 } 6128 for (int i = 0, N = list.size(); i < N; i++) { 6129 final ResolveInfo ri = list.get(i); 6130 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6131 if (ai == null || !packageName.equals(ai.packageName)) { 6132 return false; 6133 } 6134 } 6135 return true; 6136 } 6137 6138 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6139 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6140 final int N = query.size(); 6141 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6142 .get(userId); 6143 // Get the list of persistent preferred activities that handle the intent 6144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6145 List<PersistentPreferredActivity> pprefs = ppir != null 6146 ? ppir.queryIntent(intent, resolvedType, 6147 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6148 userId) 6149 : null; 6150 if (pprefs != null && pprefs.size() > 0) { 6151 final int M = pprefs.size(); 6152 for (int i=0; i<M; i++) { 6153 final PersistentPreferredActivity ppa = pprefs.get(i); 6154 if (DEBUG_PREFERRED || debug) { 6155 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6156 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6157 + "\n component=" + ppa.mComponent); 6158 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6159 } 6160 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6161 flags | MATCH_DISABLED_COMPONENTS, userId); 6162 if (DEBUG_PREFERRED || debug) { 6163 Slog.v(TAG, "Found persistent preferred activity:"); 6164 if (ai != null) { 6165 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6166 } else { 6167 Slog.v(TAG, " null"); 6168 } 6169 } 6170 if (ai == null) { 6171 // This previously registered persistent preferred activity 6172 // component is no longer known. Ignore it and do NOT remove it. 6173 continue; 6174 } 6175 for (int j=0; j<N; j++) { 6176 final ResolveInfo ri = query.get(j); 6177 if (!ri.activityInfo.applicationInfo.packageName 6178 .equals(ai.applicationInfo.packageName)) { 6179 continue; 6180 } 6181 if (!ri.activityInfo.name.equals(ai.name)) { 6182 continue; 6183 } 6184 // Found a persistent preference that can handle the intent. 6185 if (DEBUG_PREFERRED || debug) { 6186 Slog.v(TAG, "Returning persistent preferred activity: " + 6187 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6188 } 6189 return ri; 6190 } 6191 } 6192 } 6193 return null; 6194 } 6195 6196 // TODO: handle preferred activities missing while user has amnesia 6197 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6198 List<ResolveInfo> query, int priority, boolean always, 6199 boolean removeMatches, boolean debug, int userId) { 6200 if (!sUserManager.exists(userId)) return null; 6201 final int callingUid = Binder.getCallingUid(); 6202 flags = updateFlagsForResolve( 6203 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6204 intent = updateIntentForResolve(intent); 6205 // writer 6206 synchronized (mPackages) { 6207 // Try to find a matching persistent preferred activity. 6208 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6209 debug, userId); 6210 6211 // If a persistent preferred activity matched, use it. 6212 if (pri != null) { 6213 return pri; 6214 } 6215 6216 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6217 // Get the list of preferred activities that handle the intent 6218 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6219 List<PreferredActivity> prefs = pir != null 6220 ? pir.queryIntent(intent, resolvedType, 6221 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6222 userId) 6223 : null; 6224 if (prefs != null && prefs.size() > 0) { 6225 boolean changed = false; 6226 try { 6227 // First figure out how good the original match set is. 6228 // We will only allow preferred activities that came 6229 // from the same match quality. 6230 int match = 0; 6231 6232 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6233 6234 final int N = query.size(); 6235 for (int j=0; j<N; j++) { 6236 final ResolveInfo ri = query.get(j); 6237 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6238 + ": 0x" + Integer.toHexString(match)); 6239 if (ri.match > match) { 6240 match = ri.match; 6241 } 6242 } 6243 6244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6245 + Integer.toHexString(match)); 6246 6247 match &= IntentFilter.MATCH_CATEGORY_MASK; 6248 final int M = prefs.size(); 6249 for (int i=0; i<M; i++) { 6250 final PreferredActivity pa = prefs.get(i); 6251 if (DEBUG_PREFERRED || debug) { 6252 Slog.v(TAG, "Checking PreferredActivity ds=" 6253 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6254 + "\n component=" + pa.mPref.mComponent); 6255 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6256 } 6257 if (pa.mPref.mMatch != match) { 6258 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6259 + Integer.toHexString(pa.mPref.mMatch)); 6260 continue; 6261 } 6262 // If it's not an "always" type preferred activity and that's what we're 6263 // looking for, skip it. 6264 if (always && !pa.mPref.mAlways) { 6265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6266 continue; 6267 } 6268 final ActivityInfo ai = getActivityInfo( 6269 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6270 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6271 userId); 6272 if (DEBUG_PREFERRED || debug) { 6273 Slog.v(TAG, "Found preferred activity:"); 6274 if (ai != null) { 6275 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6276 } else { 6277 Slog.v(TAG, " null"); 6278 } 6279 } 6280 if (ai == null) { 6281 // This previously registered preferred activity 6282 // component is no longer known. Most likely an update 6283 // to the app was installed and in the new version this 6284 // component no longer exists. Clean it up by removing 6285 // it from the preferred activities list, and skip it. 6286 Slog.w(TAG, "Removing dangling preferred activity: " 6287 + pa.mPref.mComponent); 6288 pir.removeFilter(pa); 6289 changed = true; 6290 continue; 6291 } 6292 for (int j=0; j<N; j++) { 6293 final ResolveInfo ri = query.get(j); 6294 if (!ri.activityInfo.applicationInfo.packageName 6295 .equals(ai.applicationInfo.packageName)) { 6296 continue; 6297 } 6298 if (!ri.activityInfo.name.equals(ai.name)) { 6299 continue; 6300 } 6301 6302 if (removeMatches) { 6303 pir.removeFilter(pa); 6304 changed = true; 6305 if (DEBUG_PREFERRED) { 6306 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6307 } 6308 break; 6309 } 6310 6311 // Okay we found a previously set preferred or last chosen app. 6312 // If the result set is different from when this 6313 // was created, and is not a subset of the preferred set, we need to 6314 // clear it and re-ask the user their preference, if we're looking for 6315 // an "always" type entry. 6316 if (always && !pa.mPref.sameSet(query)) { 6317 if (pa.mPref.isSuperset(query)) { 6318 // some components of the set are no longer present in 6319 // the query, but the preferred activity can still be reused 6320 if (DEBUG_PREFERRED) { 6321 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6322 + " still valid as only non-preferred components" 6323 + " were removed for " + intent + " type " 6324 + resolvedType); 6325 } 6326 // remove obsolete components and re-add the up-to-date filter 6327 PreferredActivity freshPa = new PreferredActivity(pa, 6328 pa.mPref.mMatch, 6329 pa.mPref.discardObsoleteComponents(query), 6330 pa.mPref.mComponent, 6331 pa.mPref.mAlways); 6332 pir.removeFilter(pa); 6333 pir.addFilter(freshPa); 6334 changed = true; 6335 } else { 6336 Slog.i(TAG, 6337 "Result set changed, dropping preferred activity for " 6338 + intent + " type " + resolvedType); 6339 if (DEBUG_PREFERRED) { 6340 Slog.v(TAG, "Removing preferred activity since set changed " 6341 + pa.mPref.mComponent); 6342 } 6343 pir.removeFilter(pa); 6344 // Re-add the filter as a "last chosen" entry (!always) 6345 PreferredActivity lastChosen = new PreferredActivity( 6346 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6347 pir.addFilter(lastChosen); 6348 changed = true; 6349 return null; 6350 } 6351 } 6352 6353 // Yay! Either the set matched or we're looking for the last chosen 6354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6355 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6356 return ri; 6357 } 6358 } 6359 } finally { 6360 if (changed) { 6361 if (DEBUG_PREFERRED) { 6362 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6363 } 6364 scheduleWritePackageRestrictionsLocked(userId); 6365 } 6366 } 6367 } 6368 } 6369 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6370 return null; 6371 } 6372 6373 /* 6374 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6375 */ 6376 @Override 6377 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6378 int targetUserId) { 6379 mContext.enforceCallingOrSelfPermission( 6380 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6381 List<CrossProfileIntentFilter> matches = 6382 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6383 if (matches != null) { 6384 int size = matches.size(); 6385 for (int i = 0; i < size; i++) { 6386 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6387 } 6388 } 6389 if (intent.hasWebURI()) { 6390 // cross-profile app linking works only towards the parent. 6391 final int callingUid = Binder.getCallingUid(); 6392 final UserInfo parent = getProfileParent(sourceUserId); 6393 synchronized(mPackages) { 6394 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6395 false /*includeInstantApps*/); 6396 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6397 intent, resolvedType, flags, sourceUserId, parent.id); 6398 return xpDomainInfo != null; 6399 } 6400 } 6401 return false; 6402 } 6403 6404 private UserInfo getProfileParent(int userId) { 6405 final long identity = Binder.clearCallingIdentity(); 6406 try { 6407 return sUserManager.getProfileParent(userId); 6408 } finally { 6409 Binder.restoreCallingIdentity(identity); 6410 } 6411 } 6412 6413 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6414 String resolvedType, int userId) { 6415 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6416 if (resolver != null) { 6417 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6418 } 6419 return null; 6420 } 6421 6422 @Override 6423 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6424 String resolvedType, int flags, int userId) { 6425 try { 6426 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6427 6428 return new ParceledListSlice<>( 6429 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6430 } finally { 6431 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6432 } 6433 } 6434 6435 /** 6436 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6437 * instant, returns {@code null}. 6438 */ 6439 private String getInstantAppPackageName(int callingUid) { 6440 synchronized (mPackages) { 6441 // If the caller is an isolated app use the owner's uid for the lookup. 6442 if (Process.isIsolated(callingUid)) { 6443 callingUid = mIsolatedOwners.get(callingUid); 6444 } 6445 final int appId = UserHandle.getAppId(callingUid); 6446 final Object obj = mSettings.getUserIdLPr(appId); 6447 if (obj instanceof PackageSetting) { 6448 final PackageSetting ps = (PackageSetting) obj; 6449 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6450 return isInstantApp ? ps.pkg.packageName : null; 6451 } 6452 } 6453 return null; 6454 } 6455 6456 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6457 String resolvedType, int flags, int userId) { 6458 return queryIntentActivitiesInternal( 6459 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6460 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6461 } 6462 6463 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6464 String resolvedType, int flags, int filterCallingUid, int userId, 6465 boolean resolveForStart, boolean allowDynamicSplits) { 6466 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6467 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6468 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6469 false /* requireFullPermission */, false /* checkShell */, 6470 "query intent activities"); 6471 final String pkgName = intent.getPackage(); 6472 ComponentName comp = intent.getComponent(); 6473 if (comp == null) { 6474 if (intent.getSelector() != null) { 6475 intent = intent.getSelector(); 6476 comp = intent.getComponent(); 6477 } 6478 } 6479 6480 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6481 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6482 if (comp != null) { 6483 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6484 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6485 if (ai != null) { 6486 // When specifying an explicit component, we prevent the activity from being 6487 // used when either 1) the calling package is normal and the activity is within 6488 // an ephemeral application or 2) the calling package is ephemeral and the 6489 // activity is not visible to ephemeral applications. 6490 final boolean matchInstantApp = 6491 (flags & PackageManager.MATCH_INSTANT) != 0; 6492 final boolean matchVisibleToInstantAppOnly = 6493 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6494 final boolean matchExplicitlyVisibleOnly = 6495 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6496 final boolean isCallerInstantApp = 6497 instantAppPkgName != null; 6498 final boolean isTargetSameInstantApp = 6499 comp.getPackageName().equals(instantAppPkgName); 6500 final boolean isTargetInstantApp = 6501 (ai.applicationInfo.privateFlags 6502 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6503 final boolean isTargetVisibleToInstantApp = 6504 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6505 final boolean isTargetExplicitlyVisibleToInstantApp = 6506 isTargetVisibleToInstantApp 6507 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6508 final boolean isTargetHiddenFromInstantApp = 6509 !isTargetVisibleToInstantApp 6510 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6511 final boolean blockResolution = 6512 !isTargetSameInstantApp 6513 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6514 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6515 && isTargetHiddenFromInstantApp)); 6516 if (!blockResolution) { 6517 final ResolveInfo ri = new ResolveInfo(); 6518 ri.activityInfo = ai; 6519 list.add(ri); 6520 } 6521 } 6522 return applyPostResolutionFilter( 6523 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6524 } 6525 6526 // reader 6527 boolean sortResult = false; 6528 boolean addInstant = false; 6529 List<ResolveInfo> result; 6530 synchronized (mPackages) { 6531 if (pkgName == null) { 6532 List<CrossProfileIntentFilter> matchingFilters = 6533 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6534 // Check for results that need to skip the current profile. 6535 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6536 resolvedType, flags, userId); 6537 if (xpResolveInfo != null) { 6538 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6539 xpResult.add(xpResolveInfo); 6540 return applyPostResolutionFilter( 6541 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6542 allowDynamicSplits, filterCallingUid, userId, intent); 6543 } 6544 6545 // Check for results in the current profile. 6546 result = filterIfNotSystemUser(mActivities.queryIntent( 6547 intent, resolvedType, flags, userId), userId); 6548 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 6549 false /*skipPackageCheck*/); 6550 // Check for cross profile results. 6551 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6552 xpResolveInfo = queryCrossProfileIntents( 6553 matchingFilters, intent, resolvedType, flags, userId, 6554 hasNonNegativePriorityResult); 6555 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6556 boolean isVisibleToUser = filterIfNotSystemUser( 6557 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6558 if (isVisibleToUser) { 6559 result.add(xpResolveInfo); 6560 sortResult = true; 6561 } 6562 } 6563 if (intent.hasWebURI()) { 6564 CrossProfileDomainInfo xpDomainInfo = null; 6565 final UserInfo parent = getProfileParent(userId); 6566 if (parent != null) { 6567 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6568 flags, userId, parent.id); 6569 } 6570 if (xpDomainInfo != null) { 6571 if (xpResolveInfo != null) { 6572 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6573 // in the result. 6574 result.remove(xpResolveInfo); 6575 } 6576 if (result.size() == 0 && !addInstant) { 6577 // No result in current profile, but found candidate in parent user. 6578 // And we are not going to add emphemeral app, so we can return the 6579 // result straight away. 6580 result.add(xpDomainInfo.resolveInfo); 6581 return applyPostResolutionFilter(result, instantAppPkgName, 6582 allowDynamicSplits, filterCallingUid, userId, intent); 6583 } 6584 } else if (result.size() <= 1 && !addInstant) { 6585 // No result in parent user and <= 1 result in current profile, and we 6586 // are not going to add emphemeral app, so we can return the result without 6587 // further processing. 6588 return applyPostResolutionFilter(result, instantAppPkgName, 6589 allowDynamicSplits, filterCallingUid, userId, intent); 6590 } 6591 // We have more than one candidate (combining results from current and parent 6592 // profile), so we need filtering and sorting. 6593 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6594 intent, flags, result, xpDomainInfo, userId); 6595 sortResult = true; 6596 } 6597 } else { 6598 final PackageParser.Package pkg = mPackages.get(pkgName); 6599 result = null; 6600 if (pkg != null) { 6601 result = filterIfNotSystemUser( 6602 mActivities.queryIntentForPackage( 6603 intent, resolvedType, flags, pkg.activities, userId), 6604 userId); 6605 } 6606 if (result == null || result.size() == 0) { 6607 // the caller wants to resolve for a particular package; however, there 6608 // were no installed results, so, try to find an ephemeral result 6609 addInstant = isInstantAppResolutionAllowed( 6610 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6611 if (result == null) { 6612 result = new ArrayList<>(); 6613 } 6614 } 6615 } 6616 } 6617 if (addInstant) { 6618 result = maybeAddInstantAppInstaller( 6619 result, intent, resolvedType, flags, userId, resolveForStart); 6620 } 6621 if (sortResult) { 6622 Collections.sort(result, mResolvePrioritySorter); 6623 } 6624 return applyPostResolutionFilter( 6625 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6626 } 6627 6628 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6629 String resolvedType, int flags, int userId, boolean resolveForStart) { 6630 // first, check to see if we've got an instant app already installed 6631 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6632 ResolveInfo localInstantApp = null; 6633 boolean blockResolution = false; 6634 if (!alreadyResolvedLocally) { 6635 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6636 flags 6637 | PackageManager.GET_RESOLVED_FILTER 6638 | PackageManager.MATCH_INSTANT 6639 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6640 userId); 6641 for (int i = instantApps.size() - 1; i >= 0; --i) { 6642 final ResolveInfo info = instantApps.get(i); 6643 final String packageName = info.activityInfo.packageName; 6644 final PackageSetting ps = mSettings.mPackages.get(packageName); 6645 if (ps.getInstantApp(userId)) { 6646 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6647 final int status = (int)(packedStatus >> 32); 6648 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6649 // there's a local instant application installed, but, the user has 6650 // chosen to never use it; skip resolution and don't acknowledge 6651 // an instant application is even available 6652 if (DEBUG_INSTANT) { 6653 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6654 } 6655 blockResolution = true; 6656 break; 6657 } else { 6658 // we have a locally installed instant application; skip resolution 6659 // but acknowledge there's an instant application available 6660 if (DEBUG_INSTANT) { 6661 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6662 } 6663 localInstantApp = info; 6664 break; 6665 } 6666 } 6667 } 6668 } 6669 // no app installed, let's see if one's available 6670 AuxiliaryResolveInfo auxiliaryResponse = null; 6671 if (!blockResolution) { 6672 if (localInstantApp == null) { 6673 // we don't have an instant app locally, resolve externally 6674 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6675 final InstantAppRequest requestObject = new InstantAppRequest( 6676 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6677 null /*callingPackage*/, userId, null /*verificationBundle*/, 6678 resolveForStart); 6679 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6680 mInstantAppResolverConnection, requestObject); 6681 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6682 } else { 6683 // we have an instant application locally, but, we can't admit that since 6684 // callers shouldn't be able to determine prior browsing. create a dummy 6685 // auxiliary response so the downstream code behaves as if there's an 6686 // instant application available externally. when it comes time to start 6687 // the instant application, we'll do the right thing. 6688 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6689 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6690 ai.packageName, ai.versionCode, null /* splitName */); 6691 } 6692 } 6693 if (intent.isWebIntent() && auxiliaryResponse == null) { 6694 return result; 6695 } 6696 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6697 if (ps == null 6698 || ps.getUserState().get(userId) == null 6699 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 6700 return result; 6701 } 6702 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6703 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6704 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6705 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6706 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6707 // add a non-generic filter 6708 ephemeralInstaller.filter = new IntentFilter(); 6709 if (intent.getAction() != null) { 6710 ephemeralInstaller.filter.addAction(intent.getAction()); 6711 } 6712 if (intent.getData() != null && intent.getData().getPath() != null) { 6713 ephemeralInstaller.filter.addDataPath( 6714 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6715 } 6716 ephemeralInstaller.isInstantAppAvailable = true; 6717 // make sure this resolver is the default 6718 ephemeralInstaller.isDefault = true; 6719 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6720 if (DEBUG_INSTANT) { 6721 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6722 } 6723 6724 result.add(ephemeralInstaller); 6725 return result; 6726 } 6727 6728 private static class CrossProfileDomainInfo { 6729 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6730 ResolveInfo resolveInfo; 6731 /* Best domain verification status of the activities found in the other profile */ 6732 int bestDomainVerificationStatus; 6733 } 6734 6735 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6736 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6737 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6738 sourceUserId)) { 6739 return null; 6740 } 6741 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6742 resolvedType, flags, parentUserId); 6743 6744 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6745 return null; 6746 } 6747 CrossProfileDomainInfo result = null; 6748 int size = resultTargetUser.size(); 6749 for (int i = 0; i < size; i++) { 6750 ResolveInfo riTargetUser = resultTargetUser.get(i); 6751 // Intent filter verification is only for filters that specify a host. So don't return 6752 // those that handle all web uris. 6753 if (riTargetUser.handleAllWebDataURI) { 6754 continue; 6755 } 6756 String packageName = riTargetUser.activityInfo.packageName; 6757 PackageSetting ps = mSettings.mPackages.get(packageName); 6758 if (ps == null) { 6759 continue; 6760 } 6761 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6762 int status = (int)(verificationState >> 32); 6763 if (result == null) { 6764 result = new CrossProfileDomainInfo(); 6765 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6766 sourceUserId, parentUserId); 6767 result.bestDomainVerificationStatus = status; 6768 } else { 6769 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6770 result.bestDomainVerificationStatus); 6771 } 6772 } 6773 // Don't consider matches with status NEVER across profiles. 6774 if (result != null && result.bestDomainVerificationStatus 6775 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6776 return null; 6777 } 6778 return result; 6779 } 6780 6781 /** 6782 * Verification statuses are ordered from the worse to the best, except for 6783 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6784 */ 6785 private int bestDomainVerificationStatus(int status1, int status2) { 6786 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6787 return status2; 6788 } 6789 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6790 return status1; 6791 } 6792 return (int) MathUtils.max(status1, status2); 6793 } 6794 6795 private boolean isUserEnabled(int userId) { 6796 long callingId = Binder.clearCallingIdentity(); 6797 try { 6798 UserInfo userInfo = sUserManager.getUserInfo(userId); 6799 return userInfo != null && userInfo.isEnabled(); 6800 } finally { 6801 Binder.restoreCallingIdentity(callingId); 6802 } 6803 } 6804 6805 /** 6806 * Filter out activities with systemUserOnly flag set, when current user is not System. 6807 * 6808 * @return filtered list 6809 */ 6810 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6811 if (userId == UserHandle.USER_SYSTEM) { 6812 return resolveInfos; 6813 } 6814 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6815 ResolveInfo info = resolveInfos.get(i); 6816 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6817 resolveInfos.remove(i); 6818 } 6819 } 6820 return resolveInfos; 6821 } 6822 6823 /** 6824 * Filters out ephemeral activities. 6825 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6826 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6827 * 6828 * @param resolveInfos The pre-filtered list of resolved activities 6829 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6830 * is performed. 6831 * @param intent 6832 * @return A filtered list of resolved activities. 6833 */ 6834 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6835 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId, 6836 Intent intent) { 6837 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(); 6838 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6839 final ResolveInfo info = resolveInfos.get(i); 6840 // remove locally resolved instant app web results when disabled 6841 if (info.isInstantAppAvailable && blockInstant) { 6842 resolveInfos.remove(i); 6843 continue; 6844 } 6845 // allow activities that are defined in the provided package 6846 if (allowDynamicSplits 6847 && info.activityInfo != null 6848 && info.activityInfo.splitName != null 6849 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6850 info.activityInfo.splitName)) { 6851 if (mInstantAppInstallerActivity == null) { 6852 if (DEBUG_INSTALL) { 6853 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6854 } 6855 resolveInfos.remove(i); 6856 continue; 6857 } 6858 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 6859 resolveInfos.remove(i); 6860 continue; 6861 } 6862 // requested activity is defined in a split that hasn't been installed yet. 6863 // add the installer to the resolve list 6864 if (DEBUG_INSTALL) { 6865 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6866 } 6867 final ResolveInfo installerInfo = new ResolveInfo( 6868 mInstantAppInstallerInfo); 6869 final ComponentName installFailureActivity = findInstallFailureActivity( 6870 info.activityInfo.packageName, filterCallingUid, userId); 6871 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6872 installFailureActivity, 6873 info.activityInfo.packageName, 6874 info.activityInfo.applicationInfo.versionCode, 6875 info.activityInfo.splitName); 6876 // add a non-generic filter 6877 installerInfo.filter = new IntentFilter(); 6878 6879 // This resolve info may appear in the chooser UI, so let us make it 6880 // look as the one it replaces as far as the user is concerned which 6881 // requires loading the correct label and icon for the resolve info. 6882 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6883 installerInfo.labelRes = info.resolveLabelResId(); 6884 installerInfo.icon = info.resolveIconResId(); 6885 installerInfo.isInstantAppAvailable = true; 6886 resolveInfos.set(i, installerInfo); 6887 continue; 6888 } 6889 // caller is a full app, don't need to apply any other filtering 6890 if (ephemeralPkgName == null) { 6891 continue; 6892 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6893 // caller is same app; don't need to apply any other filtering 6894 continue; 6895 } 6896 // allow activities that have been explicitly exposed to ephemeral apps 6897 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6898 if (!isEphemeralApp 6899 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6900 continue; 6901 } 6902 resolveInfos.remove(i); 6903 } 6904 return resolveInfos; 6905 } 6906 6907 /** 6908 * Returns the activity component that can handle install failures. 6909 * <p>By default, the instant application installer handles failures. However, an 6910 * application may want to handle failures on its own. Applications do this by 6911 * creating an activity with an intent filter that handles the action 6912 * {@link Intent#ACTION_INSTALL_FAILURE}. 6913 */ 6914 private @Nullable ComponentName findInstallFailureActivity( 6915 String packageName, int filterCallingUid, int userId) { 6916 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6917 failureActivityIntent.setPackage(packageName); 6918 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6919 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6920 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6921 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6922 final int NR = result.size(); 6923 if (NR > 0) { 6924 for (int i = 0; i < NR; i++) { 6925 final ResolveInfo info = result.get(i); 6926 if (info.activityInfo.splitName != null) { 6927 continue; 6928 } 6929 return new ComponentName(packageName, info.activityInfo.name); 6930 } 6931 } 6932 return null; 6933 } 6934 6935 /** 6936 * @param resolveInfos list of resolve infos in descending priority order 6937 * @return if the list contains a resolve info with non-negative priority 6938 */ 6939 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6940 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6941 } 6942 6943 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6944 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6945 int userId) { 6946 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6947 6948 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6949 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6950 candidates.size()); 6951 } 6952 6953 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6954 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6955 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6956 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6957 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6958 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6959 6960 synchronized (mPackages) { 6961 final int count = candidates.size(); 6962 // First, try to use linked apps. Partition the candidates into four lists: 6963 // one for the final results, one for the "do not use ever", one for "undefined status" 6964 // and finally one for "browser app type". 6965 for (int n=0; n<count; n++) { 6966 ResolveInfo info = candidates.get(n); 6967 String packageName = info.activityInfo.packageName; 6968 PackageSetting ps = mSettings.mPackages.get(packageName); 6969 if (ps != null) { 6970 // Add to the special match all list (Browser use case) 6971 if (info.handleAllWebDataURI) { 6972 matchAllList.add(info); 6973 continue; 6974 } 6975 // Try to get the status from User settings first 6976 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6977 int status = (int)(packedStatus >> 32); 6978 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6979 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6980 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6981 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6982 + " : linkgen=" + linkGeneration); 6983 } 6984 // Use link-enabled generation as preferredOrder, i.e. 6985 // prefer newly-enabled over earlier-enabled. 6986 info.preferredOrder = linkGeneration; 6987 alwaysList.add(info); 6988 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6989 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6990 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6991 } 6992 neverList.add(info); 6993 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6994 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6995 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6996 } 6997 alwaysAskList.add(info); 6998 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6999 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7000 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7001 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7002 } 7003 undefinedList.add(info); 7004 } 7005 } 7006 } 7007 7008 // We'll want to include browser possibilities in a few cases 7009 boolean includeBrowser = false; 7010 7011 // First try to add the "always" resolution(s) for the current user, if any 7012 if (alwaysList.size() > 0) { 7013 result.addAll(alwaysList); 7014 } else { 7015 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7016 result.addAll(undefinedList); 7017 // Maybe add one for the other profile. 7018 if (xpDomainInfo != null && ( 7019 xpDomainInfo.bestDomainVerificationStatus 7020 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7021 result.add(xpDomainInfo.resolveInfo); 7022 } 7023 includeBrowser = true; 7024 } 7025 7026 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7027 // If there were 'always' entries their preferred order has been set, so we also 7028 // back that off to make the alternatives equivalent 7029 if (alwaysAskList.size() > 0) { 7030 for (ResolveInfo i : result) { 7031 i.preferredOrder = 0; 7032 } 7033 result.addAll(alwaysAskList); 7034 includeBrowser = true; 7035 } 7036 7037 if (includeBrowser) { 7038 // Also add browsers (all of them or only the default one) 7039 if (DEBUG_DOMAIN_VERIFICATION) { 7040 Slog.v(TAG, " ...including browsers in candidate set"); 7041 } 7042 if ((matchFlags & MATCH_ALL) != 0) { 7043 result.addAll(matchAllList); 7044 } else { 7045 // Browser/generic handling case. If there's a default browser, go straight 7046 // to that (but only if there is no other higher-priority match). 7047 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7048 int maxMatchPrio = 0; 7049 ResolveInfo defaultBrowserMatch = null; 7050 final int numCandidates = matchAllList.size(); 7051 for (int n = 0; n < numCandidates; n++) { 7052 ResolveInfo info = matchAllList.get(n); 7053 // track the highest overall match priority... 7054 if (info.priority > maxMatchPrio) { 7055 maxMatchPrio = info.priority; 7056 } 7057 // ...and the highest-priority default browser match 7058 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7059 if (defaultBrowserMatch == null 7060 || (defaultBrowserMatch.priority < info.priority)) { 7061 if (debug) { 7062 Slog.v(TAG, "Considering default browser match " + info); 7063 } 7064 defaultBrowserMatch = info; 7065 } 7066 } 7067 } 7068 if (defaultBrowserMatch != null 7069 && defaultBrowserMatch.priority >= maxMatchPrio 7070 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7071 { 7072 if (debug) { 7073 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7074 } 7075 result.add(defaultBrowserMatch); 7076 } else { 7077 result.addAll(matchAllList); 7078 } 7079 } 7080 7081 // If there is nothing selected, add all candidates and remove the ones that the user 7082 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7083 if (result.size() == 0) { 7084 result.addAll(candidates); 7085 result.removeAll(neverList); 7086 } 7087 } 7088 } 7089 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7090 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7091 result.size()); 7092 for (ResolveInfo info : result) { 7093 Slog.v(TAG, " + " + info.activityInfo); 7094 } 7095 } 7096 return result; 7097 } 7098 7099 // Returns a packed value as a long: 7100 // 7101 // high 'int'-sized word: link status: undefined/ask/never/always. 7102 // low 'int'-sized word: relative priority among 'always' results. 7103 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7104 long result = ps.getDomainVerificationStatusForUser(userId); 7105 // if none available, get the master status 7106 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7107 if (ps.getIntentFilterVerificationInfo() != null) { 7108 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7109 } 7110 } 7111 return result; 7112 } 7113 7114 private ResolveInfo querySkipCurrentProfileIntents( 7115 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7116 int flags, int sourceUserId) { 7117 if (matchingFilters != null) { 7118 int size = matchingFilters.size(); 7119 for (int i = 0; i < size; i ++) { 7120 CrossProfileIntentFilter filter = matchingFilters.get(i); 7121 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7122 // Checking if there are activities in the target user that can handle the 7123 // intent. 7124 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7125 resolvedType, flags, sourceUserId); 7126 if (resolveInfo != null) { 7127 return resolveInfo; 7128 } 7129 } 7130 } 7131 } 7132 return null; 7133 } 7134 7135 // Return matching ResolveInfo in target user if any. 7136 private ResolveInfo queryCrossProfileIntents( 7137 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7138 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7139 if (matchingFilters != null) { 7140 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7141 // match the same intent. For performance reasons, it is better not to 7142 // run queryIntent twice for the same userId 7143 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7144 int size = matchingFilters.size(); 7145 for (int i = 0; i < size; i++) { 7146 CrossProfileIntentFilter filter = matchingFilters.get(i); 7147 int targetUserId = filter.getTargetUserId(); 7148 boolean skipCurrentProfile = 7149 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7150 boolean skipCurrentProfileIfNoMatchFound = 7151 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7152 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7153 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7154 // Checking if there are activities in the target user that can handle the 7155 // intent. 7156 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7157 resolvedType, flags, sourceUserId); 7158 if (resolveInfo != null) return resolveInfo; 7159 alreadyTriedUserIds.put(targetUserId, true); 7160 } 7161 } 7162 } 7163 return null; 7164 } 7165 7166 /** 7167 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7168 * will forward the intent to the filter's target user. 7169 * Otherwise, returns null. 7170 */ 7171 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7172 String resolvedType, int flags, int sourceUserId) { 7173 int targetUserId = filter.getTargetUserId(); 7174 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7175 resolvedType, flags, targetUserId); 7176 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7177 // If all the matches in the target profile are suspended, return null. 7178 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7179 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7180 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7181 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7182 targetUserId); 7183 } 7184 } 7185 } 7186 return null; 7187 } 7188 7189 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7190 int sourceUserId, int targetUserId) { 7191 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7192 long ident = Binder.clearCallingIdentity(); 7193 boolean targetIsProfile; 7194 try { 7195 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7196 } finally { 7197 Binder.restoreCallingIdentity(ident); 7198 } 7199 String className; 7200 if (targetIsProfile) { 7201 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7202 } else { 7203 className = FORWARD_INTENT_TO_PARENT; 7204 } 7205 ComponentName forwardingActivityComponentName = new ComponentName( 7206 mAndroidApplication.packageName, className); 7207 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7208 sourceUserId); 7209 if (!targetIsProfile) { 7210 forwardingActivityInfo.showUserIcon = targetUserId; 7211 forwardingResolveInfo.noResourceId = true; 7212 } 7213 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7214 forwardingResolveInfo.priority = 0; 7215 forwardingResolveInfo.preferredOrder = 0; 7216 forwardingResolveInfo.match = 0; 7217 forwardingResolveInfo.isDefault = true; 7218 forwardingResolveInfo.filter = filter; 7219 forwardingResolveInfo.targetUserId = targetUserId; 7220 return forwardingResolveInfo; 7221 } 7222 7223 @Override 7224 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7225 Intent[] specifics, String[] specificTypes, Intent intent, 7226 String resolvedType, int flags, int userId) { 7227 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7228 specificTypes, intent, resolvedType, flags, userId)); 7229 } 7230 7231 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7232 Intent[] specifics, String[] specificTypes, Intent intent, 7233 String resolvedType, int flags, int userId) { 7234 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7235 final int callingUid = Binder.getCallingUid(); 7236 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7237 false /*includeInstantApps*/); 7238 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7239 false /*requireFullPermission*/, false /*checkShell*/, 7240 "query intent activity options"); 7241 final String resultsAction = intent.getAction(); 7242 7243 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7244 | PackageManager.GET_RESOLVED_FILTER, userId); 7245 7246 if (DEBUG_INTENT_MATCHING) { 7247 Log.v(TAG, "Query " + intent + ": " + results); 7248 } 7249 7250 int specificsPos = 0; 7251 int N; 7252 7253 // todo: note that the algorithm used here is O(N^2). This 7254 // isn't a problem in our current environment, but if we start running 7255 // into situations where we have more than 5 or 10 matches then this 7256 // should probably be changed to something smarter... 7257 7258 // First we go through and resolve each of the specific items 7259 // that were supplied, taking care of removing any corresponding 7260 // duplicate items in the generic resolve list. 7261 if (specifics != null) { 7262 for (int i=0; i<specifics.length; i++) { 7263 final Intent sintent = specifics[i]; 7264 if (sintent == null) { 7265 continue; 7266 } 7267 7268 if (DEBUG_INTENT_MATCHING) { 7269 Log.v(TAG, "Specific #" + i + ": " + sintent); 7270 } 7271 7272 String action = sintent.getAction(); 7273 if (resultsAction != null && resultsAction.equals(action)) { 7274 // If this action was explicitly requested, then don't 7275 // remove things that have it. 7276 action = null; 7277 } 7278 7279 ResolveInfo ri = null; 7280 ActivityInfo ai = null; 7281 7282 ComponentName comp = sintent.getComponent(); 7283 if (comp == null) { 7284 ri = resolveIntent( 7285 sintent, 7286 specificTypes != null ? specificTypes[i] : null, 7287 flags, userId); 7288 if (ri == null) { 7289 continue; 7290 } 7291 if (ri == mResolveInfo) { 7292 // ACK! Must do something better with this. 7293 } 7294 ai = ri.activityInfo; 7295 comp = new ComponentName(ai.applicationInfo.packageName, 7296 ai.name); 7297 } else { 7298 ai = getActivityInfo(comp, flags, userId); 7299 if (ai == null) { 7300 continue; 7301 } 7302 } 7303 7304 // Look for any generic query activities that are duplicates 7305 // of this specific one, and remove them from the results. 7306 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7307 N = results.size(); 7308 int j; 7309 for (j=specificsPos; j<N; j++) { 7310 ResolveInfo sri = results.get(j); 7311 if ((sri.activityInfo.name.equals(comp.getClassName()) 7312 && sri.activityInfo.applicationInfo.packageName.equals( 7313 comp.getPackageName())) 7314 || (action != null && sri.filter.matchAction(action))) { 7315 results.remove(j); 7316 if (DEBUG_INTENT_MATCHING) Log.v( 7317 TAG, "Removing duplicate item from " + j 7318 + " due to specific " + specificsPos); 7319 if (ri == null) { 7320 ri = sri; 7321 } 7322 j--; 7323 N--; 7324 } 7325 } 7326 7327 // Add this specific item to its proper place. 7328 if (ri == null) { 7329 ri = new ResolveInfo(); 7330 ri.activityInfo = ai; 7331 } 7332 results.add(specificsPos, ri); 7333 ri.specificIndex = i; 7334 specificsPos++; 7335 } 7336 } 7337 7338 // Now we go through the remaining generic results and remove any 7339 // duplicate actions that are found here. 7340 N = results.size(); 7341 for (int i=specificsPos; i<N-1; i++) { 7342 final ResolveInfo rii = results.get(i); 7343 if (rii.filter == null) { 7344 continue; 7345 } 7346 7347 // Iterate over all of the actions of this result's intent 7348 // filter... typically this should be just one. 7349 final Iterator<String> it = rii.filter.actionsIterator(); 7350 if (it == null) { 7351 continue; 7352 } 7353 while (it.hasNext()) { 7354 final String action = it.next(); 7355 if (resultsAction != null && resultsAction.equals(action)) { 7356 // If this action was explicitly requested, then don't 7357 // remove things that have it. 7358 continue; 7359 } 7360 for (int j=i+1; j<N; j++) { 7361 final ResolveInfo rij = results.get(j); 7362 if (rij.filter != null && rij.filter.hasAction(action)) { 7363 results.remove(j); 7364 if (DEBUG_INTENT_MATCHING) Log.v( 7365 TAG, "Removing duplicate item from " + j 7366 + " due to action " + action + " at " + i); 7367 j--; 7368 N--; 7369 } 7370 } 7371 } 7372 7373 // If the caller didn't request filter information, drop it now 7374 // so we don't have to marshall/unmarshall it. 7375 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7376 rii.filter = null; 7377 } 7378 } 7379 7380 // Filter out the caller activity if so requested. 7381 if (caller != null) { 7382 N = results.size(); 7383 for (int i=0; i<N; i++) { 7384 ActivityInfo ainfo = results.get(i).activityInfo; 7385 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7386 && caller.getClassName().equals(ainfo.name)) { 7387 results.remove(i); 7388 break; 7389 } 7390 } 7391 } 7392 7393 // If the caller didn't request filter information, 7394 // drop them now so we don't have to 7395 // marshall/unmarshall it. 7396 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7397 N = results.size(); 7398 for (int i=0; i<N; i++) { 7399 results.get(i).filter = null; 7400 } 7401 } 7402 7403 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7404 return results; 7405 } 7406 7407 @Override 7408 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7409 String resolvedType, int flags, int userId) { 7410 return new ParceledListSlice<>( 7411 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7412 false /*allowDynamicSplits*/)); 7413 } 7414 7415 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7416 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7417 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7418 final int callingUid = Binder.getCallingUid(); 7419 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7420 false /*requireFullPermission*/, false /*checkShell*/, 7421 "query intent receivers"); 7422 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7423 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7424 false /*includeInstantApps*/); 7425 ComponentName comp = intent.getComponent(); 7426 if (comp == null) { 7427 if (intent.getSelector() != null) { 7428 intent = intent.getSelector(); 7429 comp = intent.getComponent(); 7430 } 7431 } 7432 if (comp != null) { 7433 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7434 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7435 if (ai != null) { 7436 // When specifying an explicit component, we prevent the activity from being 7437 // used when either 1) the calling package is normal and the activity is within 7438 // an instant application or 2) the calling package is ephemeral and the 7439 // activity is not visible to instant applications. 7440 final boolean matchInstantApp = 7441 (flags & PackageManager.MATCH_INSTANT) != 0; 7442 final boolean matchVisibleToInstantAppOnly = 7443 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7444 final boolean matchExplicitlyVisibleOnly = 7445 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7446 final boolean isCallerInstantApp = 7447 instantAppPkgName != null; 7448 final boolean isTargetSameInstantApp = 7449 comp.getPackageName().equals(instantAppPkgName); 7450 final boolean isTargetInstantApp = 7451 (ai.applicationInfo.privateFlags 7452 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7453 final boolean isTargetVisibleToInstantApp = 7454 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7455 final boolean isTargetExplicitlyVisibleToInstantApp = 7456 isTargetVisibleToInstantApp 7457 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7458 final boolean isTargetHiddenFromInstantApp = 7459 !isTargetVisibleToInstantApp 7460 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7461 final boolean blockResolution = 7462 !isTargetSameInstantApp 7463 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7464 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7465 && isTargetHiddenFromInstantApp)); 7466 if (!blockResolution) { 7467 ResolveInfo ri = new ResolveInfo(); 7468 ri.activityInfo = ai; 7469 list.add(ri); 7470 } 7471 } 7472 return applyPostResolutionFilter( 7473 list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7474 } 7475 7476 // reader 7477 synchronized (mPackages) { 7478 String pkgName = intent.getPackage(); 7479 if (pkgName == null) { 7480 final List<ResolveInfo> result = 7481 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7482 return applyPostResolutionFilter( 7483 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7484 } 7485 final PackageParser.Package pkg = mPackages.get(pkgName); 7486 if (pkg != null) { 7487 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7488 intent, resolvedType, flags, pkg.receivers, userId); 7489 return applyPostResolutionFilter( 7490 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7491 } 7492 return Collections.emptyList(); 7493 } 7494 } 7495 7496 @Override 7497 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7498 final int callingUid = Binder.getCallingUid(); 7499 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7500 } 7501 7502 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7503 int userId, int callingUid) { 7504 if (!sUserManager.exists(userId)) return null; 7505 flags = updateFlagsForResolve( 7506 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7507 List<ResolveInfo> query = queryIntentServicesInternal( 7508 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7509 if (query != null) { 7510 if (query.size() >= 1) { 7511 // If there is more than one service with the same priority, 7512 // just arbitrarily pick the first one. 7513 return query.get(0); 7514 } 7515 } 7516 return null; 7517 } 7518 7519 @Override 7520 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7521 String resolvedType, int flags, int userId) { 7522 final int callingUid = Binder.getCallingUid(); 7523 return new ParceledListSlice<>(queryIntentServicesInternal( 7524 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7525 } 7526 7527 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7528 String resolvedType, int flags, int userId, int callingUid, 7529 boolean includeInstantApps) { 7530 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7531 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7532 false /*requireFullPermission*/, false /*checkShell*/, 7533 "query intent receivers"); 7534 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7535 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7536 ComponentName comp = intent.getComponent(); 7537 if (comp == null) { 7538 if (intent.getSelector() != null) { 7539 intent = intent.getSelector(); 7540 comp = intent.getComponent(); 7541 } 7542 } 7543 if (comp != null) { 7544 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7545 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7546 if (si != null) { 7547 // When specifying an explicit component, we prevent the service from being 7548 // used when either 1) the service is in an instant application and the 7549 // caller is not the same instant application or 2) the calling package is 7550 // ephemeral and the activity is not visible to ephemeral applications. 7551 final boolean matchInstantApp = 7552 (flags & PackageManager.MATCH_INSTANT) != 0; 7553 final boolean matchVisibleToInstantAppOnly = 7554 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7555 final boolean isCallerInstantApp = 7556 instantAppPkgName != null; 7557 final boolean isTargetSameInstantApp = 7558 comp.getPackageName().equals(instantAppPkgName); 7559 final boolean isTargetInstantApp = 7560 (si.applicationInfo.privateFlags 7561 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7562 final boolean isTargetHiddenFromInstantApp = 7563 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7564 final boolean blockResolution = 7565 !isTargetSameInstantApp 7566 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7567 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7568 && isTargetHiddenFromInstantApp)); 7569 if (!blockResolution) { 7570 final ResolveInfo ri = new ResolveInfo(); 7571 ri.serviceInfo = si; 7572 list.add(ri); 7573 } 7574 } 7575 return list; 7576 } 7577 7578 // reader 7579 synchronized (mPackages) { 7580 String pkgName = intent.getPackage(); 7581 if (pkgName == null) { 7582 return applyPostServiceResolutionFilter( 7583 mServices.queryIntent(intent, resolvedType, flags, userId), 7584 instantAppPkgName); 7585 } 7586 final PackageParser.Package pkg = mPackages.get(pkgName); 7587 if (pkg != null) { 7588 return applyPostServiceResolutionFilter( 7589 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7590 userId), 7591 instantAppPkgName); 7592 } 7593 return Collections.emptyList(); 7594 } 7595 } 7596 7597 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7598 String instantAppPkgName) { 7599 if (instantAppPkgName == null) { 7600 return resolveInfos; 7601 } 7602 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7603 final ResolveInfo info = resolveInfos.get(i); 7604 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7605 // allow services that are defined in the provided package 7606 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7607 if (info.serviceInfo.splitName != null 7608 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7609 info.serviceInfo.splitName)) { 7610 // requested service is defined in a split that hasn't been installed yet. 7611 // add the installer to the resolve list 7612 if (DEBUG_INSTANT) { 7613 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7614 } 7615 final ResolveInfo installerInfo = new ResolveInfo( 7616 mInstantAppInstallerInfo); 7617 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7618 null /* installFailureActivity */, 7619 info.serviceInfo.packageName, 7620 info.serviceInfo.applicationInfo.versionCode, 7621 info.serviceInfo.splitName); 7622 // add a non-generic filter 7623 installerInfo.filter = new IntentFilter(); 7624 // load resources from the correct package 7625 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7626 resolveInfos.set(i, installerInfo); 7627 } 7628 continue; 7629 } 7630 // allow services that have been explicitly exposed to ephemeral apps 7631 if (!isEphemeralApp 7632 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7633 continue; 7634 } 7635 resolveInfos.remove(i); 7636 } 7637 return resolveInfos; 7638 } 7639 7640 @Override 7641 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7642 String resolvedType, int flags, int userId) { 7643 return new ParceledListSlice<>( 7644 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7645 } 7646 7647 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7648 Intent intent, String resolvedType, int flags, int userId) { 7649 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7650 final int callingUid = Binder.getCallingUid(); 7651 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7652 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7653 false /*includeInstantApps*/); 7654 ComponentName comp = intent.getComponent(); 7655 if (comp == null) { 7656 if (intent.getSelector() != null) { 7657 intent = intent.getSelector(); 7658 comp = intent.getComponent(); 7659 } 7660 } 7661 if (comp != null) { 7662 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7663 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7664 if (pi != null) { 7665 // When specifying an explicit component, we prevent the provider from being 7666 // used when either 1) the provider is in an instant application and the 7667 // caller is not the same instant application or 2) the calling package is an 7668 // instant application and the provider is not visible to instant applications. 7669 final boolean matchInstantApp = 7670 (flags & PackageManager.MATCH_INSTANT) != 0; 7671 final boolean matchVisibleToInstantAppOnly = 7672 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7673 final boolean isCallerInstantApp = 7674 instantAppPkgName != null; 7675 final boolean isTargetSameInstantApp = 7676 comp.getPackageName().equals(instantAppPkgName); 7677 final boolean isTargetInstantApp = 7678 (pi.applicationInfo.privateFlags 7679 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7680 final boolean isTargetHiddenFromInstantApp = 7681 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7682 final boolean blockResolution = 7683 !isTargetSameInstantApp 7684 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7685 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7686 && isTargetHiddenFromInstantApp)); 7687 if (!blockResolution) { 7688 final ResolveInfo ri = new ResolveInfo(); 7689 ri.providerInfo = pi; 7690 list.add(ri); 7691 } 7692 } 7693 return list; 7694 } 7695 7696 // reader 7697 synchronized (mPackages) { 7698 String pkgName = intent.getPackage(); 7699 if (pkgName == null) { 7700 return applyPostContentProviderResolutionFilter( 7701 mProviders.queryIntent(intent, resolvedType, flags, userId), 7702 instantAppPkgName); 7703 } 7704 final PackageParser.Package pkg = mPackages.get(pkgName); 7705 if (pkg != null) { 7706 return applyPostContentProviderResolutionFilter( 7707 mProviders.queryIntentForPackage( 7708 intent, resolvedType, flags, pkg.providers, userId), 7709 instantAppPkgName); 7710 } 7711 return Collections.emptyList(); 7712 } 7713 } 7714 7715 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7716 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7717 if (instantAppPkgName == null) { 7718 return resolveInfos; 7719 } 7720 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7721 final ResolveInfo info = resolveInfos.get(i); 7722 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7723 // allow providers that are defined in the provided package 7724 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7725 if (info.providerInfo.splitName != null 7726 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7727 info.providerInfo.splitName)) { 7728 // requested provider is defined in a split that hasn't been installed yet. 7729 // add the installer to the resolve list 7730 if (DEBUG_INSTANT) { 7731 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7732 } 7733 final ResolveInfo installerInfo = new ResolveInfo( 7734 mInstantAppInstallerInfo); 7735 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7736 null /*failureActivity*/, 7737 info.providerInfo.packageName, 7738 info.providerInfo.applicationInfo.versionCode, 7739 info.providerInfo.splitName); 7740 // add a non-generic filter 7741 installerInfo.filter = new IntentFilter(); 7742 // load resources from the correct package 7743 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7744 resolveInfos.set(i, installerInfo); 7745 } 7746 continue; 7747 } 7748 // allow providers that have been explicitly exposed to instant applications 7749 if (!isEphemeralApp 7750 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7751 continue; 7752 } 7753 resolveInfos.remove(i); 7754 } 7755 return resolveInfos; 7756 } 7757 7758 @Override 7759 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7760 final int callingUid = Binder.getCallingUid(); 7761 if (getInstantAppPackageName(callingUid) != null) { 7762 return ParceledListSlice.emptyList(); 7763 } 7764 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7765 flags = updateFlagsForPackage(flags, userId, null); 7766 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7767 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7768 true /* requireFullPermission */, false /* checkShell */, 7769 "get installed packages"); 7770 7771 // writer 7772 synchronized (mPackages) { 7773 ArrayList<PackageInfo> list; 7774 if (listUninstalled) { 7775 list = new ArrayList<>(mSettings.mPackages.size()); 7776 for (PackageSetting ps : mSettings.mPackages.values()) { 7777 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7778 continue; 7779 } 7780 if (filterAppAccessLPr(ps, callingUid, userId)) { 7781 continue; 7782 } 7783 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7784 if (pi != null) { 7785 list.add(pi); 7786 } 7787 } 7788 } else { 7789 list = new ArrayList<>(mPackages.size()); 7790 for (PackageParser.Package p : mPackages.values()) { 7791 final PackageSetting ps = (PackageSetting) p.mExtras; 7792 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7793 continue; 7794 } 7795 if (filterAppAccessLPr(ps, callingUid, userId)) { 7796 continue; 7797 } 7798 final PackageInfo pi = generatePackageInfo((PackageSetting) 7799 p.mExtras, flags, userId); 7800 if (pi != null) { 7801 list.add(pi); 7802 } 7803 } 7804 } 7805 7806 return new ParceledListSlice<>(list); 7807 } 7808 } 7809 7810 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7811 String[] permissions, boolean[] tmp, int flags, int userId) { 7812 int numMatch = 0; 7813 final PermissionsState permissionsState = ps.getPermissionsState(); 7814 for (int i=0; i<permissions.length; i++) { 7815 final String permission = permissions[i]; 7816 if (permissionsState.hasPermission(permission, userId)) { 7817 tmp[i] = true; 7818 numMatch++; 7819 } else { 7820 tmp[i] = false; 7821 } 7822 } 7823 if (numMatch == 0) { 7824 return; 7825 } 7826 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7827 7828 // The above might return null in cases of uninstalled apps or install-state 7829 // skew across users/profiles. 7830 if (pi != null) { 7831 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7832 if (numMatch == permissions.length) { 7833 pi.requestedPermissions = permissions; 7834 } else { 7835 pi.requestedPermissions = new String[numMatch]; 7836 numMatch = 0; 7837 for (int i=0; i<permissions.length; i++) { 7838 if (tmp[i]) { 7839 pi.requestedPermissions[numMatch] = permissions[i]; 7840 numMatch++; 7841 } 7842 } 7843 } 7844 } 7845 list.add(pi); 7846 } 7847 } 7848 7849 @Override 7850 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7851 String[] permissions, int flags, int userId) { 7852 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7853 flags = updateFlagsForPackage(flags, userId, permissions); 7854 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7855 true /* requireFullPermission */, false /* checkShell */, 7856 "get packages holding permissions"); 7857 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7858 7859 // writer 7860 synchronized (mPackages) { 7861 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7862 boolean[] tmpBools = new boolean[permissions.length]; 7863 if (listUninstalled) { 7864 for (PackageSetting ps : mSettings.mPackages.values()) { 7865 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7866 userId); 7867 } 7868 } else { 7869 for (PackageParser.Package pkg : mPackages.values()) { 7870 PackageSetting ps = (PackageSetting)pkg.mExtras; 7871 if (ps != null) { 7872 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7873 userId); 7874 } 7875 } 7876 } 7877 7878 return new ParceledListSlice<PackageInfo>(list); 7879 } 7880 } 7881 7882 @Override 7883 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7884 final int callingUid = Binder.getCallingUid(); 7885 if (getInstantAppPackageName(callingUid) != null) { 7886 return ParceledListSlice.emptyList(); 7887 } 7888 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7889 flags = updateFlagsForApplication(flags, userId, null); 7890 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7891 7892 // writer 7893 synchronized (mPackages) { 7894 ArrayList<ApplicationInfo> list; 7895 if (listUninstalled) { 7896 list = new ArrayList<>(mSettings.mPackages.size()); 7897 for (PackageSetting ps : mSettings.mPackages.values()) { 7898 ApplicationInfo ai; 7899 int effectiveFlags = flags; 7900 if (ps.isSystem()) { 7901 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7902 } 7903 if (ps.pkg != null) { 7904 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7905 continue; 7906 } 7907 if (filterAppAccessLPr(ps, callingUid, userId)) { 7908 continue; 7909 } 7910 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7911 ps.readUserState(userId), userId); 7912 if (ai != null) { 7913 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7914 } 7915 } else { 7916 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7917 // and already converts to externally visible package name 7918 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7919 callingUid, effectiveFlags, userId); 7920 } 7921 if (ai != null) { 7922 list.add(ai); 7923 } 7924 } 7925 } else { 7926 list = new ArrayList<>(mPackages.size()); 7927 for (PackageParser.Package p : mPackages.values()) { 7928 if (p.mExtras != null) { 7929 PackageSetting ps = (PackageSetting) p.mExtras; 7930 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7931 continue; 7932 } 7933 if (filterAppAccessLPr(ps, callingUid, userId)) { 7934 continue; 7935 } 7936 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7937 ps.readUserState(userId), userId); 7938 if (ai != null) { 7939 ai.packageName = resolveExternalPackageNameLPr(p); 7940 list.add(ai); 7941 } 7942 } 7943 } 7944 } 7945 7946 return new ParceledListSlice<>(list); 7947 } 7948 } 7949 7950 @Override 7951 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7952 if (HIDE_EPHEMERAL_APIS) { 7953 return null; 7954 } 7955 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7956 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7957 "getEphemeralApplications"); 7958 } 7959 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7960 true /* requireFullPermission */, false /* checkShell */, 7961 "getEphemeralApplications"); 7962 synchronized (mPackages) { 7963 List<InstantAppInfo> instantApps = mInstantAppRegistry 7964 .getInstantAppsLPr(userId); 7965 if (instantApps != null) { 7966 return new ParceledListSlice<>(instantApps); 7967 } 7968 } 7969 return null; 7970 } 7971 7972 @Override 7973 public boolean isInstantApp(String packageName, int userId) { 7974 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7975 true /* requireFullPermission */, false /* checkShell */, 7976 "isInstantApp"); 7977 if (HIDE_EPHEMERAL_APIS) { 7978 return false; 7979 } 7980 7981 synchronized (mPackages) { 7982 int callingUid = Binder.getCallingUid(); 7983 if (Process.isIsolated(callingUid)) { 7984 callingUid = mIsolatedOwners.get(callingUid); 7985 } 7986 final PackageSetting ps = mSettings.mPackages.get(packageName); 7987 PackageParser.Package pkg = mPackages.get(packageName); 7988 final boolean returnAllowed = 7989 ps != null 7990 && (isCallerSameApp(packageName, callingUid) 7991 || canViewInstantApps(callingUid, userId) 7992 || mInstantAppRegistry.isInstantAccessGranted( 7993 userId, UserHandle.getAppId(callingUid), ps.appId)); 7994 if (returnAllowed) { 7995 return ps.getInstantApp(userId); 7996 } 7997 } 7998 return false; 7999 } 8000 8001 @Override 8002 public byte[] getInstantAppCookie(String packageName, int userId) { 8003 if (HIDE_EPHEMERAL_APIS) { 8004 return null; 8005 } 8006 8007 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8008 true /* requireFullPermission */, false /* checkShell */, 8009 "getInstantAppCookie"); 8010 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8011 return null; 8012 } 8013 synchronized (mPackages) { 8014 return mInstantAppRegistry.getInstantAppCookieLPw( 8015 packageName, userId); 8016 } 8017 } 8018 8019 @Override 8020 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8021 if (HIDE_EPHEMERAL_APIS) { 8022 return true; 8023 } 8024 8025 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8026 true /* requireFullPermission */, true /* checkShell */, 8027 "setInstantAppCookie"); 8028 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8029 return false; 8030 } 8031 synchronized (mPackages) { 8032 return mInstantAppRegistry.setInstantAppCookieLPw( 8033 packageName, cookie, userId); 8034 } 8035 } 8036 8037 @Override 8038 public Bitmap getInstantAppIcon(String packageName, int userId) { 8039 if (HIDE_EPHEMERAL_APIS) { 8040 return null; 8041 } 8042 8043 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8044 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8045 "getInstantAppIcon"); 8046 } 8047 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8048 true /* requireFullPermission */, false /* checkShell */, 8049 "getInstantAppIcon"); 8050 8051 synchronized (mPackages) { 8052 return mInstantAppRegistry.getInstantAppIconLPw( 8053 packageName, userId); 8054 } 8055 } 8056 8057 private boolean isCallerSameApp(String packageName, int uid) { 8058 PackageParser.Package pkg = mPackages.get(packageName); 8059 return pkg != null 8060 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8061 } 8062 8063 @Override 8064 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8065 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8066 return ParceledListSlice.emptyList(); 8067 } 8068 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8069 } 8070 8071 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8072 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8073 8074 // reader 8075 synchronized (mPackages) { 8076 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8077 final int userId = UserHandle.getCallingUserId(); 8078 while (i.hasNext()) { 8079 final PackageParser.Package p = i.next(); 8080 if (p.applicationInfo == null) continue; 8081 8082 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8083 && !p.applicationInfo.isDirectBootAware(); 8084 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8085 && p.applicationInfo.isDirectBootAware(); 8086 8087 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8088 && (!mSafeMode || isSystemApp(p)) 8089 && (matchesUnaware || matchesAware)) { 8090 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8091 if (ps != null) { 8092 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8093 ps.readUserState(userId), userId); 8094 if (ai != null) { 8095 finalList.add(ai); 8096 } 8097 } 8098 } 8099 } 8100 } 8101 8102 return finalList; 8103 } 8104 8105 @Override 8106 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8107 return resolveContentProviderInternal(name, flags, userId); 8108 } 8109 8110 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8111 if (!sUserManager.exists(userId)) return null; 8112 flags = updateFlagsForComponent(flags, userId, name); 8113 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8114 // reader 8115 synchronized (mPackages) { 8116 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8117 PackageSetting ps = provider != null 8118 ? mSettings.mPackages.get(provider.owner.packageName) 8119 : null; 8120 if (ps != null) { 8121 final boolean isInstantApp = ps.getInstantApp(userId); 8122 // normal application; filter out instant application provider 8123 if (instantAppPkgName == null && isInstantApp) { 8124 return null; 8125 } 8126 // instant application; filter out other instant applications 8127 if (instantAppPkgName != null 8128 && isInstantApp 8129 && !provider.owner.packageName.equals(instantAppPkgName)) { 8130 return null; 8131 } 8132 // instant application; filter out non-exposed provider 8133 if (instantAppPkgName != null 8134 && !isInstantApp 8135 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8136 return null; 8137 } 8138 // provider not enabled 8139 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8140 return null; 8141 } 8142 return PackageParser.generateProviderInfo( 8143 provider, flags, ps.readUserState(userId), userId); 8144 } 8145 return null; 8146 } 8147 } 8148 8149 /** 8150 * @deprecated 8151 */ 8152 @Deprecated 8153 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8154 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8155 return; 8156 } 8157 // reader 8158 synchronized (mPackages) { 8159 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8160 .entrySet().iterator(); 8161 final int userId = UserHandle.getCallingUserId(); 8162 while (i.hasNext()) { 8163 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8164 PackageParser.Provider p = entry.getValue(); 8165 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8166 8167 if (ps != null && p.syncable 8168 && (!mSafeMode || (p.info.applicationInfo.flags 8169 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8170 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8171 ps.readUserState(userId), userId); 8172 if (info != null) { 8173 outNames.add(entry.getKey()); 8174 outInfo.add(info); 8175 } 8176 } 8177 } 8178 } 8179 } 8180 8181 @Override 8182 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8183 int uid, int flags, String metaDataKey) { 8184 final int callingUid = Binder.getCallingUid(); 8185 final int userId = processName != null ? UserHandle.getUserId(uid) 8186 : UserHandle.getCallingUserId(); 8187 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8188 flags = updateFlagsForComponent(flags, userId, processName); 8189 ArrayList<ProviderInfo> finalList = null; 8190 // reader 8191 synchronized (mPackages) { 8192 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8193 while (i.hasNext()) { 8194 final PackageParser.Provider p = i.next(); 8195 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8196 if (ps != null && p.info.authority != null 8197 && (processName == null 8198 || (p.info.processName.equals(processName) 8199 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8200 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8201 8202 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8203 // parameter. 8204 if (metaDataKey != null 8205 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8206 continue; 8207 } 8208 final ComponentName component = 8209 new ComponentName(p.info.packageName, p.info.name); 8210 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8211 continue; 8212 } 8213 if (finalList == null) { 8214 finalList = new ArrayList<ProviderInfo>(3); 8215 } 8216 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8217 ps.readUserState(userId), userId); 8218 if (info != null) { 8219 finalList.add(info); 8220 } 8221 } 8222 } 8223 } 8224 8225 if (finalList != null) { 8226 Collections.sort(finalList, mProviderInitOrderSorter); 8227 return new ParceledListSlice<ProviderInfo>(finalList); 8228 } 8229 8230 return ParceledListSlice.emptyList(); 8231 } 8232 8233 @Override 8234 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8235 // reader 8236 synchronized (mPackages) { 8237 final int callingUid = Binder.getCallingUid(); 8238 final int callingUserId = UserHandle.getUserId(callingUid); 8239 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8240 if (ps == null) return null; 8241 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8242 return null; 8243 } 8244 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8245 return PackageParser.generateInstrumentationInfo(i, flags); 8246 } 8247 } 8248 8249 @Override 8250 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8251 String targetPackage, int flags) { 8252 final int callingUid = Binder.getCallingUid(); 8253 final int callingUserId = UserHandle.getUserId(callingUid); 8254 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8255 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8256 return ParceledListSlice.emptyList(); 8257 } 8258 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8259 } 8260 8261 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8262 int flags) { 8263 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8264 8265 // reader 8266 synchronized (mPackages) { 8267 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8268 while (i.hasNext()) { 8269 final PackageParser.Instrumentation p = i.next(); 8270 if (targetPackage == null 8271 || targetPackage.equals(p.info.targetPackage)) { 8272 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8273 flags); 8274 if (ii != null) { 8275 finalList.add(ii); 8276 } 8277 } 8278 } 8279 } 8280 8281 return finalList; 8282 } 8283 8284 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8285 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8286 try { 8287 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8288 } finally { 8289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8290 } 8291 } 8292 8293 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8294 final File[] files = scanDir.listFiles(); 8295 if (ArrayUtils.isEmpty(files)) { 8296 Log.d(TAG, "No files in app dir " + scanDir); 8297 return; 8298 } 8299 8300 if (DEBUG_PACKAGE_SCANNING) { 8301 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8302 + " flags=0x" + Integer.toHexString(parseFlags)); 8303 } 8304 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8305 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8306 mParallelPackageParserCallback)) { 8307 // Submit files for parsing in parallel 8308 int fileCount = 0; 8309 for (File file : files) { 8310 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8311 && !PackageInstallerService.isStageName(file.getName()); 8312 if (!isPackage) { 8313 // Ignore entries which are not packages 8314 continue; 8315 } 8316 parallelPackageParser.submit(file, parseFlags); 8317 fileCount++; 8318 } 8319 8320 // Process results one by one 8321 for (; fileCount > 0; fileCount--) { 8322 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8323 Throwable throwable = parseResult.throwable; 8324 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8325 8326 if (throwable == null) { 8327 // TODO(toddke): move lower in the scan chain 8328 // Static shared libraries have synthetic package names 8329 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8330 renameStaticSharedLibraryPackage(parseResult.pkg); 8331 } 8332 try { 8333 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8334 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8335 currentTime, null); 8336 } 8337 } catch (PackageManagerException e) { 8338 errorCode = e.error; 8339 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8340 } 8341 } else if (throwable instanceof PackageParser.PackageParserException) { 8342 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8343 throwable; 8344 errorCode = e.error; 8345 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8346 } else { 8347 throw new IllegalStateException("Unexpected exception occurred while parsing " 8348 + parseResult.scanFile, throwable); 8349 } 8350 8351 // Delete invalid userdata apps 8352 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8353 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8354 logCriticalInfo(Log.WARN, 8355 "Deleting invalid package at " + parseResult.scanFile); 8356 removeCodePathLI(parseResult.scanFile); 8357 } 8358 } 8359 } 8360 } 8361 8362 public static void reportSettingsProblem(int priority, String msg) { 8363 logCriticalInfo(priority, msg); 8364 } 8365 8366 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8367 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 8368 // When upgrading from pre-N MR1, verify the package time stamp using the package 8369 // directory and not the APK file. 8370 final long lastModifiedTime = mIsPreNMR1Upgrade 8371 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8372 if (ps != null && !forceCollect 8373 && ps.codePathString.equals(pkg.codePath) 8374 && ps.timeStamp == lastModifiedTime 8375 && !isCompatSignatureUpdateNeeded(pkg) 8376 && !isRecoverSignatureUpdateNeeded(pkg)) { 8377 if (ps.signatures.mSigningDetails.signatures != null 8378 && ps.signatures.mSigningDetails.signatures.length != 0 8379 && ps.signatures.mSigningDetails.signatureSchemeVersion 8380 != SignatureSchemeVersion.UNKNOWN) { 8381 // Optimization: reuse the existing cached signing data 8382 // if the package appears to be unchanged. 8383 pkg.mSigningDetails = 8384 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8385 return; 8386 } 8387 8388 Slog.w(TAG, "PackageSetting for " + ps.name 8389 + " is missing signatures. Collecting certs again to recover them."); 8390 } else { 8391 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8392 (forceCollect ? " (forced)" : "")); 8393 } 8394 8395 try { 8396 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8397 PackageParser.collectCertificates(pkg, skipVerify); 8398 } catch (PackageParserException e) { 8399 throw PackageManagerException.from(e); 8400 } finally { 8401 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8402 } 8403 } 8404 8405 /** 8406 * Traces a package scan. 8407 * @see #scanPackageLI(File, int, int, long, UserHandle) 8408 */ 8409 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8410 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8412 try { 8413 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8414 } finally { 8415 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8416 } 8417 } 8418 8419 /** 8420 * Scans a package and returns the newly parsed package. 8421 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8422 */ 8423 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8424 long currentTime, UserHandle user) throws PackageManagerException { 8425 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8426 PackageParser pp = new PackageParser(); 8427 pp.setSeparateProcesses(mSeparateProcesses); 8428 pp.setOnlyCoreApps(mOnlyCore); 8429 pp.setDisplayMetrics(mMetrics); 8430 pp.setCallback(mPackageParserCallback); 8431 8432 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8433 final PackageParser.Package pkg; 8434 try { 8435 pkg = pp.parsePackage(scanFile, parseFlags); 8436 } catch (PackageParserException e) { 8437 throw PackageManagerException.from(e); 8438 } finally { 8439 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8440 } 8441 8442 // Static shared libraries have synthetic package names 8443 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8444 renameStaticSharedLibraryPackage(pkg); 8445 } 8446 8447 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8448 } 8449 8450 /** 8451 * Scans a package and returns the newly parsed package. 8452 * @throws PackageManagerException on a parse error. 8453 */ 8454 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8455 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8456 @Nullable UserHandle user) 8457 throws PackageManagerException { 8458 // If the package has children and this is the first dive in the function 8459 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8460 // packages (parent and children) would be successfully scanned before the 8461 // actual scan since scanning mutates internal state and we want to atomically 8462 // install the package and its children. 8463 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8464 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8465 scanFlags |= SCAN_CHECK_ONLY; 8466 } 8467 } else { 8468 scanFlags &= ~SCAN_CHECK_ONLY; 8469 } 8470 8471 // Scan the parent 8472 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8473 scanFlags, currentTime, user); 8474 8475 // Scan the children 8476 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8477 for (int i = 0; i < childCount; i++) { 8478 PackageParser.Package childPackage = pkg.childPackages.get(i); 8479 addForInitLI(childPackage, parseFlags, scanFlags, 8480 currentTime, user); 8481 } 8482 8483 8484 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8485 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8486 } 8487 8488 return scannedPkg; 8489 } 8490 8491 /** 8492 * Returns if full apk verification can be skipped for the whole package, including the splits. 8493 */ 8494 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8495 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8496 return false; 8497 } 8498 // TODO: Allow base and splits to be verified individually. 8499 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8500 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8501 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8502 return false; 8503 } 8504 } 8505 } 8506 return true; 8507 } 8508 8509 /** 8510 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8511 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8512 * match one in a trusted source, and should be done separately. 8513 */ 8514 private boolean canSkipFullApkVerification(String apkPath) { 8515 byte[] rootHashObserved = null; 8516 try { 8517 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8518 if (rootHashObserved == null) { 8519 return false; // APK does not contain Merkle tree root hash. 8520 } 8521 synchronized (mInstallLock) { 8522 // Returns whether the observed root hash matches what kernel has. 8523 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8524 return true; 8525 } 8526 } catch (InstallerException | IOException | DigestException | 8527 NoSuchAlgorithmException e) { 8528 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8529 } 8530 return false; 8531 } 8532 8533 /** 8534 * Adds a new package to the internal data structures during platform initialization. 8535 * <p>After adding, the package is known to the system and available for querying. 8536 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8537 * etc...], additional checks are performed. Basic verification [such as ensuring 8538 * matching signatures, checking version codes, etc...] occurs if the package is 8539 * identical to a previously known package. If the package fails a signature check, 8540 * the version installed on /data will be removed. If the version of the new package 8541 * is less than or equal than the version on /data, it will be ignored. 8542 * <p>Regardless of the package location, the results are applied to the internal 8543 * structures and the package is made available to the rest of the system. 8544 * <p>NOTE: The return value should be removed. It's the passed in package object. 8545 */ 8546 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8547 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8548 @Nullable UserHandle user) 8549 throws PackageManagerException { 8550 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8551 final String renamedPkgName; 8552 final PackageSetting disabledPkgSetting; 8553 final boolean isSystemPkgUpdated; 8554 final boolean pkgAlreadyExists; 8555 PackageSetting pkgSetting; 8556 8557 // NOTE: installPackageLI() has the same code to setup the package's 8558 // application info. This probably should be done lower in the call 8559 // stack [such as scanPackageOnly()]. However, we verify the application 8560 // info prior to that [in scanPackageNew()] and thus have to setup 8561 // the application info early. 8562 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8563 pkg.setApplicationInfoCodePath(pkg.codePath); 8564 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8565 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8566 pkg.setApplicationInfoResourcePath(pkg.codePath); 8567 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8568 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8569 8570 synchronized (mPackages) { 8571 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8572 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8573 if (realPkgName != null) { 8574 ensurePackageRenamed(pkg, renamedPkgName); 8575 } 8576 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8577 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8578 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8579 pkgAlreadyExists = pkgSetting != null; 8580 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8581 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8582 isSystemPkgUpdated = disabledPkgSetting != null; 8583 8584 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8585 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8586 } 8587 8588 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8589 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8590 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8591 : null; 8592 if (DEBUG_PACKAGE_SCANNING 8593 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8594 && sharedUserSetting != null) { 8595 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8596 + " (uid=" + sharedUserSetting.userId + "):" 8597 + " packages=" + sharedUserSetting.packages); 8598 } 8599 8600 if (scanSystemPartition) { 8601 // Potentially prune child packages. If the application on the /system 8602 // partition has been updated via OTA, but, is still disabled by a 8603 // version on /data, cycle through all of its children packages and 8604 // remove children that are no longer defined. 8605 if (isSystemPkgUpdated) { 8606 final int scannedChildCount = (pkg.childPackages != null) 8607 ? pkg.childPackages.size() : 0; 8608 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8609 ? disabledPkgSetting.childPackageNames.size() : 0; 8610 for (int i = 0; i < disabledChildCount; i++) { 8611 String disabledChildPackageName = 8612 disabledPkgSetting.childPackageNames.get(i); 8613 boolean disabledPackageAvailable = false; 8614 for (int j = 0; j < scannedChildCount; j++) { 8615 PackageParser.Package childPkg = pkg.childPackages.get(j); 8616 if (childPkg.packageName.equals(disabledChildPackageName)) { 8617 disabledPackageAvailable = true; 8618 break; 8619 } 8620 } 8621 if (!disabledPackageAvailable) { 8622 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8623 } 8624 } 8625 // we're updating the disabled package, so, scan it as the package setting 8626 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8627 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8628 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8629 (pkg == mPlatformPackage), user); 8630 scanPackageOnlyLI(request, mFactoryTest, -1L); 8631 } 8632 } 8633 } 8634 8635 final boolean newPkgChangedPaths = 8636 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8637 final boolean newPkgVersionGreater = 8638 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8639 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8640 && newPkgChangedPaths && newPkgVersionGreater; 8641 if (isSystemPkgBetter) { 8642 // The version of the application on /system is greater than the version on 8643 // /data. Switch back to the application on /system. 8644 // It's safe to assume the application on /system will correctly scan. If not, 8645 // there won't be a working copy of the application. 8646 synchronized (mPackages) { 8647 // just remove the loaded entries from package lists 8648 mPackages.remove(pkgSetting.name); 8649 } 8650 8651 logCriticalInfo(Log.WARN, 8652 "System package updated;" 8653 + " name: " + pkgSetting.name 8654 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8655 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8656 8657 final InstallArgs args = createInstallArgsForExisting( 8658 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8659 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8660 args.cleanUpResourcesLI(); 8661 synchronized (mPackages) { 8662 mSettings.enableSystemPackageLPw(pkgSetting.name); 8663 } 8664 } 8665 8666 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8667 // The version of the application on the /system partition is less than or 8668 // equal to the version on the /data partition. Throw an exception and use 8669 // the application already installed on the /data partition. 8670 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8671 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8672 + " better than this " + pkg.getLongVersionCode()); 8673 } 8674 8675 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8676 // force re-collecting certificate. 8677 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8678 disabledPkgSetting); 8679 // Full APK verification can be skipped during certificate collection, only if the file is 8680 // in verified partition, or can be verified on access (when apk verity is enabled). In both 8681 // cases, only data in Signing Block is verified instead of the whole file. 8682 final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) || 8683 (forceCollect && canSkipFullPackageVerification(pkg)); 8684 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 8685 8686 boolean shouldHideSystemApp = false; 8687 // A new application appeared on /system, but, we already have a copy of 8688 // the application installed on /data. 8689 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8690 && !pkgSetting.isSystem()) { 8691 8692 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 8693 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 8694 logCriticalInfo(Log.WARN, 8695 "System package signature mismatch;" 8696 + " name: " + pkgSetting.name); 8697 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8698 "scanPackageInternalLI")) { 8699 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8700 } 8701 pkgSetting = null; 8702 } else if (newPkgVersionGreater) { 8703 // The application on /system is newer than the application on /data. 8704 // Simply remove the application on /data [keeping application data] 8705 // and replace it with the version on /system. 8706 logCriticalInfo(Log.WARN, 8707 "System package enabled;" 8708 + " name: " + pkgSetting.name 8709 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8710 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8711 InstallArgs args = createInstallArgsForExisting( 8712 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8713 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8714 synchronized (mInstallLock) { 8715 args.cleanUpResourcesLI(); 8716 } 8717 } else { 8718 // The application on /system is older than the application on /data. Hide 8719 // the application on /system and the version on /data will be scanned later 8720 // and re-added like an update. 8721 shouldHideSystemApp = true; 8722 logCriticalInfo(Log.INFO, 8723 "System package disabled;" 8724 + " name: " + pkgSetting.name 8725 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8726 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8727 } 8728 } 8729 8730 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8731 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8732 8733 if (shouldHideSystemApp) { 8734 synchronized (mPackages) { 8735 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8736 } 8737 } 8738 return scannedPkg; 8739 } 8740 8741 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8742 // Derive the new package synthetic package name 8743 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8744 + pkg.staticSharedLibVersion); 8745 } 8746 8747 private static String fixProcessName(String defProcessName, 8748 String processName) { 8749 if (processName == null) { 8750 return defProcessName; 8751 } 8752 return processName; 8753 } 8754 8755 /** 8756 * Enforces that only the system UID or root's UID can call a method exposed 8757 * via Binder. 8758 * 8759 * @param message used as message if SecurityException is thrown 8760 * @throws SecurityException if the caller is not system or root 8761 */ 8762 private static final void enforceSystemOrRoot(String message) { 8763 final int uid = Binder.getCallingUid(); 8764 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8765 throw new SecurityException(message); 8766 } 8767 } 8768 8769 @Override 8770 public void performFstrimIfNeeded() { 8771 enforceSystemOrRoot("Only the system can request fstrim"); 8772 8773 // Before everything else, see whether we need to fstrim. 8774 try { 8775 IStorageManager sm = PackageHelper.getStorageManager(); 8776 if (sm != null) { 8777 boolean doTrim = false; 8778 final long interval = android.provider.Settings.Global.getLong( 8779 mContext.getContentResolver(), 8780 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8781 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8782 if (interval > 0) { 8783 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8784 if (timeSinceLast > interval) { 8785 doTrim = true; 8786 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8787 + "; running immediately"); 8788 } 8789 } 8790 if (doTrim) { 8791 final boolean dexOptDialogShown; 8792 synchronized (mPackages) { 8793 dexOptDialogShown = mDexOptDialogShown; 8794 } 8795 if (!isFirstBoot() && dexOptDialogShown) { 8796 try { 8797 ActivityManager.getService().showBootMessage( 8798 mContext.getResources().getString( 8799 R.string.android_upgrading_fstrim), true); 8800 } catch (RemoteException e) { 8801 } 8802 } 8803 sm.runMaintenance(); 8804 } 8805 } else { 8806 Slog.e(TAG, "storageManager service unavailable!"); 8807 } 8808 } catch (RemoteException e) { 8809 // Can't happen; StorageManagerService is local 8810 } 8811 } 8812 8813 @Override 8814 public void updatePackagesIfNeeded() { 8815 enforceSystemOrRoot("Only the system can request package update"); 8816 8817 // We need to re-extract after an OTA. 8818 boolean causeUpgrade = isUpgrade(); 8819 8820 // First boot or factory reset. 8821 // Note: we also handle devices that are upgrading to N right now as if it is their 8822 // first boot, as they do not have profile data. 8823 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8824 8825 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8826 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8827 8828 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8829 return; 8830 } 8831 8832 List<PackageParser.Package> pkgs; 8833 synchronized (mPackages) { 8834 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8835 } 8836 8837 final long startTime = System.nanoTime(); 8838 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8839 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 8840 false /* bootComplete */); 8841 8842 final int elapsedTimeSeconds = 8843 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8844 8845 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8846 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8847 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8848 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8849 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8850 } 8851 8852 /* 8853 * Return the prebuilt profile path given a package base code path. 8854 */ 8855 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8856 return pkg.baseCodePath + ".prof"; 8857 } 8858 8859 /** 8860 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8861 * containing statistics about the invocation. The array consists of three elements, 8862 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8863 * and {@code numberOfPackagesFailed}. 8864 */ 8865 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8866 final int compilationReason, boolean bootComplete) { 8867 8868 int numberOfPackagesVisited = 0; 8869 int numberOfPackagesOptimized = 0; 8870 int numberOfPackagesSkipped = 0; 8871 int numberOfPackagesFailed = 0; 8872 final int numberOfPackagesToDexopt = pkgs.size(); 8873 8874 for (PackageParser.Package pkg : pkgs) { 8875 numberOfPackagesVisited++; 8876 8877 boolean useProfileForDexopt = false; 8878 8879 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8880 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8881 // that are already compiled. 8882 File profileFile = new File(getPrebuildProfilePath(pkg)); 8883 // Copy profile if it exists. 8884 if (profileFile.exists()) { 8885 try { 8886 // We could also do this lazily before calling dexopt in 8887 // PackageDexOptimizer to prevent this happening on first boot. The issue 8888 // is that we don't have a good way to say "do this only once". 8889 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8890 pkg.applicationInfo.uid, pkg.packageName, 8891 ArtManager.getProfileName(null))) { 8892 Log.e(TAG, "Installer failed to copy system profile!"); 8893 } else { 8894 // Disabled as this causes speed-profile compilation during first boot 8895 // even if things are already compiled. 8896 // useProfileForDexopt = true; 8897 } 8898 } catch (Exception e) { 8899 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8900 e); 8901 } 8902 } else { 8903 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8904 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8905 // minimize the number off apps being speed-profile compiled during first boot. 8906 // The other paths will not change the filter. 8907 if (disabledPs != null && disabledPs.pkg.isStub) { 8908 // The package is the stub one, remove the stub suffix to get the normal 8909 // package and APK names. 8910 String systemProfilePath = 8911 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8912 profileFile = new File(systemProfilePath); 8913 // If we have a profile for a compressed APK, copy it to the reference 8914 // location. 8915 // Note that copying the profile here will cause it to override the 8916 // reference profile every OTA even though the existing reference profile 8917 // may have more data. We can't copy during decompression since the 8918 // directories are not set up at that point. 8919 if (profileFile.exists()) { 8920 try { 8921 // We could also do this lazily before calling dexopt in 8922 // PackageDexOptimizer to prevent this happening on first boot. The 8923 // issue is that we don't have a good way to say "do this only 8924 // once". 8925 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8926 pkg.applicationInfo.uid, pkg.packageName, 8927 ArtManager.getProfileName(null))) { 8928 Log.e(TAG, "Failed to copy system profile for stub package!"); 8929 } else { 8930 useProfileForDexopt = true; 8931 } 8932 } catch (Exception e) { 8933 Log.e(TAG, "Failed to copy profile " + 8934 profileFile.getAbsolutePath() + " ", e); 8935 } 8936 } 8937 } 8938 } 8939 } 8940 8941 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8942 if (DEBUG_DEXOPT) { 8943 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8944 } 8945 numberOfPackagesSkipped++; 8946 continue; 8947 } 8948 8949 if (DEBUG_DEXOPT) { 8950 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8951 numberOfPackagesToDexopt + ": " + pkg.packageName); 8952 } 8953 8954 if (showDialog) { 8955 try { 8956 ActivityManager.getService().showBootMessage( 8957 mContext.getResources().getString(R.string.android_upgrading_apk, 8958 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8959 } catch (RemoteException e) { 8960 } 8961 synchronized (mPackages) { 8962 mDexOptDialogShown = true; 8963 } 8964 } 8965 8966 int pkgCompilationReason = compilationReason; 8967 if (useProfileForDexopt) { 8968 // Use background dexopt mode to try and use the profile. Note that this does not 8969 // guarantee usage of the profile. 8970 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 8971 } 8972 8973 // checkProfiles is false to avoid merging profiles during boot which 8974 // might interfere with background compilation (b/28612421). 8975 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8976 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8977 // trade-off worth doing to save boot time work. 8978 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8979 if (compilationReason == REASON_FIRST_BOOT) { 8980 // TODO: This doesn't cover the upgrade case, we should check for this too. 8981 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 8982 } 8983 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8984 pkg.packageName, 8985 pkgCompilationReason, 8986 dexoptFlags)); 8987 8988 switch (primaryDexOptStaus) { 8989 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8990 numberOfPackagesOptimized++; 8991 break; 8992 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8993 numberOfPackagesSkipped++; 8994 break; 8995 case PackageDexOptimizer.DEX_OPT_FAILED: 8996 numberOfPackagesFailed++; 8997 break; 8998 default: 8999 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9000 break; 9001 } 9002 } 9003 9004 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9005 numberOfPackagesFailed }; 9006 } 9007 9008 @Override 9009 public void notifyPackageUse(String packageName, int reason) { 9010 synchronized (mPackages) { 9011 final int callingUid = Binder.getCallingUid(); 9012 final int callingUserId = UserHandle.getUserId(callingUid); 9013 if (getInstantAppPackageName(callingUid) != null) { 9014 if (!isCallerSameApp(packageName, callingUid)) { 9015 return; 9016 } 9017 } else { 9018 if (isInstantApp(packageName, callingUserId)) { 9019 return; 9020 } 9021 } 9022 notifyPackageUseLocked(packageName, reason); 9023 } 9024 } 9025 9026 @GuardedBy("mPackages") 9027 private void notifyPackageUseLocked(String packageName, int reason) { 9028 final PackageParser.Package p = mPackages.get(packageName); 9029 if (p == null) { 9030 return; 9031 } 9032 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9033 } 9034 9035 @Override 9036 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9037 List<String> classPaths, String loaderIsa) { 9038 int userId = UserHandle.getCallingUserId(); 9039 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9040 if (ai == null) { 9041 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9042 + loadingPackageName + ", user=" + userId); 9043 return; 9044 } 9045 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9046 } 9047 9048 @Override 9049 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9050 IDexModuleRegisterCallback callback) { 9051 int userId = UserHandle.getCallingUserId(); 9052 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9053 DexManager.RegisterDexModuleResult result; 9054 if (ai == null) { 9055 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9056 " calling user. package=" + packageName + ", user=" + userId); 9057 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9058 } else { 9059 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9060 } 9061 9062 if (callback != null) { 9063 mHandler.post(() -> { 9064 try { 9065 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9066 } catch (RemoteException e) { 9067 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9068 } 9069 }); 9070 } 9071 } 9072 9073 /** 9074 * Ask the package manager to perform a dex-opt with the given compiler filter. 9075 * 9076 * Note: exposed only for the shell command to allow moving packages explicitly to a 9077 * definite state. 9078 */ 9079 @Override 9080 public boolean performDexOptMode(String packageName, 9081 boolean checkProfiles, String targetCompilerFilter, boolean force, 9082 boolean bootComplete, String splitName) { 9083 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9084 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9085 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9086 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9087 targetCompilerFilter, splitName, flags)); 9088 } 9089 9090 /** 9091 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9092 * secondary dex files belonging to the given package. 9093 * 9094 * Note: exposed only for the shell command to allow moving packages explicitly to a 9095 * definite state. 9096 */ 9097 @Override 9098 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9099 boolean force) { 9100 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9101 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9102 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9103 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9104 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9105 } 9106 9107 /*package*/ boolean performDexOpt(DexoptOptions options) { 9108 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9109 return false; 9110 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9111 return false; 9112 } 9113 9114 if (options.isDexoptOnlySecondaryDex()) { 9115 return mDexManager.dexoptSecondaryDex(options); 9116 } else { 9117 int dexoptStatus = performDexOptWithStatus(options); 9118 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9119 } 9120 } 9121 9122 /** 9123 * Perform dexopt on the given package and return one of following result: 9124 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9125 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9126 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9127 */ 9128 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9129 return performDexOptTraced(options); 9130 } 9131 9132 private int performDexOptTraced(DexoptOptions options) { 9133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9134 try { 9135 return performDexOptInternal(options); 9136 } finally { 9137 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9138 } 9139 } 9140 9141 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9142 // if the package can now be considered up to date for the given filter. 9143 private int performDexOptInternal(DexoptOptions options) { 9144 PackageParser.Package p; 9145 synchronized (mPackages) { 9146 p = mPackages.get(options.getPackageName()); 9147 if (p == null) { 9148 // Package could not be found. Report failure. 9149 return PackageDexOptimizer.DEX_OPT_FAILED; 9150 } 9151 mPackageUsage.maybeWriteAsync(mPackages); 9152 mCompilerStats.maybeWriteAsync(); 9153 } 9154 long callingId = Binder.clearCallingIdentity(); 9155 try { 9156 synchronized (mInstallLock) { 9157 return performDexOptInternalWithDependenciesLI(p, options); 9158 } 9159 } finally { 9160 Binder.restoreCallingIdentity(callingId); 9161 } 9162 } 9163 9164 public ArraySet<String> getOptimizablePackages() { 9165 ArraySet<String> pkgs = new ArraySet<String>(); 9166 synchronized (mPackages) { 9167 for (PackageParser.Package p : mPackages.values()) { 9168 if (PackageDexOptimizer.canOptimizePackage(p)) { 9169 pkgs.add(p.packageName); 9170 } 9171 } 9172 } 9173 return pkgs; 9174 } 9175 9176 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9177 DexoptOptions options) { 9178 // Select the dex optimizer based on the force parameter. 9179 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9180 // allocate an object here. 9181 PackageDexOptimizer pdo = options.isForce() 9182 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9183 : mPackageDexOptimizer; 9184 9185 // Dexopt all dependencies first. Note: we ignore the return value and march on 9186 // on errors. 9187 // Note that we are going to call performDexOpt on those libraries as many times as 9188 // they are referenced in packages. When we do a batch of performDexOpt (for example 9189 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9190 // and the first package that uses the library will dexopt it. The 9191 // others will see that the compiled code for the library is up to date. 9192 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9193 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9194 if (!deps.isEmpty()) { 9195 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9196 options.getCompilationReason(), options.getCompilerFilter(), 9197 options.getSplitName(), 9198 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9199 for (PackageParser.Package depPackage : deps) { 9200 // TODO: Analyze and investigate if we (should) profile libraries. 9201 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9202 getOrCreateCompilerPackageStats(depPackage), 9203 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9204 } 9205 } 9206 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9207 getOrCreateCompilerPackageStats(p), 9208 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9209 } 9210 9211 /** 9212 * Reconcile the information we have about the secondary dex files belonging to 9213 * {@code packagName} and the actual dex files. For all dex files that were 9214 * deleted, update the internal records and delete the generated oat files. 9215 */ 9216 @Override 9217 public void reconcileSecondaryDexFiles(String packageName) { 9218 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9219 return; 9220 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9221 return; 9222 } 9223 mDexManager.reconcileSecondaryDexFiles(packageName); 9224 } 9225 9226 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9227 // a reference there. 9228 /*package*/ DexManager getDexManager() { 9229 return mDexManager; 9230 } 9231 9232 /** 9233 * Execute the background dexopt job immediately. 9234 */ 9235 @Override 9236 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9237 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9238 return false; 9239 } 9240 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9241 } 9242 9243 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9244 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9245 || p.usesStaticLibraries != null) { 9246 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9247 Set<String> collectedNames = new HashSet<>(); 9248 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9249 9250 retValue.remove(p); 9251 9252 return retValue; 9253 } else { 9254 return Collections.emptyList(); 9255 } 9256 } 9257 9258 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9259 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9260 if (!collectedNames.contains(p.packageName)) { 9261 collectedNames.add(p.packageName); 9262 collected.add(p); 9263 9264 if (p.usesLibraries != null) { 9265 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9266 null, collected, collectedNames); 9267 } 9268 if (p.usesOptionalLibraries != null) { 9269 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9270 null, collected, collectedNames); 9271 } 9272 if (p.usesStaticLibraries != null) { 9273 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9274 p.usesStaticLibrariesVersions, collected, collectedNames); 9275 } 9276 } 9277 } 9278 9279 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9280 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9281 final int libNameCount = libs.size(); 9282 for (int i = 0; i < libNameCount; i++) { 9283 String libName = libs.get(i); 9284 long version = (versions != null && versions.length == libNameCount) 9285 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9286 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9287 if (libPkg != null) { 9288 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9289 } 9290 } 9291 } 9292 9293 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9294 synchronized (mPackages) { 9295 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9296 if (libEntry != null) { 9297 return mPackages.get(libEntry.apk); 9298 } 9299 return null; 9300 } 9301 } 9302 9303 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9304 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9305 if (versionedLib == null) { 9306 return null; 9307 } 9308 return versionedLib.get(version); 9309 } 9310 9311 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9312 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9313 pkg.staticSharedLibName); 9314 if (versionedLib == null) { 9315 return null; 9316 } 9317 long previousLibVersion = -1; 9318 final int versionCount = versionedLib.size(); 9319 for (int i = 0; i < versionCount; i++) { 9320 final long libVersion = versionedLib.keyAt(i); 9321 if (libVersion < pkg.staticSharedLibVersion) { 9322 previousLibVersion = Math.max(previousLibVersion, libVersion); 9323 } 9324 } 9325 if (previousLibVersion >= 0) { 9326 return versionedLib.get(previousLibVersion); 9327 } 9328 return null; 9329 } 9330 9331 public void shutdown() { 9332 mPackageUsage.writeNow(mPackages); 9333 mCompilerStats.writeNow(); 9334 mDexManager.writePackageDexUsageNow(); 9335 } 9336 9337 @Override 9338 public void dumpProfiles(String packageName) { 9339 PackageParser.Package pkg; 9340 synchronized (mPackages) { 9341 pkg = mPackages.get(packageName); 9342 if (pkg == null) { 9343 throw new IllegalArgumentException("Unknown package: " + packageName); 9344 } 9345 } 9346 /* Only the shell, root, or the app user should be able to dump profiles. */ 9347 int callingUid = Binder.getCallingUid(); 9348 if (callingUid != Process.SHELL_UID && 9349 callingUid != Process.ROOT_UID && 9350 callingUid != pkg.applicationInfo.uid) { 9351 throw new SecurityException("dumpProfiles"); 9352 } 9353 9354 synchronized (mInstallLock) { 9355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9356 mArtManagerService.dumpProfiles(pkg); 9357 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9358 } 9359 } 9360 9361 @Override 9362 public void forceDexOpt(String packageName) { 9363 enforceSystemOrRoot("forceDexOpt"); 9364 9365 PackageParser.Package pkg; 9366 synchronized (mPackages) { 9367 pkg = mPackages.get(packageName); 9368 if (pkg == null) { 9369 throw new IllegalArgumentException("Unknown package: " + packageName); 9370 } 9371 } 9372 9373 synchronized (mInstallLock) { 9374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9375 9376 // Whoever is calling forceDexOpt wants a compiled package. 9377 // Don't use profiles since that may cause compilation to be skipped. 9378 final int res = performDexOptInternalWithDependenciesLI( 9379 pkg, 9380 new DexoptOptions(packageName, 9381 getDefaultCompilerFilter(), 9382 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9383 9384 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9385 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9386 throw new IllegalStateException("Failed to dexopt: " + res); 9387 } 9388 } 9389 } 9390 9391 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9392 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9393 Slog.w(TAG, "Unable to update from " + oldPkg.name 9394 + " to " + newPkg.packageName 9395 + ": old package not in system partition"); 9396 return false; 9397 } else if (mPackages.get(oldPkg.name) != null) { 9398 Slog.w(TAG, "Unable to update from " + oldPkg.name 9399 + " to " + newPkg.packageName 9400 + ": old package still exists"); 9401 return false; 9402 } 9403 return true; 9404 } 9405 9406 void removeCodePathLI(File codePath) { 9407 if (codePath.isDirectory()) { 9408 try { 9409 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9410 } catch (InstallerException e) { 9411 Slog.w(TAG, "Failed to remove code path", e); 9412 } 9413 } else { 9414 codePath.delete(); 9415 } 9416 } 9417 9418 private int[] resolveUserIds(int userId) { 9419 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9420 } 9421 9422 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9423 if (pkg == null) { 9424 Slog.wtf(TAG, "Package was null!", new Throwable()); 9425 return; 9426 } 9427 clearAppDataLeafLIF(pkg, userId, flags); 9428 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9429 for (int i = 0; i < childCount; i++) { 9430 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9431 } 9432 9433 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9434 } 9435 9436 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9437 final PackageSetting ps; 9438 synchronized (mPackages) { 9439 ps = mSettings.mPackages.get(pkg.packageName); 9440 } 9441 for (int realUserId : resolveUserIds(userId)) { 9442 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9443 try { 9444 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9445 ceDataInode); 9446 } catch (InstallerException e) { 9447 Slog.w(TAG, String.valueOf(e)); 9448 } 9449 } 9450 } 9451 9452 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9453 if (pkg == null) { 9454 Slog.wtf(TAG, "Package was null!", new Throwable()); 9455 return; 9456 } 9457 destroyAppDataLeafLIF(pkg, userId, flags); 9458 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9459 for (int i = 0; i < childCount; i++) { 9460 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9461 } 9462 } 9463 9464 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9465 final PackageSetting ps; 9466 synchronized (mPackages) { 9467 ps = mSettings.mPackages.get(pkg.packageName); 9468 } 9469 for (int realUserId : resolveUserIds(userId)) { 9470 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9471 try { 9472 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9473 ceDataInode); 9474 } catch (InstallerException e) { 9475 Slog.w(TAG, String.valueOf(e)); 9476 } 9477 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9478 } 9479 } 9480 9481 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9482 if (pkg == null) { 9483 Slog.wtf(TAG, "Package was null!", new Throwable()); 9484 return; 9485 } 9486 destroyAppProfilesLeafLIF(pkg); 9487 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9488 for (int i = 0; i < childCount; i++) { 9489 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9490 } 9491 } 9492 9493 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9494 try { 9495 mInstaller.destroyAppProfiles(pkg.packageName); 9496 } catch (InstallerException e) { 9497 Slog.w(TAG, String.valueOf(e)); 9498 } 9499 } 9500 9501 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9502 if (pkg == null) { 9503 Slog.wtf(TAG, "Package was null!", new Throwable()); 9504 return; 9505 } 9506 mArtManagerService.clearAppProfiles(pkg); 9507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9508 for (int i = 0; i < childCount; i++) { 9509 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9510 } 9511 } 9512 9513 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9514 long lastUpdateTime) { 9515 // Set parent install/update time 9516 PackageSetting ps = (PackageSetting) pkg.mExtras; 9517 if (ps != null) { 9518 ps.firstInstallTime = firstInstallTime; 9519 ps.lastUpdateTime = lastUpdateTime; 9520 } 9521 // Set children install/update time 9522 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9523 for (int i = 0; i < childCount; i++) { 9524 PackageParser.Package childPkg = pkg.childPackages.get(i); 9525 ps = (PackageSetting) childPkg.mExtras; 9526 if (ps != null) { 9527 ps.firstInstallTime = firstInstallTime; 9528 ps.lastUpdateTime = lastUpdateTime; 9529 } 9530 } 9531 } 9532 9533 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9534 SharedLibraryEntry file, 9535 PackageParser.Package changingLib) { 9536 if (file.path != null) { 9537 usesLibraryFiles.add(file.path); 9538 return; 9539 } 9540 PackageParser.Package p = mPackages.get(file.apk); 9541 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9542 // If we are doing this while in the middle of updating a library apk, 9543 // then we need to make sure to use that new apk for determining the 9544 // dependencies here. (We haven't yet finished committing the new apk 9545 // to the package manager state.) 9546 if (p == null || p.packageName.equals(changingLib.packageName)) { 9547 p = changingLib; 9548 } 9549 } 9550 if (p != null) { 9551 usesLibraryFiles.addAll(p.getAllCodePaths()); 9552 if (p.usesLibraryFiles != null) { 9553 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9554 } 9555 } 9556 } 9557 9558 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9559 PackageParser.Package changingLib) throws PackageManagerException { 9560 if (pkg == null) { 9561 return; 9562 } 9563 // The collection used here must maintain the order of addition (so 9564 // that libraries are searched in the correct order) and must have no 9565 // duplicates. 9566 Set<String> usesLibraryFiles = null; 9567 if (pkg.usesLibraries != null) { 9568 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9569 null, null, pkg.packageName, changingLib, true, 9570 pkg.applicationInfo.targetSdkVersion, null); 9571 } 9572 if (pkg.usesStaticLibraries != null) { 9573 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9574 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9575 pkg.packageName, changingLib, true, 9576 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9577 } 9578 if (pkg.usesOptionalLibraries != null) { 9579 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9580 null, null, pkg.packageName, changingLib, false, 9581 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9582 } 9583 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9584 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9585 } else { 9586 pkg.usesLibraryFiles = null; 9587 } 9588 } 9589 9590 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9591 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9592 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9593 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9594 throws PackageManagerException { 9595 final int libCount = requestedLibraries.size(); 9596 for (int i = 0; i < libCount; i++) { 9597 final String libName = requestedLibraries.get(i); 9598 final long libVersion = requiredVersions != null ? requiredVersions[i] 9599 : SharedLibraryInfo.VERSION_UNDEFINED; 9600 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9601 if (libEntry == null) { 9602 if (required) { 9603 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9604 "Package " + packageName + " requires unavailable shared library " 9605 + libName + "; failing!"); 9606 } else if (DEBUG_SHARED_LIBRARIES) { 9607 Slog.i(TAG, "Package " + packageName 9608 + " desires unavailable shared library " 9609 + libName + "; ignoring!"); 9610 } 9611 } else { 9612 if (requiredVersions != null && requiredCertDigests != null) { 9613 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9614 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9615 "Package " + packageName + " requires unavailable static shared" 9616 + " library " + libName + " version " 9617 + libEntry.info.getLongVersion() + "; failing!"); 9618 } 9619 9620 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9621 if (libPkg == null) { 9622 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9623 "Package " + packageName + " requires unavailable static shared" 9624 + " library; failing!"); 9625 } 9626 9627 final String[] expectedCertDigests = requiredCertDigests[i]; 9628 9629 9630 if (expectedCertDigests.length > 1) { 9631 9632 // For apps targeting O MR1 we require explicit enumeration of all certs. 9633 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9634 ? PackageUtils.computeSignaturesSha256Digests( 9635 libPkg.mSigningDetails.signatures) 9636 : PackageUtils.computeSignaturesSha256Digests( 9637 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9638 9639 // Take a shortcut if sizes don't match. Note that if an app doesn't 9640 // target O we don't parse the "additional-certificate" tags similarly 9641 // how we only consider all certs only for apps targeting O (see above). 9642 // Therefore, the size check is safe to make. 9643 if (expectedCertDigests.length != libCertDigests.length) { 9644 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9645 "Package " + packageName + " requires differently signed" + 9646 " static shared library; failing!"); 9647 } 9648 9649 // Use a predictable order as signature order may vary 9650 Arrays.sort(libCertDigests); 9651 Arrays.sort(expectedCertDigests); 9652 9653 final int certCount = libCertDigests.length; 9654 for (int j = 0; j < certCount; j++) { 9655 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9656 throw new PackageManagerException( 9657 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9658 "Package " + packageName + " requires differently signed" + 9659 " static shared library; failing!"); 9660 } 9661 } 9662 } else { 9663 9664 // lib signing cert could have rotated beyond the one expected, check to see 9665 // if the new one has been blessed by the old 9666 if (!libPkg.mSigningDetails.hasSha256Certificate( 9667 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 9668 throw new PackageManagerException( 9669 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9670 "Package " + packageName + " requires differently signed" + 9671 " static shared library; failing!"); 9672 } 9673 } 9674 } 9675 9676 if (outUsedLibraries == null) { 9677 // Use LinkedHashSet to preserve the order of files added to 9678 // usesLibraryFiles while eliminating duplicates. 9679 outUsedLibraries = new LinkedHashSet<>(); 9680 } 9681 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9682 } 9683 } 9684 return outUsedLibraries; 9685 } 9686 9687 private static boolean hasString(List<String> list, List<String> which) { 9688 if (list == null) { 9689 return false; 9690 } 9691 for (int i=list.size()-1; i>=0; i--) { 9692 for (int j=which.size()-1; j>=0; j--) { 9693 if (which.get(j).equals(list.get(i))) { 9694 return true; 9695 } 9696 } 9697 } 9698 return false; 9699 } 9700 9701 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9702 PackageParser.Package changingPkg) { 9703 ArrayList<PackageParser.Package> res = null; 9704 for (PackageParser.Package pkg : mPackages.values()) { 9705 if (changingPkg != null 9706 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9707 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9708 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9709 changingPkg.staticSharedLibName)) { 9710 return null; 9711 } 9712 if (res == null) { 9713 res = new ArrayList<>(); 9714 } 9715 res.add(pkg); 9716 try { 9717 updateSharedLibrariesLPr(pkg, changingPkg); 9718 } catch (PackageManagerException e) { 9719 // If a system app update or an app and a required lib missing we 9720 // delete the package and for updated system apps keep the data as 9721 // it is better for the user to reinstall than to be in an limbo 9722 // state. Also libs disappearing under an app should never happen 9723 // - just in case. 9724 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9725 final int flags = pkg.isUpdatedSystemApp() 9726 ? PackageManager.DELETE_KEEP_DATA : 0; 9727 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9728 flags , null, true, null); 9729 } 9730 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9731 } 9732 } 9733 return res; 9734 } 9735 9736 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9737 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9738 @Nullable UserHandle user) throws PackageManagerException { 9739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9740 // If the package has children and this is the first dive in the function 9741 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9742 // whether all packages (parent and children) would be successfully scanned 9743 // before the actual scan since scanning mutates internal state and we want 9744 // to atomically install the package and its children. 9745 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9746 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9747 scanFlags |= SCAN_CHECK_ONLY; 9748 } 9749 } else { 9750 scanFlags &= ~SCAN_CHECK_ONLY; 9751 } 9752 9753 final PackageParser.Package scannedPkg; 9754 try { 9755 // Scan the parent 9756 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9757 // Scan the children 9758 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9759 for (int i = 0; i < childCount; i++) { 9760 PackageParser.Package childPkg = pkg.childPackages.get(i); 9761 scanPackageNewLI(childPkg, parseFlags, 9762 scanFlags, currentTime, user); 9763 } 9764 } finally { 9765 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9766 } 9767 9768 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9769 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9770 } 9771 9772 return scannedPkg; 9773 } 9774 9775 /** The result of a package scan. */ 9776 private static class ScanResult { 9777 /** Whether or not the package scan was successful */ 9778 public final boolean success; 9779 /** 9780 * The final package settings. This may be the same object passed in 9781 * the {@link ScanRequest}, but, with modified values. 9782 */ 9783 @Nullable public final PackageSetting pkgSetting; 9784 /** ABI code paths that have changed in the package scan */ 9785 @Nullable public final List<String> changedAbiCodePath; 9786 public ScanResult( 9787 boolean success, 9788 @Nullable PackageSetting pkgSetting, 9789 @Nullable List<String> changedAbiCodePath) { 9790 this.success = success; 9791 this.pkgSetting = pkgSetting; 9792 this.changedAbiCodePath = changedAbiCodePath; 9793 } 9794 } 9795 9796 /** A package to be scanned */ 9797 private static class ScanRequest { 9798 /** The parsed package */ 9799 @NonNull public final PackageParser.Package pkg; 9800 /** Shared user settings, if the package has a shared user */ 9801 @Nullable public final SharedUserSetting sharedUserSetting; 9802 /** 9803 * Package settings of the currently installed version. 9804 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9805 * during scan. 9806 */ 9807 @Nullable public final PackageSetting pkgSetting; 9808 /** A copy of the settings for the currently installed version */ 9809 @Nullable public final PackageSetting oldPkgSetting; 9810 /** Package settings for the disabled version on the /system partition */ 9811 @Nullable public final PackageSetting disabledPkgSetting; 9812 /** Package settings for the installed version under its original package name */ 9813 @Nullable public final PackageSetting originalPkgSetting; 9814 /** The real package name of a renamed application */ 9815 @Nullable public final String realPkgName; 9816 public final @ParseFlags int parseFlags; 9817 public final @ScanFlags int scanFlags; 9818 /** The user for which the package is being scanned */ 9819 @Nullable public final UserHandle user; 9820 /** Whether or not the platform package is being scanned */ 9821 public final boolean isPlatformPackage; 9822 public ScanRequest( 9823 @NonNull PackageParser.Package pkg, 9824 @Nullable SharedUserSetting sharedUserSetting, 9825 @Nullable PackageSetting pkgSetting, 9826 @Nullable PackageSetting disabledPkgSetting, 9827 @Nullable PackageSetting originalPkgSetting, 9828 @Nullable String realPkgName, 9829 @ParseFlags int parseFlags, 9830 @ScanFlags int scanFlags, 9831 boolean isPlatformPackage, 9832 @Nullable UserHandle user) { 9833 this.pkg = pkg; 9834 this.pkgSetting = pkgSetting; 9835 this.sharedUserSetting = sharedUserSetting; 9836 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9837 this.disabledPkgSetting = disabledPkgSetting; 9838 this.originalPkgSetting = originalPkgSetting; 9839 this.realPkgName = realPkgName; 9840 this.parseFlags = parseFlags; 9841 this.scanFlags = scanFlags; 9842 this.isPlatformPackage = isPlatformPackage; 9843 this.user = user; 9844 } 9845 } 9846 9847 /** 9848 * Returns the actual scan flags depending upon the state of the other settings. 9849 * <p>Updated system applications will not have the following flags set 9850 * by default and need to be adjusted after the fact: 9851 * <ul> 9852 * <li>{@link #SCAN_AS_SYSTEM}</li> 9853 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9854 * <li>{@link #SCAN_AS_OEM}</li> 9855 * <li>{@link #SCAN_AS_VENDOR}</li> 9856 * <li>{@link #SCAN_AS_PRODUCT}</li> 9857 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9858 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9859 * </ul> 9860 */ 9861 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9862 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9863 PackageParser.Package pkg) { 9864 if (disabledPkgSetting != null) { 9865 // updated system application, must at least have SCAN_AS_SYSTEM 9866 scanFlags |= SCAN_AS_SYSTEM; 9867 if ((disabledPkgSetting.pkgPrivateFlags 9868 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9869 scanFlags |= SCAN_AS_PRIVILEGED; 9870 } 9871 if ((disabledPkgSetting.pkgPrivateFlags 9872 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9873 scanFlags |= SCAN_AS_OEM; 9874 } 9875 if ((disabledPkgSetting.pkgPrivateFlags 9876 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9877 scanFlags |= SCAN_AS_VENDOR; 9878 } 9879 if ((disabledPkgSetting.pkgPrivateFlags 9880 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9881 scanFlags |= SCAN_AS_PRODUCT; 9882 } 9883 } 9884 if (pkgSetting != null) { 9885 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9886 if (pkgSetting.getInstantApp(userId)) { 9887 scanFlags |= SCAN_AS_INSTANT_APP; 9888 } 9889 if (pkgSetting.getVirtulalPreload(userId)) { 9890 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9891 } 9892 } 9893 9894 // Scan as privileged apps that share a user with a priv-app. 9895 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9896 && (pkg.mSharedUserId != null)) { 9897 SharedUserSetting sharedUserSetting = null; 9898 try { 9899 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9900 } catch (PackageManagerException ignore) {} 9901 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9902 // Exempt SharedUsers signed with the platform key. 9903 // TODO(b/72378145) Fix this exemption. Force signature apps 9904 // to whitelist their privileged permissions just like other 9905 // priv-apps. 9906 synchronized (mPackages) { 9907 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9908 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9909 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9910 scanFlags |= SCAN_AS_PRIVILEGED; 9911 } 9912 } 9913 } 9914 } 9915 9916 return scanFlags; 9917 } 9918 9919 @GuardedBy("mInstallLock") 9920 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9921 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9922 @Nullable UserHandle user) throws PackageManagerException { 9923 9924 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9925 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9926 if (realPkgName != null) { 9927 ensurePackageRenamed(pkg, renamedPkgName); 9928 } 9929 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9930 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9931 final PackageSetting disabledPkgSetting = 9932 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9933 9934 if (mTransferedPackages.contains(pkg.packageName)) { 9935 Slog.w(TAG, "Package " + pkg.packageName 9936 + " was transferred to another, but its .apk remains"); 9937 } 9938 9939 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 9940 synchronized (mPackages) { 9941 applyPolicy(pkg, parseFlags, scanFlags); 9942 assertPackageIsValid(pkg, parseFlags, scanFlags); 9943 9944 SharedUserSetting sharedUserSetting = null; 9945 if (pkg.mSharedUserId != null) { 9946 // SIDE EFFECTS; may potentially allocate a new shared user 9947 sharedUserSetting = mSettings.getSharedUserLPw( 9948 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9949 if (DEBUG_PACKAGE_SCANNING) { 9950 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9951 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9952 + " (uid=" + sharedUserSetting.userId + "):" 9953 + " packages=" + sharedUserSetting.packages); 9954 } 9955 } 9956 9957 boolean scanSucceeded = false; 9958 try { 9959 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9960 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9961 (pkg == mPlatformPackage), user); 9962 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9963 if (result.success) { 9964 commitScanResultsLocked(request, result); 9965 } 9966 scanSucceeded = true; 9967 } finally { 9968 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9969 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9970 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9971 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9972 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9973 } 9974 } 9975 } 9976 return pkg; 9977 } 9978 9979 /** 9980 * Commits the package scan and modifies system state. 9981 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 9982 * of committing the package, leaving the system in an inconsistent state. 9983 * This needs to be fixed so, once we get to this point, no errors are 9984 * possible and the system is not left in an inconsistent state. 9985 */ 9986 @GuardedBy("mPackages") 9987 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 9988 throws PackageManagerException { 9989 final PackageParser.Package pkg = request.pkg; 9990 final @ParseFlags int parseFlags = request.parseFlags; 9991 final @ScanFlags int scanFlags = request.scanFlags; 9992 final PackageSetting oldPkgSetting = request.oldPkgSetting; 9993 final PackageSetting originalPkgSetting = request.originalPkgSetting; 9994 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 9995 final UserHandle user = request.user; 9996 final String realPkgName = request.realPkgName; 9997 final PackageSetting pkgSetting = result.pkgSetting; 9998 final List<String> changedAbiCodePath = result.changedAbiCodePath; 9999 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10000 10001 if (newPkgSettingCreated) { 10002 if (originalPkgSetting != null) { 10003 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10004 } 10005 // THROWS: when we can't allocate a user id. add call to check if there's 10006 // enough space to ensure we won't throw; otherwise, don't modify state 10007 mSettings.addUserToSettingLPw(pkgSetting); 10008 10009 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10010 mTransferedPackages.add(originalPkgSetting.name); 10011 } 10012 } 10013 // TODO(toddke): Consider a method specifically for modifying the Package object 10014 // post scan; or, moving this stuff out of the Package object since it has nothing 10015 // to do with the package on disk. 10016 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10017 // for creating the application ID. If we did this earlier, we would be saving the 10018 // correct ID. 10019 pkg.applicationInfo.uid = pkgSetting.appId; 10020 10021 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10022 10023 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10024 mTransferedPackages.add(pkg.packageName); 10025 } 10026 10027 // THROWS: when requested libraries that can't be found. it only changes 10028 // the state of the passed in pkg object, so, move to the top of the method 10029 // and allow it to abort 10030 if ((scanFlags & SCAN_BOOTING) == 0 10031 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10032 // Check all shared libraries and map to their actual file path. 10033 // We only do this here for apps not on a system dir, because those 10034 // are the only ones that can fail an install due to this. We 10035 // will take care of the system apps by updating all of their 10036 // library paths after the scan is done. Also during the initial 10037 // scan don't update any libs as we do this wholesale after all 10038 // apps are scanned to avoid dependency based scanning. 10039 updateSharedLibrariesLPr(pkg, null); 10040 } 10041 10042 // All versions of a static shared library are referenced with the same 10043 // package name. Internally, we use a synthetic package name to allow 10044 // multiple versions of the same shared library to be installed. So, 10045 // we need to generate the synthetic package name of the latest shared 10046 // library in order to compare signatures. 10047 PackageSetting signatureCheckPs = pkgSetting; 10048 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10049 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10050 if (libraryEntry != null) { 10051 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10052 } 10053 } 10054 10055 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10056 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10057 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10058 // We just determined the app is signed correctly, so bring 10059 // over the latest parsed certs. 10060 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10061 } else { 10062 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10063 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10064 "Package " + pkg.packageName + " upgrade keys do not match the " 10065 + "previously installed version"); 10066 } else { 10067 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10068 String msg = "System package " + pkg.packageName 10069 + " signature changed; retaining data."; 10070 reportSettingsProblem(Log.WARN, msg); 10071 } 10072 } 10073 } else { 10074 try { 10075 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10076 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10077 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10078 pkg.mSigningDetails, compareCompat, compareRecover); 10079 // The new KeySets will be re-added later in the scanning process. 10080 if (compatMatch) { 10081 synchronized (mPackages) { 10082 ksms.removeAppKeySetDataLPw(pkg.packageName); 10083 } 10084 } 10085 // We just determined the app is signed correctly, so bring 10086 // over the latest parsed certs. 10087 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10088 10089 10090 // if this is is a sharedUser, check to see if the new package is signed by a newer 10091 // signing certificate than the existing one, and if so, copy over the new details 10092 if (signatureCheckPs.sharedUser != null 10093 && pkg.mSigningDetails.hasAncestor( 10094 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 10095 signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails; 10096 } 10097 } catch (PackageManagerException e) { 10098 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10099 throw e; 10100 } 10101 // The signature has changed, but this package is in the system 10102 // image... let's recover! 10103 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10104 // However... if this package is part of a shared user, but it 10105 // doesn't match the signature of the shared user, let's fail. 10106 // What this means is that you can't change the signatures 10107 // associated with an overall shared user, which doesn't seem all 10108 // that unreasonable. 10109 if (signatureCheckPs.sharedUser != null) { 10110 if (compareSignatures( 10111 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10112 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10113 throw new PackageManagerException( 10114 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10115 "Signature mismatch for shared user: " 10116 + pkgSetting.sharedUser); 10117 } 10118 } 10119 // File a report about this. 10120 String msg = "System package " + pkg.packageName 10121 + " signature changed; retaining data."; 10122 reportSettingsProblem(Log.WARN, msg); 10123 } catch (IllegalArgumentException e) { 10124 10125 // should never happen: certs matched when checking, but not when comparing 10126 // old to new for sharedUser 10127 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10128 "Signing certificates comparison made on incomparable signing details" 10129 + " but somehow passed verifySignatures!"); 10130 } 10131 } 10132 10133 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10134 // This package wants to adopt ownership of permissions from 10135 // another package. 10136 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10137 final String origName = pkg.mAdoptPermissions.get(i); 10138 final PackageSetting orig = mSettings.getPackageLPr(origName); 10139 if (orig != null) { 10140 if (verifyPackageUpdateLPr(orig, pkg)) { 10141 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10142 + pkg.packageName); 10143 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10144 } 10145 } 10146 } 10147 } 10148 10149 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10150 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10151 final String codePathString = changedAbiCodePath.get(i); 10152 try { 10153 mInstaller.rmdex(codePathString, 10154 getDexCodeInstructionSet(getPreferredInstructionSet())); 10155 } catch (InstallerException ignored) { 10156 } 10157 } 10158 } 10159 10160 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10161 if (oldPkgSetting != null) { 10162 synchronized (mPackages) { 10163 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10164 } 10165 } 10166 } else { 10167 final int userId = user == null ? 0 : user.getIdentifier(); 10168 // Modify state for the given package setting 10169 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10170 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10171 if (pkgSetting.getInstantApp(userId)) { 10172 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10173 } 10174 } 10175 } 10176 10177 /** 10178 * Returns the "real" name of the package. 10179 * <p>This may differ from the package's actual name if the application has already 10180 * been installed under one of this package's original names. 10181 */ 10182 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10183 @Nullable String renamedPkgName) { 10184 if (isPackageRenamed(pkg, renamedPkgName)) { 10185 return pkg.mRealPackage; 10186 } 10187 return null; 10188 } 10189 10190 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10191 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10192 @Nullable String renamedPkgName) { 10193 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10194 } 10195 10196 /** 10197 * Returns the original package setting. 10198 * <p>A package can migrate its name during an update. In this scenario, a package 10199 * designates a set of names that it considers as one of its original names. 10200 * <p>An original package must be signed identically and it must have the same 10201 * shared user [if any]. 10202 */ 10203 @GuardedBy("mPackages") 10204 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10205 @Nullable String renamedPkgName) { 10206 if (!isPackageRenamed(pkg, renamedPkgName)) { 10207 return null; 10208 } 10209 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10210 final PackageSetting originalPs = 10211 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10212 if (originalPs != null) { 10213 // the package is already installed under its original name... 10214 // but, should we use it? 10215 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10216 // the new package is incompatible with the original 10217 continue; 10218 } else if (originalPs.sharedUser != null) { 10219 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10220 // the shared user id is incompatible with the original 10221 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10222 + " to " + pkg.packageName + ": old uid " 10223 + originalPs.sharedUser.name 10224 + " differs from " + pkg.mSharedUserId); 10225 continue; 10226 } 10227 // TODO: Add case when shared user id is added [b/28144775] 10228 } else { 10229 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10230 + pkg.packageName + " to old name " + originalPs.name); 10231 } 10232 return originalPs; 10233 } 10234 } 10235 return null; 10236 } 10237 10238 /** 10239 * Renames the package if it was installed under a different name. 10240 * <p>When we've already installed the package under an original name, update 10241 * the new package so we can continue to have the old name. 10242 */ 10243 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10244 @NonNull String renamedPackageName) { 10245 if (pkg.mOriginalPackages == null 10246 || !pkg.mOriginalPackages.contains(renamedPackageName) 10247 || pkg.packageName.equals(renamedPackageName)) { 10248 return; 10249 } 10250 pkg.setPackageName(renamedPackageName); 10251 } 10252 10253 /** 10254 * Just scans the package without any side effects. 10255 * <p>Not entirely true at the moment. There is still one side effect -- this 10256 * method potentially modifies a live {@link PackageSetting} object representing 10257 * the package being scanned. This will be resolved in the future. 10258 * 10259 * @param request Information about the package to be scanned 10260 * @param isUnderFactoryTest Whether or not the device is under factory test 10261 * @param currentTime The current time, in millis 10262 * @return The results of the scan 10263 */ 10264 @GuardedBy("mInstallLock") 10265 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10266 boolean isUnderFactoryTest, long currentTime) 10267 throws PackageManagerException { 10268 final PackageParser.Package pkg = request.pkg; 10269 PackageSetting pkgSetting = request.pkgSetting; 10270 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10271 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10272 final @ParseFlags int parseFlags = request.parseFlags; 10273 final @ScanFlags int scanFlags = request.scanFlags; 10274 final String realPkgName = request.realPkgName; 10275 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10276 final UserHandle user = request.user; 10277 final boolean isPlatformPackage = request.isPlatformPackage; 10278 10279 List<String> changedAbiCodePath = null; 10280 10281 if (DEBUG_PACKAGE_SCANNING) { 10282 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10283 Log.d(TAG, "Scanning package " + pkg.packageName); 10284 } 10285 10286 if (Build.IS_DEBUGGABLE && 10287 pkg.isPrivileged() && 10288 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10289 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10290 } 10291 10292 // Initialize package source and resource directories 10293 final File scanFile = new File(pkg.codePath); 10294 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10295 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10296 10297 // We keep references to the derived CPU Abis from settings in oder to reuse 10298 // them in the case where we're not upgrading or booting for the first time. 10299 String primaryCpuAbiFromSettings = null; 10300 String secondaryCpuAbiFromSettings = null; 10301 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10302 10303 if (!needToDeriveAbi) { 10304 if (pkgSetting != null) { 10305 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10306 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10307 } else { 10308 // Re-scanning a system package after uninstalling updates; need to derive ABI 10309 needToDeriveAbi = true; 10310 } 10311 } 10312 10313 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10314 PackageManagerService.reportSettingsProblem(Log.WARN, 10315 "Package " + pkg.packageName + " shared user changed from " 10316 + (pkgSetting.sharedUser != null 10317 ? pkgSetting.sharedUser.name : "<nothing>") 10318 + " to " 10319 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10320 + "; replacing with new"); 10321 pkgSetting = null; 10322 } 10323 10324 String[] usesStaticLibraries = null; 10325 if (pkg.usesStaticLibraries != null) { 10326 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10327 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10328 } 10329 final boolean createNewPackage = (pkgSetting == null); 10330 if (createNewPackage) { 10331 final String parentPackageName = (pkg.parentPackage != null) 10332 ? pkg.parentPackage.packageName : null; 10333 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10334 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10335 // REMOVE SharedUserSetting from method; update in a separate call 10336 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10337 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10338 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10339 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10340 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10341 user, true /*allowInstall*/, instantApp, virtualPreload, 10342 parentPackageName, pkg.getChildPackageNames(), 10343 UserManagerService.getInstance(), usesStaticLibraries, 10344 pkg.usesStaticLibrariesVersions); 10345 } else { 10346 // REMOVE SharedUserSetting from method; update in a separate call. 10347 // 10348 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10349 // secondaryCpuAbi are not known at this point so we always update them 10350 // to null here, only to reset them at a later point. 10351 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10352 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10353 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10354 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10355 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10356 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10357 } 10358 if (createNewPackage && originalPkgSetting != null) { 10359 // This is the initial transition from the original package, so, 10360 // fix up the new package's name now. We must do this after looking 10361 // up the package under its new name, so getPackageLP takes care of 10362 // fiddling things correctly. 10363 pkg.setPackageName(originalPkgSetting.name); 10364 10365 // File a report about this. 10366 String msg = "New package " + pkgSetting.realName 10367 + " renamed to replace old package " + pkgSetting.name; 10368 reportSettingsProblem(Log.WARN, msg); 10369 } 10370 10371 if (disabledPkgSetting != null) { 10372 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10373 } 10374 10375 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 10376 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 10377 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 10378 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 10379 // least restrictive selinux domain. 10380 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 10381 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 10382 // ensures that all packages continue to run in the same selinux domain. 10383 final int targetSdkVersion = 10384 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 10385 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 10386 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10387 // They currently can be if the sharedUser apps are signed with the platform key. 10388 final boolean isPrivileged = (sharedUserSetting != null) ? 10389 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 10390 10391 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 10392 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 10393 10394 pkg.mExtras = pkgSetting; 10395 pkg.applicationInfo.processName = fixProcessName( 10396 pkg.applicationInfo.packageName, 10397 pkg.applicationInfo.processName); 10398 10399 if (!isPlatformPackage) { 10400 // Get all of our default paths setup 10401 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10402 } 10403 10404 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10405 10406 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10407 if (needToDeriveAbi) { 10408 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10409 final boolean extractNativeLibs = !pkg.isLibrary(); 10410 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10412 10413 // Some system apps still use directory structure for native libraries 10414 // in which case we might end up not detecting abi solely based on apk 10415 // structure. Try to detect abi based on directory structure. 10416 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10417 pkg.applicationInfo.primaryCpuAbi == null) { 10418 setBundledAppAbisAndRoots(pkg, pkgSetting); 10419 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10420 } 10421 } else { 10422 // This is not a first boot or an upgrade, don't bother deriving the 10423 // ABI during the scan. Instead, trust the value that was stored in the 10424 // package setting. 10425 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10426 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10427 10428 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10429 10430 if (DEBUG_ABI_SELECTION) { 10431 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10432 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10433 pkg.applicationInfo.secondaryCpuAbi); 10434 } 10435 } 10436 } else { 10437 if ((scanFlags & SCAN_MOVE) != 0) { 10438 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10439 // but we already have this packages package info in the PackageSetting. We just 10440 // use that and derive the native library path based on the new codepath. 10441 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10442 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10443 } 10444 10445 // Set native library paths again. For moves, the path will be updated based on the 10446 // ABIs we've determined above. For non-moves, the path will be updated based on the 10447 // ABIs we determined during compilation, but the path will depend on the final 10448 // package path (after the rename away from the stage path). 10449 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10450 } 10451 10452 // This is a special case for the "system" package, where the ABI is 10453 // dictated by the zygote configuration (and init.rc). We should keep track 10454 // of this ABI so that we can deal with "normal" applications that run under 10455 // the same UID correctly. 10456 if (isPlatformPackage) { 10457 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10458 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10459 } 10460 10461 // If there's a mismatch between the abi-override in the package setting 10462 // and the abiOverride specified for the install. Warn about this because we 10463 // would've already compiled the app without taking the package setting into 10464 // account. 10465 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10466 if (cpuAbiOverride == null && pkg.packageName != null) { 10467 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10468 " for package " + pkg.packageName); 10469 } 10470 } 10471 10472 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10473 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10474 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10475 10476 // Copy the derived override back to the parsed package, so that we can 10477 // update the package settings accordingly. 10478 pkg.cpuAbiOverride = cpuAbiOverride; 10479 10480 if (DEBUG_ABI_SELECTION) { 10481 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10482 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10483 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10484 } 10485 10486 // Push the derived path down into PackageSettings so we know what to 10487 // clean up at uninstall time. 10488 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10489 10490 if (DEBUG_ABI_SELECTION) { 10491 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10492 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10493 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10494 } 10495 10496 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10497 // We don't do this here during boot because we can do it all 10498 // at once after scanning all existing packages. 10499 // 10500 // We also do this *before* we perform dexopt on this package, so that 10501 // we can avoid redundant dexopts, and also to make sure we've got the 10502 // code and package path correct. 10503 changedAbiCodePath = 10504 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10505 } 10506 10507 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10508 android.Manifest.permission.FACTORY_TEST)) { 10509 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10510 } 10511 10512 if (isSystemApp(pkg)) { 10513 pkgSetting.isOrphaned = true; 10514 } 10515 10516 // Take care of first install / last update times. 10517 final long scanFileTime = getLastModifiedTime(pkg); 10518 if (currentTime != 0) { 10519 if (pkgSetting.firstInstallTime == 0) { 10520 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10521 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10522 pkgSetting.lastUpdateTime = currentTime; 10523 } 10524 } else if (pkgSetting.firstInstallTime == 0) { 10525 // We need *something*. Take time time stamp of the file. 10526 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10527 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10528 if (scanFileTime != pkgSetting.timeStamp) { 10529 // A package on the system image has changed; consider this 10530 // to be an update. 10531 pkgSetting.lastUpdateTime = scanFileTime; 10532 } 10533 } 10534 pkgSetting.setTimeStamp(scanFileTime); 10535 10536 pkgSetting.pkg = pkg; 10537 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10538 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10539 pkgSetting.versionCode = pkg.getLongVersionCode(); 10540 } 10541 // Update volume if needed 10542 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10543 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10544 Slog.i(PackageManagerService.TAG, 10545 "Update" + (pkgSetting.isSystem() ? " system" : "") 10546 + " package " + pkg.packageName 10547 + " volume from " + pkgSetting.volumeUuid 10548 + " to " + volumeUuid); 10549 pkgSetting.volumeUuid = volumeUuid; 10550 } 10551 10552 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10553 } 10554 10555 /** 10556 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10557 */ 10558 private static boolean apkHasCode(String fileName) { 10559 StrictJarFile jarFile = null; 10560 try { 10561 jarFile = new StrictJarFile(fileName, 10562 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10563 return jarFile.findEntry("classes.dex") != null; 10564 } catch (IOException ignore) { 10565 } finally { 10566 try { 10567 if (jarFile != null) { 10568 jarFile.close(); 10569 } 10570 } catch (IOException ignore) {} 10571 } 10572 return false; 10573 } 10574 10575 /** 10576 * Enforces code policy for the package. This ensures that if an APK has 10577 * declared hasCode="true" in its manifest that the APK actually contains 10578 * code. 10579 * 10580 * @throws PackageManagerException If bytecode could not be found when it should exist 10581 */ 10582 private static void assertCodePolicy(PackageParser.Package pkg) 10583 throws PackageManagerException { 10584 final boolean shouldHaveCode = 10585 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10586 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10587 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10588 "Package " + pkg.baseCodePath + " code is missing"); 10589 } 10590 10591 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10592 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10593 final boolean splitShouldHaveCode = 10594 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10595 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10596 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10597 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10598 } 10599 } 10600 } 10601 } 10602 10603 /** 10604 * Applies policy to the parsed package based upon the given policy flags. 10605 * Ensures the package is in a good state. 10606 * <p> 10607 * Implementation detail: This method must NOT have any side effect. It would 10608 * ideally be static, but, it requires locks to read system state. 10609 */ 10610 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10611 final @ScanFlags int scanFlags) { 10612 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10613 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10614 if (pkg.applicationInfo.isDirectBootAware()) { 10615 // we're direct boot aware; set for all components 10616 for (PackageParser.Service s : pkg.services) { 10617 s.info.encryptionAware = s.info.directBootAware = true; 10618 } 10619 for (PackageParser.Provider p : pkg.providers) { 10620 p.info.encryptionAware = p.info.directBootAware = true; 10621 } 10622 for (PackageParser.Activity a : pkg.activities) { 10623 a.info.encryptionAware = a.info.directBootAware = true; 10624 } 10625 for (PackageParser.Activity r : pkg.receivers) { 10626 r.info.encryptionAware = r.info.directBootAware = true; 10627 } 10628 } 10629 if (compressedFileExists(pkg.codePath)) { 10630 pkg.isStub = true; 10631 } 10632 } else { 10633 // non system apps can't be flagged as core 10634 pkg.coreApp = false; 10635 // clear flags not applicable to regular apps 10636 pkg.applicationInfo.flags &= 10637 ~ApplicationInfo.FLAG_PERSISTENT; 10638 pkg.applicationInfo.privateFlags &= 10639 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10640 pkg.applicationInfo.privateFlags &= 10641 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10642 // cap permission priorities 10643 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10644 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10645 pkg.permissionGroups.get(i).info.priority = 0; 10646 } 10647 } 10648 } 10649 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10650 // clear protected broadcasts 10651 pkg.protectedBroadcasts = null; 10652 // ignore export request for single user receivers 10653 if (pkg.receivers != null) { 10654 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10655 final PackageParser.Activity receiver = pkg.receivers.get(i); 10656 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10657 receiver.info.exported = false; 10658 } 10659 } 10660 } 10661 // ignore export request for single user services 10662 if (pkg.services != null) { 10663 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10664 final PackageParser.Service service = pkg.services.get(i); 10665 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10666 service.info.exported = false; 10667 } 10668 } 10669 } 10670 // ignore export request for single user providers 10671 if (pkg.providers != null) { 10672 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10673 final PackageParser.Provider provider = pkg.providers.get(i); 10674 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10675 provider.info.exported = false; 10676 } 10677 } 10678 } 10679 } 10680 10681 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10682 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10683 } 10684 10685 if ((scanFlags & SCAN_AS_OEM) != 0) { 10686 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10687 } 10688 10689 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10690 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10691 } 10692 10693 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10694 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10695 } 10696 10697 if (!isSystemApp(pkg)) { 10698 // Only system apps can use these features. 10699 pkg.mOriginalPackages = null; 10700 pkg.mRealPackage = null; 10701 pkg.mAdoptPermissions = null; 10702 } 10703 } 10704 10705 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10706 throws PackageManagerException { 10707 if (object == null) { 10708 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10709 } 10710 return object; 10711 } 10712 10713 /** 10714 * Asserts the parsed package is valid according to the given policy. If the 10715 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10716 * <p> 10717 * Implementation detail: This method must NOT have any side effects. It would 10718 * ideally be static, but, it requires locks to read system state. 10719 * 10720 * @throws PackageManagerException If the package fails any of the validation checks 10721 */ 10722 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10723 final @ScanFlags int scanFlags) 10724 throws PackageManagerException { 10725 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10726 assertCodePolicy(pkg); 10727 } 10728 10729 if (pkg.applicationInfo.getCodePath() == null || 10730 pkg.applicationInfo.getResourcePath() == null) { 10731 // Bail out. The resource and code paths haven't been set. 10732 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10733 "Code and resource paths haven't been set correctly"); 10734 } 10735 10736 // Make sure we're not adding any bogus keyset info 10737 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10738 ksms.assertScannedPackageValid(pkg); 10739 10740 synchronized (mPackages) { 10741 // The special "android" package can only be defined once 10742 if (pkg.packageName.equals("android")) { 10743 if (mAndroidApplication != null) { 10744 Slog.w(TAG, "*************************************************"); 10745 Slog.w(TAG, "Core android package being redefined. Skipping."); 10746 Slog.w(TAG, " codePath=" + pkg.codePath); 10747 Slog.w(TAG, "*************************************************"); 10748 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10749 "Core android package being redefined. Skipping."); 10750 } 10751 } 10752 10753 // A package name must be unique; don't allow duplicates 10754 if (mPackages.containsKey(pkg.packageName)) { 10755 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10756 "Application package " + pkg.packageName 10757 + " already installed. Skipping duplicate."); 10758 } 10759 10760 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10761 // Static libs have a synthetic package name containing the version 10762 // but we still want the base name to be unique. 10763 if (mPackages.containsKey(pkg.manifestPackageName)) { 10764 throw new PackageManagerException( 10765 "Duplicate static shared lib provider package"); 10766 } 10767 10768 // Static shared libraries should have at least O target SDK 10769 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10770 throw new PackageManagerException( 10771 "Packages declaring static-shared libs must target O SDK or higher"); 10772 } 10773 10774 // Package declaring static a shared lib cannot be instant apps 10775 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10776 throw new PackageManagerException( 10777 "Packages declaring static-shared libs cannot be instant apps"); 10778 } 10779 10780 // Package declaring static a shared lib cannot be renamed since the package 10781 // name is synthetic and apps can't code around package manager internals. 10782 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10783 throw new PackageManagerException( 10784 "Packages declaring static-shared libs cannot be renamed"); 10785 } 10786 10787 // Package declaring static a shared lib cannot declare child packages 10788 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10789 throw new PackageManagerException( 10790 "Packages declaring static-shared libs cannot have child packages"); 10791 } 10792 10793 // Package declaring static a shared lib cannot declare dynamic libs 10794 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10795 throw new PackageManagerException( 10796 "Packages declaring static-shared libs cannot declare dynamic libs"); 10797 } 10798 10799 // Package declaring static a shared lib cannot declare shared users 10800 if (pkg.mSharedUserId != null) { 10801 throw new PackageManagerException( 10802 "Packages declaring static-shared libs cannot declare shared users"); 10803 } 10804 10805 // Static shared libs cannot declare activities 10806 if (!pkg.activities.isEmpty()) { 10807 throw new PackageManagerException( 10808 "Static shared libs cannot declare activities"); 10809 } 10810 10811 // Static shared libs cannot declare services 10812 if (!pkg.services.isEmpty()) { 10813 throw new PackageManagerException( 10814 "Static shared libs cannot declare services"); 10815 } 10816 10817 // Static shared libs cannot declare providers 10818 if (!pkg.providers.isEmpty()) { 10819 throw new PackageManagerException( 10820 "Static shared libs cannot declare content providers"); 10821 } 10822 10823 // Static shared libs cannot declare receivers 10824 if (!pkg.receivers.isEmpty()) { 10825 throw new PackageManagerException( 10826 "Static shared libs cannot declare broadcast receivers"); 10827 } 10828 10829 // Static shared libs cannot declare permission groups 10830 if (!pkg.permissionGroups.isEmpty()) { 10831 throw new PackageManagerException( 10832 "Static shared libs cannot declare permission groups"); 10833 } 10834 10835 // Static shared libs cannot declare permissions 10836 if (!pkg.permissions.isEmpty()) { 10837 throw new PackageManagerException( 10838 "Static shared libs cannot declare permissions"); 10839 } 10840 10841 // Static shared libs cannot declare protected broadcasts 10842 if (pkg.protectedBroadcasts != null) { 10843 throw new PackageManagerException( 10844 "Static shared libs cannot declare protected broadcasts"); 10845 } 10846 10847 // Static shared libs cannot be overlay targets 10848 if (pkg.mOverlayTarget != null) { 10849 throw new PackageManagerException( 10850 "Static shared libs cannot be overlay targets"); 10851 } 10852 10853 // The version codes must be ordered as lib versions 10854 long minVersionCode = Long.MIN_VALUE; 10855 long maxVersionCode = Long.MAX_VALUE; 10856 10857 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10858 pkg.staticSharedLibName); 10859 if (versionedLib != null) { 10860 final int versionCount = versionedLib.size(); 10861 for (int i = 0; i < versionCount; i++) { 10862 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10863 final long libVersionCode = libInfo.getDeclaringPackage() 10864 .getLongVersionCode(); 10865 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10866 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10867 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10868 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10869 } else { 10870 minVersionCode = maxVersionCode = libVersionCode; 10871 break; 10872 } 10873 } 10874 } 10875 if (pkg.getLongVersionCode() < minVersionCode 10876 || pkg.getLongVersionCode() > maxVersionCode) { 10877 throw new PackageManagerException("Static shared" 10878 + " lib version codes must be ordered as lib versions"); 10879 } 10880 } 10881 10882 // Only privileged apps and updated privileged apps can add child packages. 10883 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10884 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10885 throw new PackageManagerException("Only privileged apps can add child " 10886 + "packages. Ignoring package " + pkg.packageName); 10887 } 10888 final int childCount = pkg.childPackages.size(); 10889 for (int i = 0; i < childCount; i++) { 10890 PackageParser.Package childPkg = pkg.childPackages.get(i); 10891 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10892 childPkg.packageName)) { 10893 throw new PackageManagerException("Can't override child of " 10894 + "another disabled app. Ignoring package " + pkg.packageName); 10895 } 10896 } 10897 } 10898 10899 // If we're only installing presumed-existing packages, require that the 10900 // scanned APK is both already known and at the path previously established 10901 // for it. Previously unknown packages we pick up normally, but if we have an 10902 // a priori expectation about this package's install presence, enforce it. 10903 // With a singular exception for new system packages. When an OTA contains 10904 // a new system package, we allow the codepath to change from a system location 10905 // to the user-installed location. If we don't allow this change, any newer, 10906 // user-installed version of the application will be ignored. 10907 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10908 if (mExpectingBetter.containsKey(pkg.packageName)) { 10909 logCriticalInfo(Log.WARN, 10910 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10911 } else { 10912 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10913 if (known != null) { 10914 if (DEBUG_PACKAGE_SCANNING) { 10915 Log.d(TAG, "Examining " + pkg.codePath 10916 + " and requiring known paths " + known.codePathString 10917 + " & " + known.resourcePathString); 10918 } 10919 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10920 || !pkg.applicationInfo.getResourcePath().equals( 10921 known.resourcePathString)) { 10922 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10923 "Application package " + pkg.packageName 10924 + " found at " + pkg.applicationInfo.getCodePath() 10925 + " but expected at " + known.codePathString 10926 + "; ignoring."); 10927 } 10928 } else { 10929 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10930 "Application package " + pkg.packageName 10931 + " not found; ignoring."); 10932 } 10933 } 10934 } 10935 10936 // Verify that this new package doesn't have any content providers 10937 // that conflict with existing packages. Only do this if the 10938 // package isn't already installed, since we don't want to break 10939 // things that are installed. 10940 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10941 final int N = pkg.providers.size(); 10942 int i; 10943 for (i=0; i<N; i++) { 10944 PackageParser.Provider p = pkg.providers.get(i); 10945 if (p.info.authority != null) { 10946 String names[] = p.info.authority.split(";"); 10947 for (int j = 0; j < names.length; j++) { 10948 if (mProvidersByAuthority.containsKey(names[j])) { 10949 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10950 final String otherPackageName = 10951 ((other != null && other.getComponentName() != null) ? 10952 other.getComponentName().getPackageName() : "?"); 10953 throw new PackageManagerException( 10954 INSTALL_FAILED_CONFLICTING_PROVIDER, 10955 "Can't install because provider name " + names[j] 10956 + " (in package " + pkg.applicationInfo.packageName 10957 + ") is already used by " + otherPackageName); 10958 } 10959 } 10960 } 10961 } 10962 } 10963 10964 // Verify that packages sharing a user with a privileged app are marked as privileged. 10965 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 10966 SharedUserSetting sharedUserSetting = null; 10967 try { 10968 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10969 } catch (PackageManagerException ignore) {} 10970 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10971 // Exempt SharedUsers signed with the platform key. 10972 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10973 if ((platformPkgSetting.signatures.mSigningDetails 10974 != PackageParser.SigningDetails.UNKNOWN) 10975 && (compareSignatures( 10976 platformPkgSetting.signatures.mSigningDetails.signatures, 10977 pkg.mSigningDetails.signatures) 10978 != PackageManager.SIGNATURE_MATCH)) { 10979 throw new PackageManagerException("Apps that share a user with a " + 10980 "privileged app must themselves be marked as privileged. " + 10981 pkg.packageName + " shares privileged user " + 10982 pkg.mSharedUserId + "."); 10983 } 10984 } 10985 } 10986 10987 // Apply policies specific for runtime resource overlays (RROs). 10988 if (pkg.mOverlayTarget != null) { 10989 // System overlays have some restrictions on their use of the 'static' state. 10990 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10991 // We are scanning a system overlay. This can be the first scan of the 10992 // system/vendor/oem partition, or an update to the system overlay. 10993 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10994 // This must be an update to a system overlay. 10995 final PackageSetting previousPkg = assertNotNull( 10996 mSettings.getPackageLPr(pkg.packageName), 10997 "previous package state not present"); 10998 10999 // Static overlays cannot be updated. 11000 if (previousPkg.pkg.mOverlayIsStatic) { 11001 throw new PackageManagerException("Overlay " + pkg.packageName + 11002 " is static and cannot be upgraded."); 11003 // Non-static overlays cannot be converted to static overlays. 11004 } else if (pkg.mOverlayIsStatic) { 11005 throw new PackageManagerException("Overlay " + pkg.packageName + 11006 " cannot be upgraded into a static overlay."); 11007 } 11008 } 11009 } else { 11010 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11011 if (pkg.mOverlayIsStatic) { 11012 throw new PackageManagerException("Overlay " + pkg.packageName + 11013 " is static but not pre-installed."); 11014 } 11015 11016 // The only case where we allow installation of a non-system overlay is when 11017 // its signature is signed with the platform certificate. 11018 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11019 if ((platformPkgSetting.signatures.mSigningDetails 11020 != PackageParser.SigningDetails.UNKNOWN) 11021 && (compareSignatures( 11022 platformPkgSetting.signatures.mSigningDetails.signatures, 11023 pkg.mSigningDetails.signatures) 11024 != PackageManager.SIGNATURE_MATCH)) { 11025 throw new PackageManagerException("Overlay " + pkg.packageName + 11026 " must be signed with the platform certificate."); 11027 } 11028 } 11029 } 11030 } 11031 } 11032 11033 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11034 int type, String declaringPackageName, long declaringVersionCode) { 11035 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11036 if (versionedLib == null) { 11037 versionedLib = new LongSparseArray<>(); 11038 mSharedLibraries.put(name, versionedLib); 11039 if (type == SharedLibraryInfo.TYPE_STATIC) { 11040 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11041 } 11042 } else if (versionedLib.indexOfKey(version) >= 0) { 11043 return false; 11044 } 11045 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11046 version, type, declaringPackageName, declaringVersionCode); 11047 versionedLib.put(version, libEntry); 11048 return true; 11049 } 11050 11051 private boolean removeSharedLibraryLPw(String name, long version) { 11052 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11053 if (versionedLib == null) { 11054 return false; 11055 } 11056 final int libIdx = versionedLib.indexOfKey(version); 11057 if (libIdx < 0) { 11058 return false; 11059 } 11060 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11061 versionedLib.remove(version); 11062 if (versionedLib.size() <= 0) { 11063 mSharedLibraries.remove(name); 11064 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11065 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11066 .getPackageName()); 11067 } 11068 } 11069 return true; 11070 } 11071 11072 /** 11073 * Adds a scanned package to the system. When this method is finished, the package will 11074 * be available for query, resolution, etc... 11075 */ 11076 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11077 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11078 final String pkgName = pkg.packageName; 11079 if (mCustomResolverComponentName != null && 11080 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11081 setUpCustomResolverActivity(pkg); 11082 } 11083 11084 if (pkg.packageName.equals("android")) { 11085 synchronized (mPackages) { 11086 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11087 // Set up information for our fall-back user intent resolution activity. 11088 mPlatformPackage = pkg; 11089 pkg.mVersionCode = mSdkVersion; 11090 pkg.mVersionCodeMajor = 0; 11091 mAndroidApplication = pkg.applicationInfo; 11092 if (!mResolverReplaced) { 11093 mResolveActivity.applicationInfo = mAndroidApplication; 11094 mResolveActivity.name = ResolverActivity.class.getName(); 11095 mResolveActivity.packageName = mAndroidApplication.packageName; 11096 mResolveActivity.processName = "system:ui"; 11097 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11098 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11099 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11100 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11101 mResolveActivity.exported = true; 11102 mResolveActivity.enabled = true; 11103 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11104 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11105 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11106 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11107 | ActivityInfo.CONFIG_ORIENTATION 11108 | ActivityInfo.CONFIG_KEYBOARD 11109 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11110 mResolveInfo.activityInfo = mResolveActivity; 11111 mResolveInfo.priority = 0; 11112 mResolveInfo.preferredOrder = 0; 11113 mResolveInfo.match = 0; 11114 mResolveComponentName = new ComponentName( 11115 mAndroidApplication.packageName, mResolveActivity.name); 11116 } 11117 } 11118 } 11119 } 11120 11121 ArrayList<PackageParser.Package> clientLibPkgs = null; 11122 // writer 11123 synchronized (mPackages) { 11124 boolean hasStaticSharedLibs = false; 11125 11126 // Any app can add new static shared libraries 11127 if (pkg.staticSharedLibName != null) { 11128 // Static shared libs don't allow renaming as they have synthetic package 11129 // names to allow install of multiple versions, so use name from manifest. 11130 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11131 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11132 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11133 hasStaticSharedLibs = true; 11134 } else { 11135 Slog.w(TAG, "Package " + pkg.packageName + " library " 11136 + pkg.staticSharedLibName + " already exists; skipping"); 11137 } 11138 // Static shared libs cannot be updated once installed since they 11139 // use synthetic package name which includes the version code, so 11140 // not need to update other packages's shared lib dependencies. 11141 } 11142 11143 if (!hasStaticSharedLibs 11144 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11145 // Only system apps can add new dynamic shared libraries. 11146 if (pkg.libraryNames != null) { 11147 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11148 String name = pkg.libraryNames.get(i); 11149 boolean allowed = false; 11150 if (pkg.isUpdatedSystemApp()) { 11151 // New library entries can only be added through the 11152 // system image. This is important to get rid of a lot 11153 // of nasty edge cases: for example if we allowed a non- 11154 // system update of the app to add a library, then uninstalling 11155 // the update would make the library go away, and assumptions 11156 // we made such as through app install filtering would now 11157 // have allowed apps on the device which aren't compatible 11158 // with it. Better to just have the restriction here, be 11159 // conservative, and create many fewer cases that can negatively 11160 // impact the user experience. 11161 final PackageSetting sysPs = mSettings 11162 .getDisabledSystemPkgLPr(pkg.packageName); 11163 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11164 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11165 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11166 allowed = true; 11167 break; 11168 } 11169 } 11170 } 11171 } else { 11172 allowed = true; 11173 } 11174 if (allowed) { 11175 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11176 SharedLibraryInfo.VERSION_UNDEFINED, 11177 SharedLibraryInfo.TYPE_DYNAMIC, 11178 pkg.packageName, pkg.getLongVersionCode())) { 11179 Slog.w(TAG, "Package " + pkg.packageName + " library " 11180 + name + " already exists; skipping"); 11181 } 11182 } else { 11183 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11184 + name + " that is not declared on system image; skipping"); 11185 } 11186 } 11187 11188 if ((scanFlags & SCAN_BOOTING) == 0) { 11189 // If we are not booting, we need to update any applications 11190 // that are clients of our shared library. If we are booting, 11191 // this will all be done once the scan is complete. 11192 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11193 } 11194 } 11195 } 11196 } 11197 11198 if ((scanFlags & SCAN_BOOTING) != 0) { 11199 // No apps can run during boot scan, so they don't need to be frozen 11200 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11201 // Caller asked to not kill app, so it's probably not frozen 11202 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11203 // Caller asked us to ignore frozen check for some reason; they 11204 // probably didn't know the package name 11205 } else { 11206 // We're doing major surgery on this package, so it better be frozen 11207 // right now to keep it from launching 11208 checkPackageFrozen(pkgName); 11209 } 11210 11211 // Also need to kill any apps that are dependent on the library. 11212 if (clientLibPkgs != null) { 11213 for (int i=0; i<clientLibPkgs.size(); i++) { 11214 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11215 killApplication(clientPkg.applicationInfo.packageName, 11216 clientPkg.applicationInfo.uid, "update lib"); 11217 } 11218 } 11219 11220 // writer 11221 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11222 11223 synchronized (mPackages) { 11224 // We don't expect installation to fail beyond this point 11225 11226 // Add the new setting to mSettings 11227 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11228 // Add the new setting to mPackages 11229 mPackages.put(pkg.applicationInfo.packageName, pkg); 11230 // Make sure we don't accidentally delete its data. 11231 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11232 while (iter.hasNext()) { 11233 PackageCleanItem item = iter.next(); 11234 if (pkgName.equals(item.packageName)) { 11235 iter.remove(); 11236 } 11237 } 11238 11239 // Add the package's KeySets to the global KeySetManagerService 11240 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11241 ksms.addScannedPackageLPw(pkg); 11242 11243 int N = pkg.providers.size(); 11244 StringBuilder r = null; 11245 int i; 11246 for (i=0; i<N; i++) { 11247 PackageParser.Provider p = pkg.providers.get(i); 11248 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11249 p.info.processName); 11250 mProviders.addProvider(p); 11251 p.syncable = p.info.isSyncable; 11252 if (p.info.authority != null) { 11253 String names[] = p.info.authority.split(";"); 11254 p.info.authority = null; 11255 for (int j = 0; j < names.length; j++) { 11256 if (j == 1 && p.syncable) { 11257 // We only want the first authority for a provider to possibly be 11258 // syncable, so if we already added this provider using a different 11259 // authority clear the syncable flag. We copy the provider before 11260 // changing it because the mProviders object contains a reference 11261 // to a provider that we don't want to change. 11262 // Only do this for the second authority since the resulting provider 11263 // object can be the same for all future authorities for this provider. 11264 p = new PackageParser.Provider(p); 11265 p.syncable = false; 11266 } 11267 if (!mProvidersByAuthority.containsKey(names[j])) { 11268 mProvidersByAuthority.put(names[j], p); 11269 if (p.info.authority == null) { 11270 p.info.authority = names[j]; 11271 } else { 11272 p.info.authority = p.info.authority + ";" + names[j]; 11273 } 11274 if (DEBUG_PACKAGE_SCANNING) { 11275 if (chatty) 11276 Log.d(TAG, "Registered content provider: " + names[j] 11277 + ", className = " + p.info.name + ", isSyncable = " 11278 + p.info.isSyncable); 11279 } 11280 } else { 11281 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11282 Slog.w(TAG, "Skipping provider name " + names[j] + 11283 " (in package " + pkg.applicationInfo.packageName + 11284 "): name already used by " 11285 + ((other != null && other.getComponentName() != null) 11286 ? other.getComponentName().getPackageName() : "?")); 11287 } 11288 } 11289 } 11290 if (chatty) { 11291 if (r == null) { 11292 r = new StringBuilder(256); 11293 } else { 11294 r.append(' '); 11295 } 11296 r.append(p.info.name); 11297 } 11298 } 11299 if (r != null) { 11300 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11301 } 11302 11303 N = pkg.services.size(); 11304 r = null; 11305 for (i=0; i<N; i++) { 11306 PackageParser.Service s = pkg.services.get(i); 11307 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11308 s.info.processName); 11309 mServices.addService(s); 11310 if (chatty) { 11311 if (r == null) { 11312 r = new StringBuilder(256); 11313 } else { 11314 r.append(' '); 11315 } 11316 r.append(s.info.name); 11317 } 11318 } 11319 if (r != null) { 11320 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11321 } 11322 11323 N = pkg.receivers.size(); 11324 r = null; 11325 for (i=0; i<N; i++) { 11326 PackageParser.Activity a = pkg.receivers.get(i); 11327 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11328 a.info.processName); 11329 mReceivers.addActivity(a, "receiver"); 11330 if (chatty) { 11331 if (r == null) { 11332 r = new StringBuilder(256); 11333 } else { 11334 r.append(' '); 11335 } 11336 r.append(a.info.name); 11337 } 11338 } 11339 if (r != null) { 11340 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11341 } 11342 11343 N = pkg.activities.size(); 11344 r = null; 11345 for (i=0; i<N; i++) { 11346 PackageParser.Activity a = pkg.activities.get(i); 11347 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11348 a.info.processName); 11349 mActivities.addActivity(a, "activity"); 11350 if (chatty) { 11351 if (r == null) { 11352 r = new StringBuilder(256); 11353 } else { 11354 r.append(' '); 11355 } 11356 r.append(a.info.name); 11357 } 11358 } 11359 if (r != null) { 11360 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11361 } 11362 11363 // Don't allow ephemeral applications to define new permissions groups. 11364 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11365 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11366 + " ignored: instant apps cannot define new permission groups."); 11367 } else { 11368 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11369 } 11370 11371 // Don't allow ephemeral applications to define new permissions. 11372 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11373 Slog.w(TAG, "Permissions from package " + pkg.packageName 11374 + " ignored: instant apps cannot define new permissions."); 11375 } else { 11376 mPermissionManager.addAllPermissions(pkg, chatty); 11377 } 11378 11379 N = pkg.instrumentation.size(); 11380 r = null; 11381 for (i=0; i<N; i++) { 11382 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11383 a.info.packageName = pkg.applicationInfo.packageName; 11384 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11385 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11386 a.info.splitNames = pkg.splitNames; 11387 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11388 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11389 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11390 a.info.dataDir = pkg.applicationInfo.dataDir; 11391 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11392 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11393 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11394 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11395 mInstrumentation.put(a.getComponentName(), a); 11396 if (chatty) { 11397 if (r == null) { 11398 r = new StringBuilder(256); 11399 } else { 11400 r.append(' '); 11401 } 11402 r.append(a.info.name); 11403 } 11404 } 11405 if (r != null) { 11406 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11407 } 11408 11409 if (pkg.protectedBroadcasts != null) { 11410 N = pkg.protectedBroadcasts.size(); 11411 synchronized (mProtectedBroadcasts) { 11412 for (i = 0; i < N; i++) { 11413 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11414 } 11415 } 11416 } 11417 } 11418 11419 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11420 } 11421 11422 /** 11423 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11424 * is derived purely on the basis of the contents of {@code scanFile} and 11425 * {@code cpuAbiOverride}. 11426 * 11427 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11428 */ 11429 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11430 boolean extractLibs) 11431 throws PackageManagerException { 11432 // Give ourselves some initial paths; we'll come back for another 11433 // pass once we've determined ABI below. 11434 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11435 11436 // We would never need to extract libs for forward-locked and external packages, 11437 // since the container service will do it for us. We shouldn't attempt to 11438 // extract libs from system app when it was not updated. 11439 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11440 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11441 extractLibs = false; 11442 } 11443 11444 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11445 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11446 11447 NativeLibraryHelper.Handle handle = null; 11448 try { 11449 handle = NativeLibraryHelper.Handle.create(pkg); 11450 // TODO(multiArch): This can be null for apps that didn't go through the 11451 // usual installation process. We can calculate it again, like we 11452 // do during install time. 11453 // 11454 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11455 // unnecessary. 11456 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11457 11458 // Null out the abis so that they can be recalculated. 11459 pkg.applicationInfo.primaryCpuAbi = null; 11460 pkg.applicationInfo.secondaryCpuAbi = null; 11461 if (isMultiArch(pkg.applicationInfo)) { 11462 // Warn if we've set an abiOverride for multi-lib packages.. 11463 // By definition, we need to copy both 32 and 64 bit libraries for 11464 // such packages. 11465 if (pkg.cpuAbiOverride != null 11466 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11467 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11468 } 11469 11470 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11471 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11472 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11473 if (extractLibs) { 11474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11475 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11476 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11477 useIsaSpecificSubdirs); 11478 } else { 11479 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11480 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11481 } 11482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11483 } 11484 11485 // Shared library native code should be in the APK zip aligned 11486 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11487 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11488 "Shared library native lib extraction not supported"); 11489 } 11490 11491 maybeThrowExceptionForMultiArchCopy( 11492 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11493 11494 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11495 if (extractLibs) { 11496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11497 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11498 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11499 useIsaSpecificSubdirs); 11500 } else { 11501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11502 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11503 } 11504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11505 } 11506 11507 maybeThrowExceptionForMultiArchCopy( 11508 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11509 11510 if (abi64 >= 0) { 11511 // Shared library native libs should be in the APK zip aligned 11512 if (extractLibs && pkg.isLibrary()) { 11513 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11514 "Shared library native lib extraction not supported"); 11515 } 11516 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11517 } 11518 11519 if (abi32 >= 0) { 11520 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11521 if (abi64 >= 0) { 11522 if (pkg.use32bitAbi) { 11523 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11524 pkg.applicationInfo.primaryCpuAbi = abi; 11525 } else { 11526 pkg.applicationInfo.secondaryCpuAbi = abi; 11527 } 11528 } else { 11529 pkg.applicationInfo.primaryCpuAbi = abi; 11530 } 11531 } 11532 } else { 11533 String[] abiList = (cpuAbiOverride != null) ? 11534 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11535 11536 // Enable gross and lame hacks for apps that are built with old 11537 // SDK tools. We must scan their APKs for renderscript bitcode and 11538 // not launch them if it's present. Don't bother checking on devices 11539 // that don't have 64 bit support. 11540 boolean needsRenderScriptOverride = false; 11541 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11542 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11543 abiList = Build.SUPPORTED_32_BIT_ABIS; 11544 needsRenderScriptOverride = true; 11545 } 11546 11547 final int copyRet; 11548 if (extractLibs) { 11549 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11550 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11551 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11552 } else { 11553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11554 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11555 } 11556 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11557 11558 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11559 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11560 "Error unpackaging native libs for app, errorCode=" + copyRet); 11561 } 11562 11563 if (copyRet >= 0) { 11564 // Shared libraries that have native libs must be multi-architecture 11565 if (pkg.isLibrary()) { 11566 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11567 "Shared library with native libs must be multiarch"); 11568 } 11569 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11570 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11571 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11572 } else if (needsRenderScriptOverride) { 11573 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11574 } 11575 } 11576 } catch (IOException ioe) { 11577 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11578 } finally { 11579 IoUtils.closeQuietly(handle); 11580 } 11581 11582 // Now that we've calculated the ABIs and determined if it's an internal app, 11583 // we will go ahead and populate the nativeLibraryPath. 11584 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11585 } 11586 11587 /** 11588 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11589 * i.e, so that all packages can be run inside a single process if required. 11590 * 11591 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11592 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11593 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11594 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11595 * updating a package that belongs to a shared user. 11596 * 11597 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11598 * adds unnecessary complexity. 11599 */ 11600 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11601 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11602 List<String> changedAbiCodePath = null; 11603 String requiredInstructionSet = null; 11604 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11605 requiredInstructionSet = VMRuntime.getInstructionSet( 11606 scannedPackage.applicationInfo.primaryCpuAbi); 11607 } 11608 11609 PackageSetting requirer = null; 11610 for (PackageSetting ps : packagesForUser) { 11611 // If packagesForUser contains scannedPackage, we skip it. This will happen 11612 // when scannedPackage is an update of an existing package. Without this check, 11613 // we will never be able to change the ABI of any package belonging to a shared 11614 // user, even if it's compatible with other packages. 11615 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11616 if (ps.primaryCpuAbiString == null) { 11617 continue; 11618 } 11619 11620 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11621 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11622 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11623 // this but there's not much we can do. 11624 String errorMessage = "Instruction set mismatch, " 11625 + ((requirer == null) ? "[caller]" : requirer) 11626 + " requires " + requiredInstructionSet + " whereas " + ps 11627 + " requires " + instructionSet; 11628 Slog.w(TAG, errorMessage); 11629 } 11630 11631 if (requiredInstructionSet == null) { 11632 requiredInstructionSet = instructionSet; 11633 requirer = ps; 11634 } 11635 } 11636 } 11637 11638 if (requiredInstructionSet != null) { 11639 String adjustedAbi; 11640 if (requirer != null) { 11641 // requirer != null implies that either scannedPackage was null or that scannedPackage 11642 // did not require an ABI, in which case we have to adjust scannedPackage to match 11643 // the ABI of the set (which is the same as requirer's ABI) 11644 adjustedAbi = requirer.primaryCpuAbiString; 11645 if (scannedPackage != null) { 11646 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11647 } 11648 } else { 11649 // requirer == null implies that we're updating all ABIs in the set to 11650 // match scannedPackage. 11651 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11652 } 11653 11654 for (PackageSetting ps : packagesForUser) { 11655 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11656 if (ps.primaryCpuAbiString != null) { 11657 continue; 11658 } 11659 11660 ps.primaryCpuAbiString = adjustedAbi; 11661 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11662 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11663 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11664 if (DEBUG_ABI_SELECTION) { 11665 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11666 + " (requirer=" 11667 + (requirer != null ? requirer.pkg : "null") 11668 + ", scannedPackage=" 11669 + (scannedPackage != null ? scannedPackage : "null") 11670 + ")"); 11671 } 11672 if (changedAbiCodePath == null) { 11673 changedAbiCodePath = new ArrayList<>(); 11674 } 11675 changedAbiCodePath.add(ps.codePathString); 11676 } 11677 } 11678 } 11679 } 11680 return changedAbiCodePath; 11681 } 11682 11683 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11684 synchronized (mPackages) { 11685 mResolverReplaced = true; 11686 // Set up information for custom user intent resolution activity. 11687 mResolveActivity.applicationInfo = pkg.applicationInfo; 11688 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11689 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11690 mResolveActivity.processName = pkg.applicationInfo.packageName; 11691 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11692 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11693 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11694 mResolveActivity.theme = 0; 11695 mResolveActivity.exported = true; 11696 mResolveActivity.enabled = true; 11697 mResolveInfo.activityInfo = mResolveActivity; 11698 mResolveInfo.priority = 0; 11699 mResolveInfo.preferredOrder = 0; 11700 mResolveInfo.match = 0; 11701 mResolveComponentName = mCustomResolverComponentName; 11702 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11703 mResolveComponentName); 11704 } 11705 } 11706 11707 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11708 if (installerActivity == null) { 11709 if (DEBUG_INSTANT) { 11710 Slog.d(TAG, "Clear ephemeral installer activity"); 11711 } 11712 mInstantAppInstallerActivity = null; 11713 return; 11714 } 11715 11716 if (DEBUG_INSTANT) { 11717 Slog.d(TAG, "Set ephemeral installer activity: " 11718 + installerActivity.getComponentName()); 11719 } 11720 // Set up information for ephemeral installer activity 11721 mInstantAppInstallerActivity = installerActivity; 11722 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11723 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11724 mInstantAppInstallerActivity.exported = true; 11725 mInstantAppInstallerActivity.enabled = true; 11726 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11727 mInstantAppInstallerInfo.priority = 1; 11728 mInstantAppInstallerInfo.preferredOrder = 1; 11729 mInstantAppInstallerInfo.isDefault = true; 11730 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11731 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11732 } 11733 11734 private static String calculateBundledApkRoot(final String codePathString) { 11735 final File codePath = new File(codePathString); 11736 final File codeRoot; 11737 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11738 codeRoot = Environment.getRootDirectory(); 11739 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11740 codeRoot = Environment.getOemDirectory(); 11741 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11742 codeRoot = Environment.getVendorDirectory(); 11743 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11744 codeRoot = Environment.getProductDirectory(); 11745 } else { 11746 // Unrecognized code path; take its top real segment as the apk root: 11747 // e.g. /something/app/blah.apk => /something 11748 try { 11749 File f = codePath.getCanonicalFile(); 11750 File parent = f.getParentFile(); // non-null because codePath is a file 11751 File tmp; 11752 while ((tmp = parent.getParentFile()) != null) { 11753 f = parent; 11754 parent = tmp; 11755 } 11756 codeRoot = f; 11757 Slog.w(TAG, "Unrecognized code path " 11758 + codePath + " - using " + codeRoot); 11759 } catch (IOException e) { 11760 // Can't canonicalize the code path -- shenanigans? 11761 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11762 return Environment.getRootDirectory().getPath(); 11763 } 11764 } 11765 return codeRoot.getPath(); 11766 } 11767 11768 /** 11769 * Derive and set the location of native libraries for the given package, 11770 * which varies depending on where and how the package was installed. 11771 */ 11772 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11773 final ApplicationInfo info = pkg.applicationInfo; 11774 final String codePath = pkg.codePath; 11775 final File codeFile = new File(codePath); 11776 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11777 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11778 11779 info.nativeLibraryRootDir = null; 11780 info.nativeLibraryRootRequiresIsa = false; 11781 info.nativeLibraryDir = null; 11782 info.secondaryNativeLibraryDir = null; 11783 11784 if (isApkFile(codeFile)) { 11785 // Monolithic install 11786 if (bundledApp) { 11787 // If "/system/lib64/apkname" exists, assume that is the per-package 11788 // native library directory to use; otherwise use "/system/lib/apkname". 11789 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11790 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11791 getPrimaryInstructionSet(info)); 11792 11793 // This is a bundled system app so choose the path based on the ABI. 11794 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11795 // is just the default path. 11796 final String apkName = deriveCodePathName(codePath); 11797 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11798 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11799 apkName).getAbsolutePath(); 11800 11801 if (info.secondaryCpuAbi != null) { 11802 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11803 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11804 secondaryLibDir, apkName).getAbsolutePath(); 11805 } 11806 } else if (asecApp) { 11807 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11808 .getAbsolutePath(); 11809 } else { 11810 final String apkName = deriveCodePathName(codePath); 11811 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11812 .getAbsolutePath(); 11813 } 11814 11815 info.nativeLibraryRootRequiresIsa = false; 11816 info.nativeLibraryDir = info.nativeLibraryRootDir; 11817 } else { 11818 // Cluster install 11819 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11820 info.nativeLibraryRootRequiresIsa = true; 11821 11822 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11823 getPrimaryInstructionSet(info)).getAbsolutePath(); 11824 11825 if (info.secondaryCpuAbi != null) { 11826 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11827 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11828 } 11829 } 11830 } 11831 11832 /** 11833 * Calculate the abis and roots for a bundled app. These can uniquely 11834 * be determined from the contents of the system partition, i.e whether 11835 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11836 * of this information, and instead assume that the system was built 11837 * sensibly. 11838 */ 11839 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11840 PackageSetting pkgSetting) { 11841 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11842 11843 // If "/system/lib64/apkname" exists, assume that is the per-package 11844 // native library directory to use; otherwise use "/system/lib/apkname". 11845 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11846 setBundledAppAbi(pkg, apkRoot, apkName); 11847 // pkgSetting might be null during rescan following uninstall of updates 11848 // to a bundled app, so accommodate that possibility. The settings in 11849 // that case will be established later from the parsed package. 11850 // 11851 // If the settings aren't null, sync them up with what we've just derived. 11852 // note that apkRoot isn't stored in the package settings. 11853 if (pkgSetting != null) { 11854 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11855 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11856 } 11857 } 11858 11859 /** 11860 * Deduces the ABI of a bundled app and sets the relevant fields on the 11861 * parsed pkg object. 11862 * 11863 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11864 * under which system libraries are installed. 11865 * @param apkName the name of the installed package. 11866 */ 11867 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11868 final File codeFile = new File(pkg.codePath); 11869 11870 final boolean has64BitLibs; 11871 final boolean has32BitLibs; 11872 if (isApkFile(codeFile)) { 11873 // Monolithic install 11874 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11875 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11876 } else { 11877 // Cluster install 11878 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11879 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11880 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11881 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11882 has64BitLibs = (new File(rootDir, isa)).exists(); 11883 } else { 11884 has64BitLibs = false; 11885 } 11886 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11887 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11888 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11889 has32BitLibs = (new File(rootDir, isa)).exists(); 11890 } else { 11891 has32BitLibs = false; 11892 } 11893 } 11894 11895 if (has64BitLibs && !has32BitLibs) { 11896 // The package has 64 bit libs, but not 32 bit libs. Its primary 11897 // ABI should be 64 bit. We can safely assume here that the bundled 11898 // native libraries correspond to the most preferred ABI in the list. 11899 11900 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11901 pkg.applicationInfo.secondaryCpuAbi = null; 11902 } else if (has32BitLibs && !has64BitLibs) { 11903 // The package has 32 bit libs but not 64 bit libs. Its primary 11904 // ABI should be 32 bit. 11905 11906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11907 pkg.applicationInfo.secondaryCpuAbi = null; 11908 } else if (has32BitLibs && has64BitLibs) { 11909 // The application has both 64 and 32 bit bundled libraries. We check 11910 // here that the app declares multiArch support, and warn if it doesn't. 11911 // 11912 // We will be lenient here and record both ABIs. The primary will be the 11913 // ABI that's higher on the list, i.e, a device that's configured to prefer 11914 // 64 bit apps will see a 64 bit primary ABI, 11915 11916 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11917 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11918 } 11919 11920 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11921 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11922 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11923 } else { 11924 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11925 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11926 } 11927 } else { 11928 pkg.applicationInfo.primaryCpuAbi = null; 11929 pkg.applicationInfo.secondaryCpuAbi = null; 11930 } 11931 } 11932 11933 private void killApplication(String pkgName, int appId, String reason) { 11934 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11935 } 11936 11937 private void killApplication(String pkgName, int appId, int userId, String reason) { 11938 // Request the ActivityManager to kill the process(only for existing packages) 11939 // so that we do not end up in a confused state while the user is still using the older 11940 // version of the application while the new one gets installed. 11941 final long token = Binder.clearCallingIdentity(); 11942 try { 11943 IActivityManager am = ActivityManager.getService(); 11944 if (am != null) { 11945 try { 11946 am.killApplication(pkgName, appId, userId, reason); 11947 } catch (RemoteException e) { 11948 } 11949 } 11950 } finally { 11951 Binder.restoreCallingIdentity(token); 11952 } 11953 } 11954 11955 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11956 // Remove the parent package setting 11957 PackageSetting ps = (PackageSetting) pkg.mExtras; 11958 if (ps != null) { 11959 removePackageLI(ps, chatty); 11960 } 11961 // Remove the child package setting 11962 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11963 for (int i = 0; i < childCount; i++) { 11964 PackageParser.Package childPkg = pkg.childPackages.get(i); 11965 ps = (PackageSetting) childPkg.mExtras; 11966 if (ps != null) { 11967 removePackageLI(ps, chatty); 11968 } 11969 } 11970 } 11971 11972 void removePackageLI(PackageSetting ps, boolean chatty) { 11973 if (DEBUG_INSTALL) { 11974 if (chatty) 11975 Log.d(TAG, "Removing package " + ps.name); 11976 } 11977 11978 // writer 11979 synchronized (mPackages) { 11980 mPackages.remove(ps.name); 11981 final PackageParser.Package pkg = ps.pkg; 11982 if (pkg != null) { 11983 cleanPackageDataStructuresLILPw(pkg, chatty); 11984 } 11985 } 11986 } 11987 11988 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11989 if (DEBUG_INSTALL) { 11990 if (chatty) 11991 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11992 } 11993 11994 // writer 11995 synchronized (mPackages) { 11996 // Remove the parent package 11997 mPackages.remove(pkg.applicationInfo.packageName); 11998 cleanPackageDataStructuresLILPw(pkg, chatty); 11999 12000 // Remove the child packages 12001 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12002 for (int i = 0; i < childCount; i++) { 12003 PackageParser.Package childPkg = pkg.childPackages.get(i); 12004 mPackages.remove(childPkg.applicationInfo.packageName); 12005 cleanPackageDataStructuresLILPw(childPkg, chatty); 12006 } 12007 } 12008 } 12009 12010 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12011 int N = pkg.providers.size(); 12012 StringBuilder r = null; 12013 int i; 12014 for (i=0; i<N; i++) { 12015 PackageParser.Provider p = pkg.providers.get(i); 12016 mProviders.removeProvider(p); 12017 if (p.info.authority == null) { 12018 12019 /* There was another ContentProvider with this authority when 12020 * this app was installed so this authority is null, 12021 * Ignore it as we don't have to unregister the provider. 12022 */ 12023 continue; 12024 } 12025 String names[] = p.info.authority.split(";"); 12026 for (int j = 0; j < names.length; j++) { 12027 if (mProvidersByAuthority.get(names[j]) == p) { 12028 mProvidersByAuthority.remove(names[j]); 12029 if (DEBUG_REMOVE) { 12030 if (chatty) 12031 Log.d(TAG, "Unregistered content provider: " + names[j] 12032 + ", className = " + p.info.name + ", isSyncable = " 12033 + p.info.isSyncable); 12034 } 12035 } 12036 } 12037 if (DEBUG_REMOVE && chatty) { 12038 if (r == null) { 12039 r = new StringBuilder(256); 12040 } else { 12041 r.append(' '); 12042 } 12043 r.append(p.info.name); 12044 } 12045 } 12046 if (r != null) { 12047 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12048 } 12049 12050 N = pkg.services.size(); 12051 r = null; 12052 for (i=0; i<N; i++) { 12053 PackageParser.Service s = pkg.services.get(i); 12054 mServices.removeService(s); 12055 if (chatty) { 12056 if (r == null) { 12057 r = new StringBuilder(256); 12058 } else { 12059 r.append(' '); 12060 } 12061 r.append(s.info.name); 12062 } 12063 } 12064 if (r != null) { 12065 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12066 } 12067 12068 N = pkg.receivers.size(); 12069 r = null; 12070 for (i=0; i<N; i++) { 12071 PackageParser.Activity a = pkg.receivers.get(i); 12072 mReceivers.removeActivity(a, "receiver"); 12073 if (DEBUG_REMOVE && chatty) { 12074 if (r == null) { 12075 r = new StringBuilder(256); 12076 } else { 12077 r.append(' '); 12078 } 12079 r.append(a.info.name); 12080 } 12081 } 12082 if (r != null) { 12083 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12084 } 12085 12086 N = pkg.activities.size(); 12087 r = null; 12088 for (i=0; i<N; i++) { 12089 PackageParser.Activity a = pkg.activities.get(i); 12090 mActivities.removeActivity(a, "activity"); 12091 if (DEBUG_REMOVE && chatty) { 12092 if (r == null) { 12093 r = new StringBuilder(256); 12094 } else { 12095 r.append(' '); 12096 } 12097 r.append(a.info.name); 12098 } 12099 } 12100 if (r != null) { 12101 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12102 } 12103 12104 mPermissionManager.removeAllPermissions(pkg, chatty); 12105 12106 N = pkg.instrumentation.size(); 12107 r = null; 12108 for (i=0; i<N; i++) { 12109 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12110 mInstrumentation.remove(a.getComponentName()); 12111 if (DEBUG_REMOVE && chatty) { 12112 if (r == null) { 12113 r = new StringBuilder(256); 12114 } else { 12115 r.append(' '); 12116 } 12117 r.append(a.info.name); 12118 } 12119 } 12120 if (r != null) { 12121 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12122 } 12123 12124 r = null; 12125 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12126 // Only system apps can hold shared libraries. 12127 if (pkg.libraryNames != null) { 12128 for (i = 0; i < pkg.libraryNames.size(); i++) { 12129 String name = pkg.libraryNames.get(i); 12130 if (removeSharedLibraryLPw(name, 0)) { 12131 if (DEBUG_REMOVE && chatty) { 12132 if (r == null) { 12133 r = new StringBuilder(256); 12134 } else { 12135 r.append(' '); 12136 } 12137 r.append(name); 12138 } 12139 } 12140 } 12141 } 12142 } 12143 12144 r = null; 12145 12146 // Any package can hold static shared libraries. 12147 if (pkg.staticSharedLibName != null) { 12148 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12149 if (DEBUG_REMOVE && chatty) { 12150 if (r == null) { 12151 r = new StringBuilder(256); 12152 } else { 12153 r.append(' '); 12154 } 12155 r.append(pkg.staticSharedLibName); 12156 } 12157 } 12158 } 12159 12160 if (r != null) { 12161 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12162 } 12163 } 12164 12165 12166 final class ActivityIntentResolver 12167 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12168 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12169 boolean defaultOnly, int userId) { 12170 if (!sUserManager.exists(userId)) return null; 12171 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12172 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12173 } 12174 12175 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12176 int userId) { 12177 if (!sUserManager.exists(userId)) return null; 12178 mFlags = flags; 12179 return super.queryIntent(intent, resolvedType, 12180 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12181 userId); 12182 } 12183 12184 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12185 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12186 if (!sUserManager.exists(userId)) return null; 12187 if (packageActivities == null) { 12188 return null; 12189 } 12190 mFlags = flags; 12191 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12192 final int N = packageActivities.size(); 12193 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12194 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12195 12196 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12197 for (int i = 0; i < N; ++i) { 12198 intentFilters = packageActivities.get(i).intents; 12199 if (intentFilters != null && intentFilters.size() > 0) { 12200 PackageParser.ActivityIntentInfo[] array = 12201 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12202 intentFilters.toArray(array); 12203 listCut.add(array); 12204 } 12205 } 12206 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12207 } 12208 12209 /** 12210 * Finds a privileged activity that matches the specified activity names. 12211 */ 12212 private PackageParser.Activity findMatchingActivity( 12213 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12214 for (PackageParser.Activity sysActivity : activityList) { 12215 if (sysActivity.info.name.equals(activityInfo.name)) { 12216 return sysActivity; 12217 } 12218 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12219 return sysActivity; 12220 } 12221 if (sysActivity.info.targetActivity != null) { 12222 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12223 return sysActivity; 12224 } 12225 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12226 return sysActivity; 12227 } 12228 } 12229 } 12230 return null; 12231 } 12232 12233 public class IterGenerator<E> { 12234 public Iterator<E> generate(ActivityIntentInfo info) { 12235 return null; 12236 } 12237 } 12238 12239 public class ActionIterGenerator extends IterGenerator<String> { 12240 @Override 12241 public Iterator<String> generate(ActivityIntentInfo info) { 12242 return info.actionsIterator(); 12243 } 12244 } 12245 12246 public class CategoriesIterGenerator extends IterGenerator<String> { 12247 @Override 12248 public Iterator<String> generate(ActivityIntentInfo info) { 12249 return info.categoriesIterator(); 12250 } 12251 } 12252 12253 public class SchemesIterGenerator extends IterGenerator<String> { 12254 @Override 12255 public Iterator<String> generate(ActivityIntentInfo info) { 12256 return info.schemesIterator(); 12257 } 12258 } 12259 12260 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12261 @Override 12262 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12263 return info.authoritiesIterator(); 12264 } 12265 } 12266 12267 /** 12268 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12269 * MODIFIED. Do not pass in a list that should not be changed. 12270 */ 12271 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12272 IterGenerator<T> generator, Iterator<T> searchIterator) { 12273 // loop through the set of actions; every one must be found in the intent filter 12274 while (searchIterator.hasNext()) { 12275 // we must have at least one filter in the list to consider a match 12276 if (intentList.size() == 0) { 12277 break; 12278 } 12279 12280 final T searchAction = searchIterator.next(); 12281 12282 // loop through the set of intent filters 12283 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12284 while (intentIter.hasNext()) { 12285 final ActivityIntentInfo intentInfo = intentIter.next(); 12286 boolean selectionFound = false; 12287 12288 // loop through the intent filter's selection criteria; at least one 12289 // of them must match the searched criteria 12290 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12291 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12292 final T intentSelection = intentSelectionIter.next(); 12293 if (intentSelection != null && intentSelection.equals(searchAction)) { 12294 selectionFound = true; 12295 break; 12296 } 12297 } 12298 12299 // the selection criteria wasn't found in this filter's set; this filter 12300 // is not a potential match 12301 if (!selectionFound) { 12302 intentIter.remove(); 12303 } 12304 } 12305 } 12306 } 12307 12308 private boolean isProtectedAction(ActivityIntentInfo filter) { 12309 final Iterator<String> actionsIter = filter.actionsIterator(); 12310 while (actionsIter != null && actionsIter.hasNext()) { 12311 final String filterAction = actionsIter.next(); 12312 if (PROTECTED_ACTIONS.contains(filterAction)) { 12313 return true; 12314 } 12315 } 12316 return false; 12317 } 12318 12319 /** 12320 * Adjusts the priority of the given intent filter according to policy. 12321 * <p> 12322 * <ul> 12323 * <li>The priority for non privileged applications is capped to '0'</li> 12324 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12325 * <li>The priority for unbundled updates to privileged applications is capped to the 12326 * priority defined on the system partition</li> 12327 * </ul> 12328 * <p> 12329 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12330 * allowed to obtain any priority on any action. 12331 */ 12332 private void adjustPriority( 12333 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12334 // nothing to do; priority is fine as-is 12335 if (intent.getPriority() <= 0) { 12336 return; 12337 } 12338 12339 final ActivityInfo activityInfo = intent.activity.info; 12340 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12341 12342 final boolean privilegedApp = 12343 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12344 if (!privilegedApp) { 12345 // non-privileged applications can never define a priority >0 12346 if (DEBUG_FILTERS) { 12347 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12348 + " package: " + applicationInfo.packageName 12349 + " activity: " + intent.activity.className 12350 + " origPrio: " + intent.getPriority()); 12351 } 12352 intent.setPriority(0); 12353 return; 12354 } 12355 12356 if (systemActivities == null) { 12357 // the system package is not disabled; we're parsing the system partition 12358 if (isProtectedAction(intent)) { 12359 if (mDeferProtectedFilters) { 12360 // We can't deal with these just yet. No component should ever obtain a 12361 // >0 priority for a protected actions, with ONE exception -- the setup 12362 // wizard. The setup wizard, however, cannot be known until we're able to 12363 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12364 // until all intent filters have been processed. Chicken, meet egg. 12365 // Let the filter temporarily have a high priority and rectify the 12366 // priorities after all system packages have been scanned. 12367 mProtectedFilters.add(intent); 12368 if (DEBUG_FILTERS) { 12369 Slog.i(TAG, "Protected action; save for later;" 12370 + " package: " + applicationInfo.packageName 12371 + " activity: " + intent.activity.className 12372 + " origPrio: " + intent.getPriority()); 12373 } 12374 return; 12375 } else { 12376 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12377 Slog.i(TAG, "No setup wizard;" 12378 + " All protected intents capped to priority 0"); 12379 } 12380 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12381 if (DEBUG_FILTERS) { 12382 Slog.i(TAG, "Found setup wizard;" 12383 + " allow priority " + intent.getPriority() + ";" 12384 + " package: " + intent.activity.info.packageName 12385 + " activity: " + intent.activity.className 12386 + " priority: " + intent.getPriority()); 12387 } 12388 // setup wizard gets whatever it wants 12389 return; 12390 } 12391 if (DEBUG_FILTERS) { 12392 Slog.i(TAG, "Protected action; cap priority to 0;" 12393 + " package: " + intent.activity.info.packageName 12394 + " activity: " + intent.activity.className 12395 + " origPrio: " + intent.getPriority()); 12396 } 12397 intent.setPriority(0); 12398 return; 12399 } 12400 } 12401 // privileged apps on the system image get whatever priority they request 12402 return; 12403 } 12404 12405 // privileged app unbundled update ... try to find the same activity 12406 final PackageParser.Activity foundActivity = 12407 findMatchingActivity(systemActivities, activityInfo); 12408 if (foundActivity == null) { 12409 // this is a new activity; it cannot obtain >0 priority 12410 if (DEBUG_FILTERS) { 12411 Slog.i(TAG, "New activity; cap priority to 0;" 12412 + " package: " + applicationInfo.packageName 12413 + " activity: " + intent.activity.className 12414 + " origPrio: " + intent.getPriority()); 12415 } 12416 intent.setPriority(0); 12417 return; 12418 } 12419 12420 // found activity, now check for filter equivalence 12421 12422 // a shallow copy is enough; we modify the list, not its contents 12423 final List<ActivityIntentInfo> intentListCopy = 12424 new ArrayList<>(foundActivity.intents); 12425 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12426 12427 // find matching action subsets 12428 final Iterator<String> actionsIterator = intent.actionsIterator(); 12429 if (actionsIterator != null) { 12430 getIntentListSubset( 12431 intentListCopy, new ActionIterGenerator(), actionsIterator); 12432 if (intentListCopy.size() == 0) { 12433 // no more intents to match; we're not equivalent 12434 if (DEBUG_FILTERS) { 12435 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12436 + " package: " + applicationInfo.packageName 12437 + " activity: " + intent.activity.className 12438 + " origPrio: " + intent.getPriority()); 12439 } 12440 intent.setPriority(0); 12441 return; 12442 } 12443 } 12444 12445 // find matching category subsets 12446 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12447 if (categoriesIterator != null) { 12448 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12449 categoriesIterator); 12450 if (intentListCopy.size() == 0) { 12451 // no more intents to match; we're not equivalent 12452 if (DEBUG_FILTERS) { 12453 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12454 + " package: " + applicationInfo.packageName 12455 + " activity: " + intent.activity.className 12456 + " origPrio: " + intent.getPriority()); 12457 } 12458 intent.setPriority(0); 12459 return; 12460 } 12461 } 12462 12463 // find matching schemes subsets 12464 final Iterator<String> schemesIterator = intent.schemesIterator(); 12465 if (schemesIterator != null) { 12466 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12467 schemesIterator); 12468 if (intentListCopy.size() == 0) { 12469 // no more intents to match; we're not equivalent 12470 if (DEBUG_FILTERS) { 12471 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12472 + " package: " + applicationInfo.packageName 12473 + " activity: " + intent.activity.className 12474 + " origPrio: " + intent.getPriority()); 12475 } 12476 intent.setPriority(0); 12477 return; 12478 } 12479 } 12480 12481 // find matching authorities subsets 12482 final Iterator<IntentFilter.AuthorityEntry> 12483 authoritiesIterator = intent.authoritiesIterator(); 12484 if (authoritiesIterator != null) { 12485 getIntentListSubset(intentListCopy, 12486 new AuthoritiesIterGenerator(), 12487 authoritiesIterator); 12488 if (intentListCopy.size() == 0) { 12489 // no more intents to match; we're not equivalent 12490 if (DEBUG_FILTERS) { 12491 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12492 + " package: " + applicationInfo.packageName 12493 + " activity: " + intent.activity.className 12494 + " origPrio: " + intent.getPriority()); 12495 } 12496 intent.setPriority(0); 12497 return; 12498 } 12499 } 12500 12501 // we found matching filter(s); app gets the max priority of all intents 12502 int cappedPriority = 0; 12503 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12504 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12505 } 12506 if (intent.getPriority() > cappedPriority) { 12507 if (DEBUG_FILTERS) { 12508 Slog.i(TAG, "Found matching filter(s);" 12509 + " cap priority to " + cappedPriority + ";" 12510 + " package: " + applicationInfo.packageName 12511 + " activity: " + intent.activity.className 12512 + " origPrio: " + intent.getPriority()); 12513 } 12514 intent.setPriority(cappedPriority); 12515 return; 12516 } 12517 // all this for nothing; the requested priority was <= what was on the system 12518 } 12519 12520 public final void addActivity(PackageParser.Activity a, String type) { 12521 mActivities.put(a.getComponentName(), a); 12522 if (DEBUG_SHOW_INFO) 12523 Log.v( 12524 TAG, " " + type + " " + 12525 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12526 if (DEBUG_SHOW_INFO) 12527 Log.v(TAG, " Class=" + a.info.name); 12528 final int NI = a.intents.size(); 12529 for (int j=0; j<NI; j++) { 12530 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12531 if ("activity".equals(type)) { 12532 final PackageSetting ps = 12533 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12534 final List<PackageParser.Activity> systemActivities = 12535 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12536 adjustPriority(systemActivities, intent); 12537 } 12538 if (DEBUG_SHOW_INFO) { 12539 Log.v(TAG, " IntentFilter:"); 12540 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12541 } 12542 if (!intent.debugCheck()) { 12543 Log.w(TAG, "==> For Activity " + a.info.name); 12544 } 12545 addFilter(intent); 12546 } 12547 } 12548 12549 public final void removeActivity(PackageParser.Activity a, String type) { 12550 mActivities.remove(a.getComponentName()); 12551 if (DEBUG_SHOW_INFO) { 12552 Log.v(TAG, " " + type + " " 12553 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12554 : a.info.name) + ":"); 12555 Log.v(TAG, " Class=" + a.info.name); 12556 } 12557 final int NI = a.intents.size(); 12558 for (int j=0; j<NI; j++) { 12559 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12560 if (DEBUG_SHOW_INFO) { 12561 Log.v(TAG, " IntentFilter:"); 12562 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12563 } 12564 removeFilter(intent); 12565 } 12566 } 12567 12568 @Override 12569 protected boolean allowFilterResult( 12570 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12571 ActivityInfo filterAi = filter.activity.info; 12572 for (int i=dest.size()-1; i>=0; i--) { 12573 ActivityInfo destAi = dest.get(i).activityInfo; 12574 if (destAi.name == filterAi.name 12575 && destAi.packageName == filterAi.packageName) { 12576 return false; 12577 } 12578 } 12579 return true; 12580 } 12581 12582 @Override 12583 protected ActivityIntentInfo[] newArray(int size) { 12584 return new ActivityIntentInfo[size]; 12585 } 12586 12587 @Override 12588 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12589 if (!sUserManager.exists(userId)) return true; 12590 PackageParser.Package p = filter.activity.owner; 12591 if (p != null) { 12592 PackageSetting ps = (PackageSetting)p.mExtras; 12593 if (ps != null) { 12594 // System apps are never considered stopped for purposes of 12595 // filtering, because there may be no way for the user to 12596 // actually re-launch them. 12597 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12598 && ps.getStopped(userId); 12599 } 12600 } 12601 return false; 12602 } 12603 12604 @Override 12605 protected boolean isPackageForFilter(String packageName, 12606 PackageParser.ActivityIntentInfo info) { 12607 return packageName.equals(info.activity.owner.packageName); 12608 } 12609 12610 @Override 12611 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12612 int match, int userId) { 12613 if (!sUserManager.exists(userId)) return null; 12614 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12615 return null; 12616 } 12617 final PackageParser.Activity activity = info.activity; 12618 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12619 if (ps == null) { 12620 return null; 12621 } 12622 final PackageUserState userState = ps.readUserState(userId); 12623 ActivityInfo ai = 12624 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12625 if (ai == null) { 12626 return null; 12627 } 12628 final boolean matchExplicitlyVisibleOnly = 12629 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12630 final boolean matchVisibleToInstantApp = 12631 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12632 final boolean componentVisible = 12633 matchVisibleToInstantApp 12634 && info.isVisibleToInstantApp() 12635 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12636 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12637 // throw out filters that aren't visible to ephemeral apps 12638 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12639 return null; 12640 } 12641 // throw out instant app filters if we're not explicitly requesting them 12642 if (!matchInstantApp && userState.instantApp) { 12643 return null; 12644 } 12645 // throw out instant app filters if updates are available; will trigger 12646 // instant app resolution 12647 if (userState.instantApp && ps.isUpdateAvailable()) { 12648 return null; 12649 } 12650 final ResolveInfo res = new ResolveInfo(); 12651 res.activityInfo = ai; 12652 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12653 res.filter = info; 12654 } 12655 if (info != null) { 12656 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12657 } 12658 res.priority = info.getPriority(); 12659 res.preferredOrder = activity.owner.mPreferredOrder; 12660 //System.out.println("Result: " + res.activityInfo.className + 12661 // " = " + res.priority); 12662 res.match = match; 12663 res.isDefault = info.hasDefault; 12664 res.labelRes = info.labelRes; 12665 res.nonLocalizedLabel = info.nonLocalizedLabel; 12666 if (userNeedsBadging(userId)) { 12667 res.noResourceId = true; 12668 } else { 12669 res.icon = info.icon; 12670 } 12671 res.iconResourceId = info.icon; 12672 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12673 res.isInstantAppAvailable = userState.instantApp; 12674 return res; 12675 } 12676 12677 @Override 12678 protected void sortResults(List<ResolveInfo> results) { 12679 Collections.sort(results, mResolvePrioritySorter); 12680 } 12681 12682 @Override 12683 protected void dumpFilter(PrintWriter out, String prefix, 12684 PackageParser.ActivityIntentInfo filter) { 12685 out.print(prefix); out.print( 12686 Integer.toHexString(System.identityHashCode(filter.activity))); 12687 out.print(' '); 12688 filter.activity.printComponentShortName(out); 12689 out.print(" filter "); 12690 out.println(Integer.toHexString(System.identityHashCode(filter))); 12691 } 12692 12693 @Override 12694 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12695 return filter.activity; 12696 } 12697 12698 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12699 PackageParser.Activity activity = (PackageParser.Activity)label; 12700 out.print(prefix); out.print( 12701 Integer.toHexString(System.identityHashCode(activity))); 12702 out.print(' '); 12703 activity.printComponentShortName(out); 12704 if (count > 1) { 12705 out.print(" ("); out.print(count); out.print(" filters)"); 12706 } 12707 out.println(); 12708 } 12709 12710 // Keys are String (activity class name), values are Activity. 12711 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12712 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12713 private int mFlags; 12714 } 12715 12716 private final class ServiceIntentResolver 12717 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12718 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12719 boolean defaultOnly, int userId) { 12720 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12721 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12722 } 12723 12724 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12725 int userId) { 12726 if (!sUserManager.exists(userId)) return null; 12727 mFlags = flags; 12728 return super.queryIntent(intent, resolvedType, 12729 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12730 userId); 12731 } 12732 12733 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12734 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12735 if (!sUserManager.exists(userId)) return null; 12736 if (packageServices == null) { 12737 return null; 12738 } 12739 mFlags = flags; 12740 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12741 final int N = packageServices.size(); 12742 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12743 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12744 12745 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12746 for (int i = 0; i < N; ++i) { 12747 intentFilters = packageServices.get(i).intents; 12748 if (intentFilters != null && intentFilters.size() > 0) { 12749 PackageParser.ServiceIntentInfo[] array = 12750 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12751 intentFilters.toArray(array); 12752 listCut.add(array); 12753 } 12754 } 12755 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12756 } 12757 12758 public final void addService(PackageParser.Service s) { 12759 mServices.put(s.getComponentName(), s); 12760 if (DEBUG_SHOW_INFO) { 12761 Log.v(TAG, " " 12762 + (s.info.nonLocalizedLabel != null 12763 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12764 Log.v(TAG, " Class=" + s.info.name); 12765 } 12766 final int NI = s.intents.size(); 12767 int j; 12768 for (j=0; j<NI; j++) { 12769 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12770 if (DEBUG_SHOW_INFO) { 12771 Log.v(TAG, " IntentFilter:"); 12772 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12773 } 12774 if (!intent.debugCheck()) { 12775 Log.w(TAG, "==> For Service " + s.info.name); 12776 } 12777 addFilter(intent); 12778 } 12779 } 12780 12781 public final void removeService(PackageParser.Service s) { 12782 mServices.remove(s.getComponentName()); 12783 if (DEBUG_SHOW_INFO) { 12784 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12785 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12786 Log.v(TAG, " Class=" + s.info.name); 12787 } 12788 final int NI = s.intents.size(); 12789 int j; 12790 for (j=0; j<NI; j++) { 12791 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12792 if (DEBUG_SHOW_INFO) { 12793 Log.v(TAG, " IntentFilter:"); 12794 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12795 } 12796 removeFilter(intent); 12797 } 12798 } 12799 12800 @Override 12801 protected boolean allowFilterResult( 12802 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12803 ServiceInfo filterSi = filter.service.info; 12804 for (int i=dest.size()-1; i>=0; i--) { 12805 ServiceInfo destAi = dest.get(i).serviceInfo; 12806 if (destAi.name == filterSi.name 12807 && destAi.packageName == filterSi.packageName) { 12808 return false; 12809 } 12810 } 12811 return true; 12812 } 12813 12814 @Override 12815 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12816 return new PackageParser.ServiceIntentInfo[size]; 12817 } 12818 12819 @Override 12820 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12821 if (!sUserManager.exists(userId)) return true; 12822 PackageParser.Package p = filter.service.owner; 12823 if (p != null) { 12824 PackageSetting ps = (PackageSetting)p.mExtras; 12825 if (ps != null) { 12826 // System apps are never considered stopped for purposes of 12827 // filtering, because there may be no way for the user to 12828 // actually re-launch them. 12829 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12830 && ps.getStopped(userId); 12831 } 12832 } 12833 return false; 12834 } 12835 12836 @Override 12837 protected boolean isPackageForFilter(String packageName, 12838 PackageParser.ServiceIntentInfo info) { 12839 return packageName.equals(info.service.owner.packageName); 12840 } 12841 12842 @Override 12843 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12844 int match, int userId) { 12845 if (!sUserManager.exists(userId)) return null; 12846 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12847 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12848 return null; 12849 } 12850 final PackageParser.Service service = info.service; 12851 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12852 if (ps == null) { 12853 return null; 12854 } 12855 final PackageUserState userState = ps.readUserState(userId); 12856 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12857 userState, userId); 12858 if (si == null) { 12859 return null; 12860 } 12861 final boolean matchVisibleToInstantApp = 12862 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12863 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12864 // throw out filters that aren't visible to ephemeral apps 12865 if (matchVisibleToInstantApp 12866 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12867 return null; 12868 } 12869 // throw out ephemeral filters if we're not explicitly requesting them 12870 if (!isInstantApp && userState.instantApp) { 12871 return null; 12872 } 12873 // throw out instant app filters if updates are available; will trigger 12874 // instant app resolution 12875 if (userState.instantApp && ps.isUpdateAvailable()) { 12876 return null; 12877 } 12878 final ResolveInfo res = new ResolveInfo(); 12879 res.serviceInfo = si; 12880 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12881 res.filter = filter; 12882 } 12883 res.priority = info.getPriority(); 12884 res.preferredOrder = service.owner.mPreferredOrder; 12885 res.match = match; 12886 res.isDefault = info.hasDefault; 12887 res.labelRes = info.labelRes; 12888 res.nonLocalizedLabel = info.nonLocalizedLabel; 12889 res.icon = info.icon; 12890 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12891 return res; 12892 } 12893 12894 @Override 12895 protected void sortResults(List<ResolveInfo> results) { 12896 Collections.sort(results, mResolvePrioritySorter); 12897 } 12898 12899 @Override 12900 protected void dumpFilter(PrintWriter out, String prefix, 12901 PackageParser.ServiceIntentInfo filter) { 12902 out.print(prefix); out.print( 12903 Integer.toHexString(System.identityHashCode(filter.service))); 12904 out.print(' '); 12905 filter.service.printComponentShortName(out); 12906 out.print(" filter "); 12907 out.print(Integer.toHexString(System.identityHashCode(filter))); 12908 if (filter.service.info.permission != null) { 12909 out.print(" permission "); out.println(filter.service.info.permission); 12910 } else { 12911 out.println(); 12912 } 12913 } 12914 12915 @Override 12916 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12917 return filter.service; 12918 } 12919 12920 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12921 PackageParser.Service service = (PackageParser.Service)label; 12922 out.print(prefix); out.print( 12923 Integer.toHexString(System.identityHashCode(service))); 12924 out.print(' '); 12925 service.printComponentShortName(out); 12926 if (count > 1) { 12927 out.print(" ("); out.print(count); out.print(" filters)"); 12928 } 12929 out.println(); 12930 } 12931 12932// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12933// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12934// final List<ResolveInfo> retList = Lists.newArrayList(); 12935// while (i.hasNext()) { 12936// final ResolveInfo resolveInfo = (ResolveInfo) i; 12937// if (isEnabledLP(resolveInfo.serviceInfo)) { 12938// retList.add(resolveInfo); 12939// } 12940// } 12941// return retList; 12942// } 12943 12944 // Keys are String (activity class name), values are Activity. 12945 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12946 = new ArrayMap<ComponentName, PackageParser.Service>(); 12947 private int mFlags; 12948 } 12949 12950 private final class ProviderIntentResolver 12951 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12952 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12953 boolean defaultOnly, int userId) { 12954 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12955 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12956 } 12957 12958 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12959 int userId) { 12960 if (!sUserManager.exists(userId)) 12961 return null; 12962 mFlags = flags; 12963 return super.queryIntent(intent, resolvedType, 12964 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12965 userId); 12966 } 12967 12968 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12969 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12970 if (!sUserManager.exists(userId)) 12971 return null; 12972 if (packageProviders == null) { 12973 return null; 12974 } 12975 mFlags = flags; 12976 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12977 final int N = packageProviders.size(); 12978 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12979 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12980 12981 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12982 for (int i = 0; i < N; ++i) { 12983 intentFilters = packageProviders.get(i).intents; 12984 if (intentFilters != null && intentFilters.size() > 0) { 12985 PackageParser.ProviderIntentInfo[] array = 12986 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12987 intentFilters.toArray(array); 12988 listCut.add(array); 12989 } 12990 } 12991 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12992 } 12993 12994 public final void addProvider(PackageParser.Provider p) { 12995 if (mProviders.containsKey(p.getComponentName())) { 12996 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12997 return; 12998 } 12999 13000 mProviders.put(p.getComponentName(), p); 13001 if (DEBUG_SHOW_INFO) { 13002 Log.v(TAG, " " 13003 + (p.info.nonLocalizedLabel != null 13004 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13005 Log.v(TAG, " Class=" + p.info.name); 13006 } 13007 final int NI = p.intents.size(); 13008 int j; 13009 for (j = 0; j < NI; j++) { 13010 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13011 if (DEBUG_SHOW_INFO) { 13012 Log.v(TAG, " IntentFilter:"); 13013 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13014 } 13015 if (!intent.debugCheck()) { 13016 Log.w(TAG, "==> For Provider " + p.info.name); 13017 } 13018 addFilter(intent); 13019 } 13020 } 13021 13022 public final void removeProvider(PackageParser.Provider p) { 13023 mProviders.remove(p.getComponentName()); 13024 if (DEBUG_SHOW_INFO) { 13025 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13026 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13027 Log.v(TAG, " Class=" + p.info.name); 13028 } 13029 final int NI = p.intents.size(); 13030 int j; 13031 for (j = 0; j < NI; j++) { 13032 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13033 if (DEBUG_SHOW_INFO) { 13034 Log.v(TAG, " IntentFilter:"); 13035 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13036 } 13037 removeFilter(intent); 13038 } 13039 } 13040 13041 @Override 13042 protected boolean allowFilterResult( 13043 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13044 ProviderInfo filterPi = filter.provider.info; 13045 for (int i = dest.size() - 1; i >= 0; i--) { 13046 ProviderInfo destPi = dest.get(i).providerInfo; 13047 if (destPi.name == filterPi.name 13048 && destPi.packageName == filterPi.packageName) { 13049 return false; 13050 } 13051 } 13052 return true; 13053 } 13054 13055 @Override 13056 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13057 return new PackageParser.ProviderIntentInfo[size]; 13058 } 13059 13060 @Override 13061 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13062 if (!sUserManager.exists(userId)) 13063 return true; 13064 PackageParser.Package p = filter.provider.owner; 13065 if (p != null) { 13066 PackageSetting ps = (PackageSetting) p.mExtras; 13067 if (ps != null) { 13068 // System apps are never considered stopped for purposes of 13069 // filtering, because there may be no way for the user to 13070 // actually re-launch them. 13071 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13072 && ps.getStopped(userId); 13073 } 13074 } 13075 return false; 13076 } 13077 13078 @Override 13079 protected boolean isPackageForFilter(String packageName, 13080 PackageParser.ProviderIntentInfo info) { 13081 return packageName.equals(info.provider.owner.packageName); 13082 } 13083 13084 @Override 13085 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13086 int match, int userId) { 13087 if (!sUserManager.exists(userId)) 13088 return null; 13089 final PackageParser.ProviderIntentInfo info = filter; 13090 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13091 return null; 13092 } 13093 final PackageParser.Provider provider = info.provider; 13094 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13095 if (ps == null) { 13096 return null; 13097 } 13098 final PackageUserState userState = ps.readUserState(userId); 13099 final boolean matchVisibleToInstantApp = 13100 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13101 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13102 // throw out filters that aren't visible to instant applications 13103 if (matchVisibleToInstantApp 13104 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13105 return null; 13106 } 13107 // throw out instant application filters if we're not explicitly requesting them 13108 if (!isInstantApp && userState.instantApp) { 13109 return null; 13110 } 13111 // throw out instant application filters if updates are available; will trigger 13112 // instant application resolution 13113 if (userState.instantApp && ps.isUpdateAvailable()) { 13114 return null; 13115 } 13116 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13117 userState, userId); 13118 if (pi == null) { 13119 return null; 13120 } 13121 final ResolveInfo res = new ResolveInfo(); 13122 res.providerInfo = pi; 13123 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13124 res.filter = filter; 13125 } 13126 res.priority = info.getPriority(); 13127 res.preferredOrder = provider.owner.mPreferredOrder; 13128 res.match = match; 13129 res.isDefault = info.hasDefault; 13130 res.labelRes = info.labelRes; 13131 res.nonLocalizedLabel = info.nonLocalizedLabel; 13132 res.icon = info.icon; 13133 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13134 return res; 13135 } 13136 13137 @Override 13138 protected void sortResults(List<ResolveInfo> results) { 13139 Collections.sort(results, mResolvePrioritySorter); 13140 } 13141 13142 @Override 13143 protected void dumpFilter(PrintWriter out, String prefix, 13144 PackageParser.ProviderIntentInfo filter) { 13145 out.print(prefix); 13146 out.print( 13147 Integer.toHexString(System.identityHashCode(filter.provider))); 13148 out.print(' '); 13149 filter.provider.printComponentShortName(out); 13150 out.print(" filter "); 13151 out.println(Integer.toHexString(System.identityHashCode(filter))); 13152 } 13153 13154 @Override 13155 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13156 return filter.provider; 13157 } 13158 13159 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13160 PackageParser.Provider provider = (PackageParser.Provider)label; 13161 out.print(prefix); out.print( 13162 Integer.toHexString(System.identityHashCode(provider))); 13163 out.print(' '); 13164 provider.printComponentShortName(out); 13165 if (count > 1) { 13166 out.print(" ("); out.print(count); out.print(" filters)"); 13167 } 13168 out.println(); 13169 } 13170 13171 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13172 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13173 private int mFlags; 13174 } 13175 13176 static final class InstantAppIntentResolver 13177 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13178 AuxiliaryResolveInfo.AuxiliaryFilter> { 13179 /** 13180 * The result that has the highest defined order. Ordering applies on a 13181 * per-package basis. Mapping is from package name to Pair of order and 13182 * EphemeralResolveInfo. 13183 * <p> 13184 * NOTE: This is implemented as a field variable for convenience and efficiency. 13185 * By having a field variable, we're able to track filter ordering as soon as 13186 * a non-zero order is defined. Otherwise, multiple loops across the result set 13187 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13188 * this needs to be contained entirely within {@link #filterResults}. 13189 */ 13190 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13191 13192 @Override 13193 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13194 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13195 } 13196 13197 @Override 13198 protected boolean isPackageForFilter(String packageName, 13199 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13200 return true; 13201 } 13202 13203 @Override 13204 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13205 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13206 if (!sUserManager.exists(userId)) { 13207 return null; 13208 } 13209 final String packageName = responseObj.resolveInfo.getPackageName(); 13210 final Integer order = responseObj.getOrder(); 13211 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13212 mOrderResult.get(packageName); 13213 // ordering is enabled and this item's order isn't high enough 13214 if (lastOrderResult != null && lastOrderResult.first >= order) { 13215 return null; 13216 } 13217 final InstantAppResolveInfo res = responseObj.resolveInfo; 13218 if (order > 0) { 13219 // non-zero order, enable ordering 13220 mOrderResult.put(packageName, new Pair<>(order, res)); 13221 } 13222 return responseObj; 13223 } 13224 13225 @Override 13226 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13227 // only do work if ordering is enabled [most of the time it won't be] 13228 if (mOrderResult.size() == 0) { 13229 return; 13230 } 13231 int resultSize = results.size(); 13232 for (int i = 0; i < resultSize; i++) { 13233 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13234 final String packageName = info.getPackageName(); 13235 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13236 if (savedInfo == null) { 13237 // package doesn't having ordering 13238 continue; 13239 } 13240 if (savedInfo.second == info) { 13241 // circled back to the highest ordered item; remove from order list 13242 mOrderResult.remove(packageName); 13243 if (mOrderResult.size() == 0) { 13244 // no more ordered items 13245 break; 13246 } 13247 continue; 13248 } 13249 // item has a worse order, remove it from the result list 13250 results.remove(i); 13251 resultSize--; 13252 i--; 13253 } 13254 } 13255 } 13256 13257 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13258 new Comparator<ResolveInfo>() { 13259 public int compare(ResolveInfo r1, ResolveInfo r2) { 13260 int v1 = r1.priority; 13261 int v2 = r2.priority; 13262 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13263 if (v1 != v2) { 13264 return (v1 > v2) ? -1 : 1; 13265 } 13266 v1 = r1.preferredOrder; 13267 v2 = r2.preferredOrder; 13268 if (v1 != v2) { 13269 return (v1 > v2) ? -1 : 1; 13270 } 13271 if (r1.isDefault != r2.isDefault) { 13272 return r1.isDefault ? -1 : 1; 13273 } 13274 v1 = r1.match; 13275 v2 = r2.match; 13276 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13277 if (v1 != v2) { 13278 return (v1 > v2) ? -1 : 1; 13279 } 13280 if (r1.system != r2.system) { 13281 return r1.system ? -1 : 1; 13282 } 13283 if (r1.activityInfo != null) { 13284 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13285 } 13286 if (r1.serviceInfo != null) { 13287 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13288 } 13289 if (r1.providerInfo != null) { 13290 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13291 } 13292 return 0; 13293 } 13294 }; 13295 13296 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13297 new Comparator<ProviderInfo>() { 13298 public int compare(ProviderInfo p1, ProviderInfo p2) { 13299 final int v1 = p1.initOrder; 13300 final int v2 = p2.initOrder; 13301 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13302 } 13303 }; 13304 13305 @Override 13306 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13307 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13308 final int[] userIds, int[] instantUserIds) { 13309 mHandler.post(new Runnable() { 13310 @Override 13311 public void run() { 13312 try { 13313 final IActivityManager am = ActivityManager.getService(); 13314 if (am == null) return; 13315 final int[] resolvedUserIds; 13316 if (userIds == null) { 13317 resolvedUserIds = am.getRunningUserIds(); 13318 } else { 13319 resolvedUserIds = userIds; 13320 } 13321 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13322 resolvedUserIds, false); 13323 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13324 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13325 instantUserIds, true); 13326 } 13327 } catch (RemoteException ex) { 13328 } 13329 } 13330 }); 13331 } 13332 13333 @Override 13334 public void notifyPackageAdded(String packageName) { 13335 final PackageListObserver[] observers; 13336 synchronized (mPackages) { 13337 if (mPackageListObservers.size() == 0) { 13338 return; 13339 } 13340 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13341 } 13342 for (int i = observers.length - 1; i >= 0; --i) { 13343 observers[i].onPackageAdded(packageName); 13344 } 13345 } 13346 13347 @Override 13348 public void notifyPackageRemoved(String packageName) { 13349 final PackageListObserver[] observers; 13350 synchronized (mPackages) { 13351 if (mPackageListObservers.size() == 0) { 13352 return; 13353 } 13354 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13355 } 13356 for (int i = observers.length - 1; i >= 0; --i) { 13357 observers[i].onPackageRemoved(packageName); 13358 } 13359 } 13360 13361 /** 13362 * Sends a broadcast for the given action. 13363 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13364 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13365 * the system and applications allowed to see instant applications to receive package 13366 * lifecycle events for instant applications. 13367 */ 13368 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13369 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13370 int[] userIds, boolean isInstantApp) 13371 throws RemoteException { 13372 for (int id : userIds) { 13373 final Intent intent = new Intent(action, 13374 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13375 final String[] requiredPermissions = 13376 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13377 if (extras != null) { 13378 intent.putExtras(extras); 13379 } 13380 if (targetPkg != null) { 13381 intent.setPackage(targetPkg); 13382 } 13383 // Modify the UID when posting to other users 13384 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13385 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13386 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13387 intent.putExtra(Intent.EXTRA_UID, uid); 13388 } 13389 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13390 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13391 if (DEBUG_BROADCASTS) { 13392 RuntimeException here = new RuntimeException("here"); 13393 here.fillInStackTrace(); 13394 Slog.d(TAG, "Sending to user " + id + ": " 13395 + intent.toShortString(false, true, false, false) 13396 + " " + intent.getExtras(), here); 13397 } 13398 am.broadcastIntent(null, intent, null, finishedReceiver, 13399 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13400 null, finishedReceiver != null, false, id); 13401 } 13402 } 13403 13404 /** 13405 * Check if the external storage media is available. This is true if there 13406 * is a mounted external storage medium or if the external storage is 13407 * emulated. 13408 */ 13409 private boolean isExternalMediaAvailable() { 13410 return mMediaMounted || Environment.isExternalStorageEmulated(); 13411 } 13412 13413 @Override 13414 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13415 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13416 return null; 13417 } 13418 if (!isExternalMediaAvailable()) { 13419 // If the external storage is no longer mounted at this point, 13420 // the caller may not have been able to delete all of this 13421 // packages files and can not delete any more. Bail. 13422 return null; 13423 } 13424 synchronized (mPackages) { 13425 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13426 if (lastPackage != null) { 13427 pkgs.remove(lastPackage); 13428 } 13429 if (pkgs.size() > 0) { 13430 return pkgs.get(0); 13431 } 13432 } 13433 return null; 13434 } 13435 13436 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13437 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13438 userId, andCode ? 1 : 0, packageName); 13439 if (mSystemReady) { 13440 msg.sendToTarget(); 13441 } else { 13442 if (mPostSystemReadyMessages == null) { 13443 mPostSystemReadyMessages = new ArrayList<>(); 13444 } 13445 mPostSystemReadyMessages.add(msg); 13446 } 13447 } 13448 13449 void startCleaningPackages() { 13450 // reader 13451 if (!isExternalMediaAvailable()) { 13452 return; 13453 } 13454 synchronized (mPackages) { 13455 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13456 return; 13457 } 13458 } 13459 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13460 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13461 IActivityManager am = ActivityManager.getService(); 13462 if (am != null) { 13463 int dcsUid = -1; 13464 synchronized (mPackages) { 13465 if (!mDefaultContainerWhitelisted) { 13466 mDefaultContainerWhitelisted = true; 13467 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13468 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13469 } 13470 } 13471 try { 13472 if (dcsUid > 0) { 13473 am.backgroundWhitelistUid(dcsUid); 13474 } 13475 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13476 UserHandle.USER_SYSTEM); 13477 } catch (RemoteException e) { 13478 } 13479 } 13480 } 13481 13482 /** 13483 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13484 * it is acting on behalf on an enterprise or the user). 13485 * 13486 * Note that the ordering of the conditionals in this method is important. The checks we perform 13487 * are as follows, in this order: 13488 * 13489 * 1) If the install is being performed by a system app, we can trust the app to have set the 13490 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13491 * what it is. 13492 * 2) If the install is being performed by a device or profile owner app, the install reason 13493 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13494 * set the install reason correctly. If the app targets an older SDK version where install 13495 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13496 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13497 * 3) In all other cases, the install is being performed by a regular app that is neither part 13498 * of the system nor a device or profile owner. We have no reason to believe that this app is 13499 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13500 * set to enterprise policy and if so, change it to unknown instead. 13501 */ 13502 private int fixUpInstallReason(String installerPackageName, int installerUid, 13503 int installReason) { 13504 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13505 == PERMISSION_GRANTED) { 13506 // If the install is being performed by a system app, we trust that app to have set the 13507 // install reason correctly. 13508 return installReason; 13509 } 13510 13511 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13512 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13513 if (dpm != null) { 13514 ComponentName owner = null; 13515 try { 13516 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13517 if (owner == null) { 13518 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13519 } 13520 } catch (RemoteException e) { 13521 } 13522 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13523 // If the install is being performed by a device or profile owner, the install 13524 // reason should be enterprise policy. 13525 return PackageManager.INSTALL_REASON_POLICY; 13526 } 13527 } 13528 13529 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13530 // If the install is being performed by a regular app (i.e. neither system app nor 13531 // device or profile owner), we have no reason to believe that the app is acting on 13532 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13533 // change it to unknown instead. 13534 return PackageManager.INSTALL_REASON_UNKNOWN; 13535 } 13536 13537 // If the install is being performed by a regular app and the install reason was set to any 13538 // value but enterprise policy, leave the install reason unchanged. 13539 return installReason; 13540 } 13541 13542 void installStage(String packageName, File stagedDir, 13543 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13544 String installerPackageName, int installerUid, UserHandle user, 13545 PackageParser.SigningDetails signingDetails) { 13546 if (DEBUG_INSTANT) { 13547 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13548 Slog.d(TAG, "Ephemeral install of " + packageName); 13549 } 13550 } 13551 final VerificationInfo verificationInfo = new VerificationInfo( 13552 sessionParams.originatingUri, sessionParams.referrerUri, 13553 sessionParams.originatingUid, installerUid); 13554 13555 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13556 13557 final Message msg = mHandler.obtainMessage(INIT_COPY); 13558 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13559 sessionParams.installReason); 13560 final InstallParams params = new InstallParams(origin, null, observer, 13561 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13562 verificationInfo, user, sessionParams.abiOverride, 13563 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13564 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13565 msg.obj = params; 13566 13567 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13568 System.identityHashCode(msg.obj)); 13569 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13570 System.identityHashCode(msg.obj)); 13571 13572 mHandler.sendMessage(msg); 13573 } 13574 13575 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13576 int userId) { 13577 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13578 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13579 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13580 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13581 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13582 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13583 13584 // Send a session commit broadcast 13585 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13586 info.installReason = pkgSetting.getInstallReason(userId); 13587 info.appPackageName = packageName; 13588 sendSessionCommitBroadcast(info, userId); 13589 } 13590 13591 @Override 13592 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13593 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13594 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13595 return; 13596 } 13597 Bundle extras = new Bundle(1); 13598 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13599 final int uid = UserHandle.getUid( 13600 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13601 extras.putInt(Intent.EXTRA_UID, uid); 13602 13603 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13604 packageName, extras, 0, null, null, userIds, instantUserIds); 13605 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13606 mHandler.post(() -> { 13607 for (int userId : userIds) { 13608 sendBootCompletedBroadcastToSystemApp( 13609 packageName, includeStopped, userId); 13610 } 13611 } 13612 ); 13613 } 13614 } 13615 13616 /** 13617 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13618 * automatically without needing an explicit launch. 13619 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13620 */ 13621 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13622 int userId) { 13623 // If user is not running, the app didn't miss any broadcast 13624 if (!mUserManagerInternal.isUserRunning(userId)) { 13625 return; 13626 } 13627 final IActivityManager am = ActivityManager.getService(); 13628 try { 13629 // Deliver LOCKED_BOOT_COMPLETED first 13630 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13631 .setPackage(packageName); 13632 if (includeStopped) { 13633 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13634 } 13635 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13636 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13637 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13638 13639 // Deliver BOOT_COMPLETED only if user is unlocked 13640 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13641 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13642 if (includeStopped) { 13643 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13644 } 13645 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13646 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13647 } 13648 } catch (RemoteException e) { 13649 throw e.rethrowFromSystemServer(); 13650 } 13651 } 13652 13653 @Override 13654 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13655 int userId) { 13656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13657 PackageSetting pkgSetting; 13658 final int callingUid = Binder.getCallingUid(); 13659 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13660 true /* requireFullPermission */, true /* checkShell */, 13661 "setApplicationHiddenSetting for user " + userId); 13662 13663 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13664 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13665 return false; 13666 } 13667 13668 long callingId = Binder.clearCallingIdentity(); 13669 try { 13670 boolean sendAdded = false; 13671 boolean sendRemoved = false; 13672 // writer 13673 synchronized (mPackages) { 13674 pkgSetting = mSettings.mPackages.get(packageName); 13675 if (pkgSetting == null) { 13676 return false; 13677 } 13678 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13679 return false; 13680 } 13681 // Do not allow "android" is being disabled 13682 if ("android".equals(packageName)) { 13683 Slog.w(TAG, "Cannot hide package: android"); 13684 return false; 13685 } 13686 // Cannot hide static shared libs as they are considered 13687 // a part of the using app (emulating static linking). Also 13688 // static libs are installed always on internal storage. 13689 PackageParser.Package pkg = mPackages.get(packageName); 13690 if (pkg != null && pkg.staticSharedLibName != null) { 13691 Slog.w(TAG, "Cannot hide package: " + packageName 13692 + " providing static shared library: " 13693 + pkg.staticSharedLibName); 13694 return false; 13695 } 13696 // Only allow protected packages to hide themselves. 13697 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13698 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13699 Slog.w(TAG, "Not hiding protected package: " + packageName); 13700 return false; 13701 } 13702 13703 if (pkgSetting.getHidden(userId) != hidden) { 13704 pkgSetting.setHidden(hidden, userId); 13705 mSettings.writePackageRestrictionsLPr(userId); 13706 if (hidden) { 13707 sendRemoved = true; 13708 } else { 13709 sendAdded = true; 13710 } 13711 } 13712 } 13713 if (sendAdded) { 13714 sendPackageAddedForUser(packageName, pkgSetting, userId); 13715 return true; 13716 } 13717 if (sendRemoved) { 13718 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13719 "hiding pkg"); 13720 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13721 return true; 13722 } 13723 } finally { 13724 Binder.restoreCallingIdentity(callingId); 13725 } 13726 return false; 13727 } 13728 13729 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13730 int userId) { 13731 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13732 info.removedPackage = packageName; 13733 info.installerPackageName = pkgSetting.installerPackageName; 13734 info.removedUsers = new int[] {userId}; 13735 info.broadcastUsers = new int[] {userId}; 13736 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13737 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13738 } 13739 13740 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13741 if (pkgList.length > 0) { 13742 Bundle extras = new Bundle(1); 13743 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13744 13745 sendPackageBroadcast( 13746 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13747 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13748 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13749 new int[] {userId}, null); 13750 } 13751 } 13752 13753 /** 13754 * Returns true if application is not found or there was an error. Otherwise it returns 13755 * the hidden state of the package for the given user. 13756 */ 13757 @Override 13758 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13759 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13760 final int callingUid = Binder.getCallingUid(); 13761 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13762 true /* requireFullPermission */, false /* checkShell */, 13763 "getApplicationHidden for user " + userId); 13764 PackageSetting ps; 13765 long callingId = Binder.clearCallingIdentity(); 13766 try { 13767 // writer 13768 synchronized (mPackages) { 13769 ps = mSettings.mPackages.get(packageName); 13770 if (ps == null) { 13771 return true; 13772 } 13773 if (filterAppAccessLPr(ps, callingUid, userId)) { 13774 return true; 13775 } 13776 return ps.getHidden(userId); 13777 } 13778 } finally { 13779 Binder.restoreCallingIdentity(callingId); 13780 } 13781 } 13782 13783 /** 13784 * @hide 13785 */ 13786 @Override 13787 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13788 int installReason) { 13789 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13790 null); 13791 PackageSetting pkgSetting; 13792 final int callingUid = Binder.getCallingUid(); 13793 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13794 true /* requireFullPermission */, true /* checkShell */, 13795 "installExistingPackage for user " + userId); 13796 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13797 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13798 } 13799 13800 long callingId = Binder.clearCallingIdentity(); 13801 try { 13802 boolean installed = false; 13803 final boolean instantApp = 13804 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13805 final boolean fullApp = 13806 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13807 13808 // writer 13809 synchronized (mPackages) { 13810 pkgSetting = mSettings.mPackages.get(packageName); 13811 if (pkgSetting == null) { 13812 return PackageManager.INSTALL_FAILED_INVALID_URI; 13813 } 13814 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13815 // only allow the existing package to be used if it's installed as a full 13816 // application for at least one user 13817 boolean installAllowed = false; 13818 for (int checkUserId : sUserManager.getUserIds()) { 13819 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13820 if (installAllowed) { 13821 break; 13822 } 13823 } 13824 if (!installAllowed) { 13825 return PackageManager.INSTALL_FAILED_INVALID_URI; 13826 } 13827 } 13828 if (!pkgSetting.getInstalled(userId)) { 13829 pkgSetting.setInstalled(true, userId); 13830 pkgSetting.setHidden(false, userId); 13831 pkgSetting.setInstallReason(installReason, userId); 13832 mSettings.writePackageRestrictionsLPr(userId); 13833 mSettings.writeKernelMappingLPr(pkgSetting); 13834 installed = true; 13835 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13836 // upgrade app from instant to full; we don't allow app downgrade 13837 installed = true; 13838 } 13839 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13840 } 13841 13842 if (installed) { 13843 if (pkgSetting.pkg != null) { 13844 synchronized (mInstallLock) { 13845 // We don't need to freeze for a brand new install 13846 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13847 } 13848 } 13849 sendPackageAddedForUser(packageName, pkgSetting, userId); 13850 synchronized (mPackages) { 13851 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13852 } 13853 } 13854 } finally { 13855 Binder.restoreCallingIdentity(callingId); 13856 } 13857 13858 return PackageManager.INSTALL_SUCCEEDED; 13859 } 13860 13861 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13862 boolean instantApp, boolean fullApp) { 13863 // no state specified; do nothing 13864 if (!instantApp && !fullApp) { 13865 return; 13866 } 13867 if (userId != UserHandle.USER_ALL) { 13868 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13869 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13870 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13871 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13872 } 13873 } else { 13874 for (int currentUserId : sUserManager.getUserIds()) { 13875 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13876 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13877 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13878 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13879 } 13880 } 13881 } 13882 } 13883 13884 boolean isUserRestricted(int userId, String restrictionKey) { 13885 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13886 if (restrictions.getBoolean(restrictionKey, false)) { 13887 Log.w(TAG, "User is restricted: " + restrictionKey); 13888 return true; 13889 } 13890 return false; 13891 } 13892 13893 @Override 13894 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13895 int userId) { 13896 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13897 final int callingUid = Binder.getCallingUid(); 13898 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13899 true /* requireFullPermission */, true /* checkShell */, 13900 "setPackagesSuspended for user " + userId); 13901 13902 if (ArrayUtils.isEmpty(packageNames)) { 13903 return packageNames; 13904 } 13905 13906 // List of package names for whom the suspended state has changed. 13907 List<String> changedPackages = new ArrayList<>(packageNames.length); 13908 // List of package names for whom the suspended state is not set as requested in this 13909 // method. 13910 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13911 long callingId = Binder.clearCallingIdentity(); 13912 try { 13913 for (int i = 0; i < packageNames.length; i++) { 13914 String packageName = packageNames[i]; 13915 boolean changed = false; 13916 final int appId; 13917 synchronized (mPackages) { 13918 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13919 if (pkgSetting == null 13920 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13921 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13922 + "\". Skipping suspending/un-suspending."); 13923 unactionedPackages.add(packageName); 13924 continue; 13925 } 13926 appId = pkgSetting.appId; 13927 if (pkgSetting.getSuspended(userId) != suspended) { 13928 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13929 unactionedPackages.add(packageName); 13930 continue; 13931 } 13932 pkgSetting.setSuspended(suspended, userId); 13933 mSettings.writePackageRestrictionsLPr(userId); 13934 changed = true; 13935 changedPackages.add(packageName); 13936 } 13937 } 13938 13939 if (changed && suspended) { 13940 killApplication(packageName, UserHandle.getUid(userId, appId), 13941 "suspending package"); 13942 } 13943 } 13944 } finally { 13945 Binder.restoreCallingIdentity(callingId); 13946 } 13947 13948 if (!changedPackages.isEmpty()) { 13949 sendPackagesSuspendedForUser(changedPackages.toArray( 13950 new String[changedPackages.size()]), userId, suspended); 13951 } 13952 13953 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13954 } 13955 13956 @Override 13957 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13958 final int callingUid = Binder.getCallingUid(); 13959 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13960 true /* requireFullPermission */, false /* checkShell */, 13961 "isPackageSuspendedForUser for user " + userId); 13962 synchronized (mPackages) { 13963 final PackageSetting ps = mSettings.mPackages.get(packageName); 13964 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13965 throw new IllegalArgumentException("Unknown target package: " + packageName); 13966 } 13967 return ps.getSuspended(userId); 13968 } 13969 } 13970 13971 @GuardedBy("mPackages") 13972 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13973 if (isPackageDeviceAdmin(packageName, userId)) { 13974 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13975 + "\": has an active device admin"); 13976 return false; 13977 } 13978 13979 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13980 if (packageName.equals(activeLauncherPackageName)) { 13981 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13982 + "\": contains the active launcher"); 13983 return false; 13984 } 13985 13986 if (packageName.equals(mRequiredInstallerPackage)) { 13987 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13988 + "\": required for package installation"); 13989 return false; 13990 } 13991 13992 if (packageName.equals(mRequiredUninstallerPackage)) { 13993 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13994 + "\": required for package uninstallation"); 13995 return false; 13996 } 13997 13998 if (packageName.equals(mRequiredVerifierPackage)) { 13999 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14000 + "\": required for package verification"); 14001 return false; 14002 } 14003 14004 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14005 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14006 + "\": is the default dialer"); 14007 return false; 14008 } 14009 14010 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14011 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14012 + "\": protected package"); 14013 return false; 14014 } 14015 14016 // Cannot suspend static shared libs as they are considered 14017 // a part of the using app (emulating static linking). Also 14018 // static libs are installed always on internal storage. 14019 PackageParser.Package pkg = mPackages.get(packageName); 14020 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14021 Slog.w(TAG, "Cannot suspend package: " + packageName 14022 + " providing static shared library: " 14023 + pkg.staticSharedLibName); 14024 return false; 14025 } 14026 14027 return true; 14028 } 14029 14030 private String getActiveLauncherPackageName(int userId) { 14031 Intent intent = new Intent(Intent.ACTION_MAIN); 14032 intent.addCategory(Intent.CATEGORY_HOME); 14033 ResolveInfo resolveInfo = resolveIntent( 14034 intent, 14035 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14036 PackageManager.MATCH_DEFAULT_ONLY, 14037 userId); 14038 14039 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14040 } 14041 14042 private String getDefaultDialerPackageName(int userId) { 14043 synchronized (mPackages) { 14044 return mSettings.getDefaultDialerPackageNameLPw(userId); 14045 } 14046 } 14047 14048 @Override 14049 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14050 mContext.enforceCallingOrSelfPermission( 14051 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14052 "Only package verification agents can verify applications"); 14053 14054 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14055 final PackageVerificationResponse response = new PackageVerificationResponse( 14056 verificationCode, Binder.getCallingUid()); 14057 msg.arg1 = id; 14058 msg.obj = response; 14059 mHandler.sendMessage(msg); 14060 } 14061 14062 @Override 14063 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14064 long millisecondsToDelay) { 14065 mContext.enforceCallingOrSelfPermission( 14066 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14067 "Only package verification agents can extend verification timeouts"); 14068 14069 final PackageVerificationState state = mPendingVerification.get(id); 14070 final PackageVerificationResponse response = new PackageVerificationResponse( 14071 verificationCodeAtTimeout, Binder.getCallingUid()); 14072 14073 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14074 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14075 } 14076 if (millisecondsToDelay < 0) { 14077 millisecondsToDelay = 0; 14078 } 14079 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14080 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14081 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14082 } 14083 14084 if ((state != null) && !state.timeoutExtended()) { 14085 state.extendTimeout(); 14086 14087 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14088 msg.arg1 = id; 14089 msg.obj = response; 14090 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14091 } 14092 } 14093 14094 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14095 int verificationCode, UserHandle user) { 14096 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14097 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14098 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14099 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14100 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14101 14102 mContext.sendBroadcastAsUser(intent, user, 14103 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14104 } 14105 14106 private ComponentName matchComponentForVerifier(String packageName, 14107 List<ResolveInfo> receivers) { 14108 ActivityInfo targetReceiver = null; 14109 14110 final int NR = receivers.size(); 14111 for (int i = 0; i < NR; i++) { 14112 final ResolveInfo info = receivers.get(i); 14113 if (info.activityInfo == null) { 14114 continue; 14115 } 14116 14117 if (packageName.equals(info.activityInfo.packageName)) { 14118 targetReceiver = info.activityInfo; 14119 break; 14120 } 14121 } 14122 14123 if (targetReceiver == null) { 14124 return null; 14125 } 14126 14127 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14128 } 14129 14130 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14131 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14132 if (pkgInfo.verifiers.length == 0) { 14133 return null; 14134 } 14135 14136 final int N = pkgInfo.verifiers.length; 14137 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14138 for (int i = 0; i < N; i++) { 14139 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14140 14141 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14142 receivers); 14143 if (comp == null) { 14144 continue; 14145 } 14146 14147 final int verifierUid = getUidForVerifier(verifierInfo); 14148 if (verifierUid == -1) { 14149 continue; 14150 } 14151 14152 if (DEBUG_VERIFY) { 14153 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14154 + " with the correct signature"); 14155 } 14156 sufficientVerifiers.add(comp); 14157 verificationState.addSufficientVerifier(verifierUid); 14158 } 14159 14160 return sufficientVerifiers; 14161 } 14162 14163 private int getUidForVerifier(VerifierInfo verifierInfo) { 14164 synchronized (mPackages) { 14165 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14166 if (pkg == null) { 14167 return -1; 14168 } else if (pkg.mSigningDetails.signatures.length != 1) { 14169 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14170 + " has more than one signature; ignoring"); 14171 return -1; 14172 } 14173 14174 /* 14175 * If the public key of the package's signature does not match 14176 * our expected public key, then this is a different package and 14177 * we should skip. 14178 */ 14179 14180 final byte[] expectedPublicKey; 14181 try { 14182 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14183 final PublicKey publicKey = verifierSig.getPublicKey(); 14184 expectedPublicKey = publicKey.getEncoded(); 14185 } catch (CertificateException e) { 14186 return -1; 14187 } 14188 14189 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14190 14191 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14192 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14193 + " does not have the expected public key; ignoring"); 14194 return -1; 14195 } 14196 14197 return pkg.applicationInfo.uid; 14198 } 14199 } 14200 14201 @Override 14202 public void finishPackageInstall(int token, boolean didLaunch) { 14203 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14204 14205 if (DEBUG_INSTALL) { 14206 Slog.v(TAG, "BM finishing package install for " + token); 14207 } 14208 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14209 14210 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14211 mHandler.sendMessage(msg); 14212 } 14213 14214 /** 14215 * Get the verification agent timeout. Used for both the APK verifier and the 14216 * intent filter verifier. 14217 * 14218 * @return verification timeout in milliseconds 14219 */ 14220 private long getVerificationTimeout() { 14221 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14222 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14223 DEFAULT_VERIFICATION_TIMEOUT); 14224 } 14225 14226 /** 14227 * Get the default verification agent response code. 14228 * 14229 * @return default verification response code 14230 */ 14231 private int getDefaultVerificationResponse(UserHandle user) { 14232 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14233 return PackageManager.VERIFICATION_REJECT; 14234 } 14235 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14236 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14237 DEFAULT_VERIFICATION_RESPONSE); 14238 } 14239 14240 /** 14241 * Check whether or not package verification has been enabled. 14242 * 14243 * @return true if verification should be performed 14244 */ 14245 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14246 if (!DEFAULT_VERIFY_ENABLE) { 14247 return false; 14248 } 14249 14250 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14251 14252 // Check if installing from ADB 14253 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14254 // Do not run verification in a test harness environment 14255 if (ActivityManager.isRunningInTestHarness()) { 14256 return false; 14257 } 14258 if (ensureVerifyAppsEnabled) { 14259 return true; 14260 } 14261 // Check if the developer does not want package verification for ADB installs 14262 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14263 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14264 return false; 14265 } 14266 } else { 14267 // only when not installed from ADB, skip verification for instant apps when 14268 // the installer and verifier are the same. 14269 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14270 if (mInstantAppInstallerActivity != null 14271 && mInstantAppInstallerActivity.packageName.equals( 14272 mRequiredVerifierPackage)) { 14273 try { 14274 mContext.getSystemService(AppOpsManager.class) 14275 .checkPackage(installerUid, mRequiredVerifierPackage); 14276 if (DEBUG_VERIFY) { 14277 Slog.i(TAG, "disable verification for instant app"); 14278 } 14279 return false; 14280 } catch (SecurityException ignore) { } 14281 } 14282 } 14283 } 14284 14285 if (ensureVerifyAppsEnabled) { 14286 return true; 14287 } 14288 14289 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14290 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14291 } 14292 14293 @Override 14294 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14295 throws RemoteException { 14296 mContext.enforceCallingOrSelfPermission( 14297 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14298 "Only intentfilter verification agents can verify applications"); 14299 14300 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14301 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14302 Binder.getCallingUid(), verificationCode, failedDomains); 14303 msg.arg1 = id; 14304 msg.obj = response; 14305 mHandler.sendMessage(msg); 14306 } 14307 14308 @Override 14309 public int getIntentVerificationStatus(String packageName, int userId) { 14310 final int callingUid = Binder.getCallingUid(); 14311 if (UserHandle.getUserId(callingUid) != userId) { 14312 mContext.enforceCallingOrSelfPermission( 14313 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14314 "getIntentVerificationStatus" + userId); 14315 } 14316 if (getInstantAppPackageName(callingUid) != null) { 14317 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14318 } 14319 synchronized (mPackages) { 14320 final PackageSetting ps = mSettings.mPackages.get(packageName); 14321 if (ps == null 14322 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14323 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14324 } 14325 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14326 } 14327 } 14328 14329 @Override 14330 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14331 mContext.enforceCallingOrSelfPermission( 14332 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14333 14334 boolean result = false; 14335 synchronized (mPackages) { 14336 final PackageSetting ps = mSettings.mPackages.get(packageName); 14337 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14338 return false; 14339 } 14340 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14341 } 14342 if (result) { 14343 scheduleWritePackageRestrictionsLocked(userId); 14344 } 14345 return result; 14346 } 14347 14348 @Override 14349 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14350 String packageName) { 14351 final int callingUid = Binder.getCallingUid(); 14352 if (getInstantAppPackageName(callingUid) != null) { 14353 return ParceledListSlice.emptyList(); 14354 } 14355 synchronized (mPackages) { 14356 final PackageSetting ps = mSettings.mPackages.get(packageName); 14357 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14358 return ParceledListSlice.emptyList(); 14359 } 14360 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14361 } 14362 } 14363 14364 @Override 14365 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14366 if (TextUtils.isEmpty(packageName)) { 14367 return ParceledListSlice.emptyList(); 14368 } 14369 final int callingUid = Binder.getCallingUid(); 14370 final int callingUserId = UserHandle.getUserId(callingUid); 14371 synchronized (mPackages) { 14372 PackageParser.Package pkg = mPackages.get(packageName); 14373 if (pkg == null || pkg.activities == null) { 14374 return ParceledListSlice.emptyList(); 14375 } 14376 if (pkg.mExtras == null) { 14377 return ParceledListSlice.emptyList(); 14378 } 14379 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14380 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14381 return ParceledListSlice.emptyList(); 14382 } 14383 final int count = pkg.activities.size(); 14384 ArrayList<IntentFilter> result = new ArrayList<>(); 14385 for (int n=0; n<count; n++) { 14386 PackageParser.Activity activity = pkg.activities.get(n); 14387 if (activity.intents != null && activity.intents.size() > 0) { 14388 result.addAll(activity.intents); 14389 } 14390 } 14391 return new ParceledListSlice<>(result); 14392 } 14393 } 14394 14395 @Override 14396 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14397 mContext.enforceCallingOrSelfPermission( 14398 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14399 if (UserHandle.getCallingUserId() != userId) { 14400 mContext.enforceCallingOrSelfPermission( 14401 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14402 } 14403 14404 synchronized (mPackages) { 14405 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14406 if (packageName != null) { 14407 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14408 packageName, userId); 14409 } 14410 return result; 14411 } 14412 } 14413 14414 @Override 14415 public String getDefaultBrowserPackageName(int userId) { 14416 if (UserHandle.getCallingUserId() != userId) { 14417 mContext.enforceCallingOrSelfPermission( 14418 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14419 } 14420 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14421 return null; 14422 } 14423 synchronized (mPackages) { 14424 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14425 } 14426 } 14427 14428 /** 14429 * Get the "allow unknown sources" setting. 14430 * 14431 * @return the current "allow unknown sources" setting 14432 */ 14433 private int getUnknownSourcesSettings() { 14434 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14435 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14436 -1); 14437 } 14438 14439 @Override 14440 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14441 final int callingUid = Binder.getCallingUid(); 14442 if (getInstantAppPackageName(callingUid) != null) { 14443 return; 14444 } 14445 // writer 14446 synchronized (mPackages) { 14447 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14448 if (targetPackageSetting == null 14449 || filterAppAccessLPr( 14450 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14451 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14452 } 14453 14454 PackageSetting installerPackageSetting; 14455 if (installerPackageName != null) { 14456 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14457 if (installerPackageSetting == null) { 14458 throw new IllegalArgumentException("Unknown installer package: " 14459 + installerPackageName); 14460 } 14461 } else { 14462 installerPackageSetting = null; 14463 } 14464 14465 Signature[] callerSignature; 14466 Object obj = mSettings.getUserIdLPr(callingUid); 14467 if (obj != null) { 14468 if (obj instanceof SharedUserSetting) { 14469 callerSignature = 14470 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14471 } else if (obj instanceof PackageSetting) { 14472 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14473 } else { 14474 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14475 } 14476 } else { 14477 throw new SecurityException("Unknown calling UID: " + callingUid); 14478 } 14479 14480 // Verify: can't set installerPackageName to a package that is 14481 // not signed with the same cert as the caller. 14482 if (installerPackageSetting != null) { 14483 if (compareSignatures(callerSignature, 14484 installerPackageSetting.signatures.mSigningDetails.signatures) 14485 != PackageManager.SIGNATURE_MATCH) { 14486 throw new SecurityException( 14487 "Caller does not have same cert as new installer package " 14488 + installerPackageName); 14489 } 14490 } 14491 14492 // Verify: if target already has an installer package, it must 14493 // be signed with the same cert as the caller. 14494 if (targetPackageSetting.installerPackageName != null) { 14495 PackageSetting setting = mSettings.mPackages.get( 14496 targetPackageSetting.installerPackageName); 14497 // If the currently set package isn't valid, then it's always 14498 // okay to change it. 14499 if (setting != null) { 14500 if (compareSignatures(callerSignature, 14501 setting.signatures.mSigningDetails.signatures) 14502 != PackageManager.SIGNATURE_MATCH) { 14503 throw new SecurityException( 14504 "Caller does not have same cert as old installer package " 14505 + targetPackageSetting.installerPackageName); 14506 } 14507 } 14508 } 14509 14510 // Okay! 14511 targetPackageSetting.installerPackageName = installerPackageName; 14512 if (installerPackageName != null) { 14513 mSettings.mInstallerPackages.add(installerPackageName); 14514 } 14515 scheduleWriteSettingsLocked(); 14516 } 14517 } 14518 14519 @Override 14520 public void setApplicationCategoryHint(String packageName, int categoryHint, 14521 String callerPackageName) { 14522 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14523 throw new SecurityException("Instant applications don't have access to this method"); 14524 } 14525 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14526 callerPackageName); 14527 synchronized (mPackages) { 14528 PackageSetting ps = mSettings.mPackages.get(packageName); 14529 if (ps == null) { 14530 throw new IllegalArgumentException("Unknown target package " + packageName); 14531 } 14532 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14533 throw new IllegalArgumentException("Unknown target package " + packageName); 14534 } 14535 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14536 throw new IllegalArgumentException("Calling package " + callerPackageName 14537 + " is not installer for " + packageName); 14538 } 14539 14540 if (ps.categoryHint != categoryHint) { 14541 ps.categoryHint = categoryHint; 14542 scheduleWriteSettingsLocked(); 14543 } 14544 } 14545 } 14546 14547 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14548 // Queue up an async operation since the package installation may take a little while. 14549 mHandler.post(new Runnable() { 14550 public void run() { 14551 mHandler.removeCallbacks(this); 14552 // Result object to be returned 14553 PackageInstalledInfo res = new PackageInstalledInfo(); 14554 res.setReturnCode(currentStatus); 14555 res.uid = -1; 14556 res.pkg = null; 14557 res.removedInfo = null; 14558 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14559 args.doPreInstall(res.returnCode); 14560 synchronized (mInstallLock) { 14561 installPackageTracedLI(args, res); 14562 } 14563 args.doPostInstall(res.returnCode, res.uid); 14564 } 14565 14566 // A restore should be performed at this point if (a) the install 14567 // succeeded, (b) the operation is not an update, and (c) the new 14568 // package has not opted out of backup participation. 14569 final boolean update = res.removedInfo != null 14570 && res.removedInfo.removedPackage != null; 14571 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14572 boolean doRestore = !update 14573 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14574 14575 // Set up the post-install work request bookkeeping. This will be used 14576 // and cleaned up by the post-install event handling regardless of whether 14577 // there's a restore pass performed. Token values are >= 1. 14578 int token; 14579 if (mNextInstallToken < 0) mNextInstallToken = 1; 14580 token = mNextInstallToken++; 14581 14582 PostInstallData data = new PostInstallData(args, res); 14583 mRunningInstalls.put(token, data); 14584 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14585 14586 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14587 // Pass responsibility to the Backup Manager. It will perform a 14588 // restore if appropriate, then pass responsibility back to the 14589 // Package Manager to run the post-install observer callbacks 14590 // and broadcasts. 14591 IBackupManager bm = IBackupManager.Stub.asInterface( 14592 ServiceManager.getService(Context.BACKUP_SERVICE)); 14593 if (bm != null) { 14594 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14595 + " to BM for possible restore"); 14596 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14597 try { 14598 // TODO: http://b/22388012 14599 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14600 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14601 } else { 14602 doRestore = false; 14603 } 14604 } catch (RemoteException e) { 14605 // can't happen; the backup manager is local 14606 } catch (Exception e) { 14607 Slog.e(TAG, "Exception trying to enqueue restore", e); 14608 doRestore = false; 14609 } 14610 } else { 14611 Slog.e(TAG, "Backup Manager not found!"); 14612 doRestore = false; 14613 } 14614 } 14615 14616 if (!doRestore) { 14617 // No restore possible, or the Backup Manager was mysteriously not 14618 // available -- just fire the post-install work request directly. 14619 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14620 14621 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14622 14623 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14624 mHandler.sendMessage(msg); 14625 } 14626 } 14627 }); 14628 } 14629 14630 /** 14631 * Callback from PackageSettings whenever an app is first transitioned out of the 14632 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14633 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14634 * here whether the app is the target of an ongoing install, and only send the 14635 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14636 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14637 * handling. 14638 */ 14639 void notifyFirstLaunch(final String packageName, final String installerPackage, 14640 final int userId) { 14641 // Serialize this with the rest of the install-process message chain. In the 14642 // restore-at-install case, this Runnable will necessarily run before the 14643 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14644 // are coherent. In the non-restore case, the app has already completed install 14645 // and been launched through some other means, so it is not in a problematic 14646 // state for observers to see the FIRST_LAUNCH signal. 14647 mHandler.post(new Runnable() { 14648 @Override 14649 public void run() { 14650 for (int i = 0; i < mRunningInstalls.size(); i++) { 14651 final PostInstallData data = mRunningInstalls.valueAt(i); 14652 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14653 continue; 14654 } 14655 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14656 // right package; but is it for the right user? 14657 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14658 if (userId == data.res.newUsers[uIndex]) { 14659 if (DEBUG_BACKUP) { 14660 Slog.i(TAG, "Package " + packageName 14661 + " being restored so deferring FIRST_LAUNCH"); 14662 } 14663 return; 14664 } 14665 } 14666 } 14667 } 14668 // didn't find it, so not being restored 14669 if (DEBUG_BACKUP) { 14670 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14671 } 14672 final boolean isInstantApp = isInstantApp(packageName, userId); 14673 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14674 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14675 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14676 } 14677 }); 14678 } 14679 14680 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14681 int[] userIds, int[] instantUserIds) { 14682 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14683 installerPkg, null, userIds, instantUserIds); 14684 } 14685 14686 private abstract class HandlerParams { 14687 private static final int MAX_RETRIES = 4; 14688 14689 /** 14690 * Number of times startCopy() has been attempted and had a non-fatal 14691 * error. 14692 */ 14693 private int mRetries = 0; 14694 14695 /** User handle for the user requesting the information or installation. */ 14696 private final UserHandle mUser; 14697 String traceMethod; 14698 int traceCookie; 14699 14700 HandlerParams(UserHandle user) { 14701 mUser = user; 14702 } 14703 14704 UserHandle getUser() { 14705 return mUser; 14706 } 14707 14708 HandlerParams setTraceMethod(String traceMethod) { 14709 this.traceMethod = traceMethod; 14710 return this; 14711 } 14712 14713 HandlerParams setTraceCookie(int traceCookie) { 14714 this.traceCookie = traceCookie; 14715 return this; 14716 } 14717 14718 final boolean startCopy() { 14719 boolean res; 14720 try { 14721 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14722 14723 if (++mRetries > MAX_RETRIES) { 14724 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14725 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14726 handleServiceError(); 14727 return false; 14728 } else { 14729 handleStartCopy(); 14730 res = true; 14731 } 14732 } catch (RemoteException e) { 14733 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14734 mHandler.sendEmptyMessage(MCS_RECONNECT); 14735 res = false; 14736 } 14737 handleReturnCode(); 14738 return res; 14739 } 14740 14741 final void serviceError() { 14742 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14743 handleServiceError(); 14744 handleReturnCode(); 14745 } 14746 14747 abstract void handleStartCopy() throws RemoteException; 14748 abstract void handleServiceError(); 14749 abstract void handleReturnCode(); 14750 } 14751 14752 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14753 for (File path : paths) { 14754 try { 14755 mcs.clearDirectory(path.getAbsolutePath()); 14756 } catch (RemoteException e) { 14757 } 14758 } 14759 } 14760 14761 static class OriginInfo { 14762 /** 14763 * Location where install is coming from, before it has been 14764 * copied/renamed into place. This could be a single monolithic APK 14765 * file, or a cluster directory. This location may be untrusted. 14766 */ 14767 final File file; 14768 14769 /** 14770 * Flag indicating that {@link #file} or {@link #cid} has already been 14771 * staged, meaning downstream users don't need to defensively copy the 14772 * contents. 14773 */ 14774 final boolean staged; 14775 14776 /** 14777 * Flag indicating that {@link #file} or {@link #cid} is an already 14778 * installed app that is being moved. 14779 */ 14780 final boolean existing; 14781 14782 final String resolvedPath; 14783 final File resolvedFile; 14784 14785 static OriginInfo fromNothing() { 14786 return new OriginInfo(null, false, false); 14787 } 14788 14789 static OriginInfo fromUntrustedFile(File file) { 14790 return new OriginInfo(file, false, false); 14791 } 14792 14793 static OriginInfo fromExistingFile(File file) { 14794 return new OriginInfo(file, false, true); 14795 } 14796 14797 static OriginInfo fromStagedFile(File file) { 14798 return new OriginInfo(file, true, false); 14799 } 14800 14801 private OriginInfo(File file, boolean staged, boolean existing) { 14802 this.file = file; 14803 this.staged = staged; 14804 this.existing = existing; 14805 14806 if (file != null) { 14807 resolvedPath = file.getAbsolutePath(); 14808 resolvedFile = file; 14809 } else { 14810 resolvedPath = null; 14811 resolvedFile = null; 14812 } 14813 } 14814 } 14815 14816 static class MoveInfo { 14817 final int moveId; 14818 final String fromUuid; 14819 final String toUuid; 14820 final String packageName; 14821 final String dataAppName; 14822 final int appId; 14823 final String seinfo; 14824 final int targetSdkVersion; 14825 14826 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14827 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14828 this.moveId = moveId; 14829 this.fromUuid = fromUuid; 14830 this.toUuid = toUuid; 14831 this.packageName = packageName; 14832 this.dataAppName = dataAppName; 14833 this.appId = appId; 14834 this.seinfo = seinfo; 14835 this.targetSdkVersion = targetSdkVersion; 14836 } 14837 } 14838 14839 static class VerificationInfo { 14840 /** A constant used to indicate that a uid value is not present. */ 14841 public static final int NO_UID = -1; 14842 14843 /** URI referencing where the package was downloaded from. */ 14844 final Uri originatingUri; 14845 14846 /** HTTP referrer URI associated with the originatingURI. */ 14847 final Uri referrer; 14848 14849 /** UID of the application that the install request originated from. */ 14850 final int originatingUid; 14851 14852 /** UID of application requesting the install */ 14853 final int installerUid; 14854 14855 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14856 this.originatingUri = originatingUri; 14857 this.referrer = referrer; 14858 this.originatingUid = originatingUid; 14859 this.installerUid = installerUid; 14860 } 14861 } 14862 14863 class InstallParams extends HandlerParams { 14864 final OriginInfo origin; 14865 final MoveInfo move; 14866 final IPackageInstallObserver2 observer; 14867 int installFlags; 14868 final String installerPackageName; 14869 final String volumeUuid; 14870 private InstallArgs mArgs; 14871 private int mRet; 14872 final String packageAbiOverride; 14873 final String[] grantedRuntimePermissions; 14874 final VerificationInfo verificationInfo; 14875 final PackageParser.SigningDetails signingDetails; 14876 final int installReason; 14877 14878 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14879 int installFlags, String installerPackageName, String volumeUuid, 14880 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14881 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14882 super(user); 14883 this.origin = origin; 14884 this.move = move; 14885 this.observer = observer; 14886 this.installFlags = installFlags; 14887 this.installerPackageName = installerPackageName; 14888 this.volumeUuid = volumeUuid; 14889 this.verificationInfo = verificationInfo; 14890 this.packageAbiOverride = packageAbiOverride; 14891 this.grantedRuntimePermissions = grantedPermissions; 14892 this.signingDetails = signingDetails; 14893 this.installReason = installReason; 14894 } 14895 14896 @Override 14897 public String toString() { 14898 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14899 + " file=" + origin.file + "}"; 14900 } 14901 14902 private int installLocationPolicy(PackageInfoLite pkgLite) { 14903 String packageName = pkgLite.packageName; 14904 int installLocation = pkgLite.installLocation; 14905 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14906 // reader 14907 synchronized (mPackages) { 14908 // Currently installed package which the new package is attempting to replace or 14909 // null if no such package is installed. 14910 PackageParser.Package installedPkg = mPackages.get(packageName); 14911 // Package which currently owns the data which the new package will own if installed. 14912 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14913 // will be null whereas dataOwnerPkg will contain information about the package 14914 // which was uninstalled while keeping its data. 14915 PackageParser.Package dataOwnerPkg = installedPkg; 14916 if (dataOwnerPkg == null) { 14917 PackageSetting ps = mSettings.mPackages.get(packageName); 14918 if (ps != null) { 14919 dataOwnerPkg = ps.pkg; 14920 } 14921 } 14922 14923 if (dataOwnerPkg != null) { 14924 // If installed, the package will get access to data left on the device by its 14925 // predecessor. As a security measure, this is permited only if this is not a 14926 // version downgrade or if the predecessor package is marked as debuggable and 14927 // a downgrade is explicitly requested. 14928 // 14929 // On debuggable platform builds, downgrades are permitted even for 14930 // non-debuggable packages to make testing easier. Debuggable platform builds do 14931 // not offer security guarantees and thus it's OK to disable some security 14932 // mechanisms to make debugging/testing easier on those builds. However, even on 14933 // debuggable builds downgrades of packages are permitted only if requested via 14934 // installFlags. This is because we aim to keep the behavior of debuggable 14935 // platform builds as close as possible to the behavior of non-debuggable 14936 // platform builds. 14937 final boolean downgradeRequested = 14938 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14939 final boolean packageDebuggable = 14940 (dataOwnerPkg.applicationInfo.flags 14941 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14942 final boolean downgradePermitted = 14943 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14944 if (!downgradePermitted) { 14945 try { 14946 checkDowngrade(dataOwnerPkg, pkgLite); 14947 } catch (PackageManagerException e) { 14948 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14949 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14950 } 14951 } 14952 } 14953 14954 if (installedPkg != null) { 14955 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14956 // Check for updated system application. 14957 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14958 if (onSd) { 14959 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14960 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14961 } 14962 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14963 } else { 14964 if (onSd) { 14965 // Install flag overrides everything. 14966 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14967 } 14968 // If current upgrade specifies particular preference 14969 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14970 // Application explicitly specified internal. 14971 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14972 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14973 // App explictly prefers external. Let policy decide 14974 } else { 14975 // Prefer previous location 14976 if (isExternal(installedPkg)) { 14977 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14978 } 14979 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14980 } 14981 } 14982 } else { 14983 // Invalid install. Return error code 14984 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14985 } 14986 } 14987 } 14988 // All the special cases have been taken care of. 14989 // Return result based on recommended install location. 14990 if (onSd) { 14991 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14992 } 14993 return pkgLite.recommendedInstallLocation; 14994 } 14995 14996 /* 14997 * Invoke remote method to get package information and install 14998 * location values. Override install location based on default 14999 * policy if needed and then create install arguments based 15000 * on the install location. 15001 */ 15002 public void handleStartCopy() throws RemoteException { 15003 int ret = PackageManager.INSTALL_SUCCEEDED; 15004 15005 // If we're already staged, we've firmly committed to an install location 15006 if (origin.staged) { 15007 if (origin.file != null) { 15008 installFlags |= PackageManager.INSTALL_INTERNAL; 15009 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15010 } else { 15011 throw new IllegalStateException("Invalid stage location"); 15012 } 15013 } 15014 15015 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15016 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15017 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15018 PackageInfoLite pkgLite = null; 15019 15020 if (onInt && onSd) { 15021 // Check if both bits are set. 15022 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15023 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15024 } else if (onSd && ephemeral) { 15025 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15026 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15027 } else { 15028 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15029 packageAbiOverride); 15030 15031 if (DEBUG_INSTANT && ephemeral) { 15032 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15033 } 15034 15035 /* 15036 * If we have too little free space, try to free cache 15037 * before giving up. 15038 */ 15039 if (!origin.staged && pkgLite.recommendedInstallLocation 15040 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15041 // TODO: focus freeing disk space on the target device 15042 final StorageManager storage = StorageManager.from(mContext); 15043 final long lowThreshold = storage.getStorageLowBytes( 15044 Environment.getDataDirectory()); 15045 15046 final long sizeBytes = mContainerService.calculateInstalledSize( 15047 origin.resolvedPath, packageAbiOverride); 15048 15049 try { 15050 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15051 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15052 installFlags, packageAbiOverride); 15053 } catch (InstallerException e) { 15054 Slog.w(TAG, "Failed to free cache", e); 15055 } 15056 15057 /* 15058 * The cache free must have deleted the file we 15059 * downloaded to install. 15060 * 15061 * TODO: fix the "freeCache" call to not delete 15062 * the file we care about. 15063 */ 15064 if (pkgLite.recommendedInstallLocation 15065 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15066 pkgLite.recommendedInstallLocation 15067 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15068 } 15069 } 15070 } 15071 15072 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15073 int loc = pkgLite.recommendedInstallLocation; 15074 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15075 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15076 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15077 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15078 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15079 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15080 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15081 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15082 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15083 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15084 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15085 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15086 } else { 15087 // Override with defaults if needed. 15088 loc = installLocationPolicy(pkgLite); 15089 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15090 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15091 } else if (!onSd && !onInt) { 15092 // Override install location with flags 15093 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15094 // Set the flag to install on external media. 15095 installFlags |= PackageManager.INSTALL_EXTERNAL; 15096 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15097 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15098 if (DEBUG_INSTANT) { 15099 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15100 } 15101 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15102 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15103 |PackageManager.INSTALL_INTERNAL); 15104 } else { 15105 // Make sure the flag for installing on external 15106 // media is unset 15107 installFlags |= PackageManager.INSTALL_INTERNAL; 15108 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15109 } 15110 } 15111 } 15112 } 15113 15114 final InstallArgs args = createInstallArgs(this); 15115 mArgs = args; 15116 15117 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15118 // TODO: http://b/22976637 15119 // Apps installed for "all" users use the device owner to verify the app 15120 UserHandle verifierUser = getUser(); 15121 if (verifierUser == UserHandle.ALL) { 15122 verifierUser = UserHandle.SYSTEM; 15123 } 15124 15125 /* 15126 * Determine if we have any installed package verifiers. If we 15127 * do, then we'll defer to them to verify the packages. 15128 */ 15129 final int requiredUid = mRequiredVerifierPackage == null ? -1 15130 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15131 verifierUser.getIdentifier()); 15132 final int installerUid = 15133 verificationInfo == null ? -1 : verificationInfo.installerUid; 15134 if (!origin.existing && requiredUid != -1 15135 && isVerificationEnabled( 15136 verifierUser.getIdentifier(), installFlags, installerUid)) { 15137 final Intent verification = new Intent( 15138 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15139 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15140 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15141 PACKAGE_MIME_TYPE); 15142 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15143 15144 // Query all live verifiers based on current user state 15145 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15146 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15147 false /*allowDynamicSplits*/); 15148 15149 if (DEBUG_VERIFY) { 15150 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15151 + verification.toString() + " with " + pkgLite.verifiers.length 15152 + " optional verifiers"); 15153 } 15154 15155 final int verificationId = mPendingVerificationToken++; 15156 15157 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15158 15159 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15160 installerPackageName); 15161 15162 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15163 installFlags); 15164 15165 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15166 pkgLite.packageName); 15167 15168 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15169 pkgLite.versionCode); 15170 15171 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15172 pkgLite.getLongVersionCode()); 15173 15174 if (verificationInfo != null) { 15175 if (verificationInfo.originatingUri != null) { 15176 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15177 verificationInfo.originatingUri); 15178 } 15179 if (verificationInfo.referrer != null) { 15180 verification.putExtra(Intent.EXTRA_REFERRER, 15181 verificationInfo.referrer); 15182 } 15183 if (verificationInfo.originatingUid >= 0) { 15184 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15185 verificationInfo.originatingUid); 15186 } 15187 if (verificationInfo.installerUid >= 0) { 15188 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15189 verificationInfo.installerUid); 15190 } 15191 } 15192 15193 final PackageVerificationState verificationState = new PackageVerificationState( 15194 requiredUid, args); 15195 15196 mPendingVerification.append(verificationId, verificationState); 15197 15198 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15199 receivers, verificationState); 15200 15201 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15202 final long idleDuration = getVerificationTimeout(); 15203 15204 /* 15205 * If any sufficient verifiers were listed in the package 15206 * manifest, attempt to ask them. 15207 */ 15208 if (sufficientVerifiers != null) { 15209 final int N = sufficientVerifiers.size(); 15210 if (N == 0) { 15211 Slog.i(TAG, "Additional verifiers required, but none installed."); 15212 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15213 } else { 15214 for (int i = 0; i < N; i++) { 15215 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15216 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15217 verifierComponent.getPackageName(), idleDuration, 15218 verifierUser.getIdentifier(), false, "package verifier"); 15219 15220 final Intent sufficientIntent = new Intent(verification); 15221 sufficientIntent.setComponent(verifierComponent); 15222 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15223 } 15224 } 15225 } 15226 15227 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15228 mRequiredVerifierPackage, receivers); 15229 if (ret == PackageManager.INSTALL_SUCCEEDED 15230 && mRequiredVerifierPackage != null) { 15231 Trace.asyncTraceBegin( 15232 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15233 /* 15234 * Send the intent to the required verification agent, 15235 * but only start the verification timeout after the 15236 * target BroadcastReceivers have run. 15237 */ 15238 verification.setComponent(requiredVerifierComponent); 15239 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15240 mRequiredVerifierPackage, idleDuration, 15241 verifierUser.getIdentifier(), false, "package verifier"); 15242 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15243 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15244 new BroadcastReceiver() { 15245 @Override 15246 public void onReceive(Context context, Intent intent) { 15247 final Message msg = mHandler 15248 .obtainMessage(CHECK_PENDING_VERIFICATION); 15249 msg.arg1 = verificationId; 15250 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15251 } 15252 }, null, 0, null, null); 15253 15254 /* 15255 * We don't want the copy to proceed until verification 15256 * succeeds, so null out this field. 15257 */ 15258 mArgs = null; 15259 } 15260 } else { 15261 /* 15262 * No package verification is enabled, so immediately start 15263 * the remote call to initiate copy using temporary file. 15264 */ 15265 ret = args.copyApk(mContainerService, true); 15266 } 15267 } 15268 15269 mRet = ret; 15270 } 15271 15272 @Override 15273 void handleReturnCode() { 15274 // If mArgs is null, then MCS couldn't be reached. When it 15275 // reconnects, it will try again to install. At that point, this 15276 // will succeed. 15277 if (mArgs != null) { 15278 processPendingInstall(mArgs, mRet); 15279 } 15280 } 15281 15282 @Override 15283 void handleServiceError() { 15284 mArgs = createInstallArgs(this); 15285 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15286 } 15287 } 15288 15289 private InstallArgs createInstallArgs(InstallParams params) { 15290 if (params.move != null) { 15291 return new MoveInstallArgs(params); 15292 } else { 15293 return new FileInstallArgs(params); 15294 } 15295 } 15296 15297 /** 15298 * Create args that describe an existing installed package. Typically used 15299 * when cleaning up old installs, or used as a move source. 15300 */ 15301 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15302 String resourcePath, String[] instructionSets) { 15303 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15304 } 15305 15306 static abstract class InstallArgs { 15307 /** @see InstallParams#origin */ 15308 final OriginInfo origin; 15309 /** @see InstallParams#move */ 15310 final MoveInfo move; 15311 15312 final IPackageInstallObserver2 observer; 15313 // Always refers to PackageManager flags only 15314 final int installFlags; 15315 final String installerPackageName; 15316 final String volumeUuid; 15317 final UserHandle user; 15318 final String abiOverride; 15319 final String[] installGrantPermissions; 15320 /** If non-null, drop an async trace when the install completes */ 15321 final String traceMethod; 15322 final int traceCookie; 15323 final PackageParser.SigningDetails signingDetails; 15324 final int installReason; 15325 15326 // The list of instruction sets supported by this app. This is currently 15327 // only used during the rmdex() phase to clean up resources. We can get rid of this 15328 // if we move dex files under the common app path. 15329 /* nullable */ String[] instructionSets; 15330 15331 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15332 int installFlags, String installerPackageName, String volumeUuid, 15333 UserHandle user, String[] instructionSets, 15334 String abiOverride, String[] installGrantPermissions, 15335 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15336 int installReason) { 15337 this.origin = origin; 15338 this.move = move; 15339 this.installFlags = installFlags; 15340 this.observer = observer; 15341 this.installerPackageName = installerPackageName; 15342 this.volumeUuid = volumeUuid; 15343 this.user = user; 15344 this.instructionSets = instructionSets; 15345 this.abiOverride = abiOverride; 15346 this.installGrantPermissions = installGrantPermissions; 15347 this.traceMethod = traceMethod; 15348 this.traceCookie = traceCookie; 15349 this.signingDetails = signingDetails; 15350 this.installReason = installReason; 15351 } 15352 15353 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15354 abstract int doPreInstall(int status); 15355 15356 /** 15357 * Rename package into final resting place. All paths on the given 15358 * scanned package should be updated to reflect the rename. 15359 */ 15360 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15361 abstract int doPostInstall(int status, int uid); 15362 15363 /** @see PackageSettingBase#codePathString */ 15364 abstract String getCodePath(); 15365 /** @see PackageSettingBase#resourcePathString */ 15366 abstract String getResourcePath(); 15367 15368 // Need installer lock especially for dex file removal. 15369 abstract void cleanUpResourcesLI(); 15370 abstract boolean doPostDeleteLI(boolean delete); 15371 15372 /** 15373 * Called before the source arguments are copied. This is used mostly 15374 * for MoveParams when it needs to read the source file to put it in the 15375 * destination. 15376 */ 15377 int doPreCopy() { 15378 return PackageManager.INSTALL_SUCCEEDED; 15379 } 15380 15381 /** 15382 * Called after the source arguments are copied. This is used mostly for 15383 * MoveParams when it needs to read the source file to put it in the 15384 * destination. 15385 */ 15386 int doPostCopy(int uid) { 15387 return PackageManager.INSTALL_SUCCEEDED; 15388 } 15389 15390 protected boolean isFwdLocked() { 15391 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15392 } 15393 15394 protected boolean isExternalAsec() { 15395 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15396 } 15397 15398 protected boolean isEphemeral() { 15399 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15400 } 15401 15402 UserHandle getUser() { 15403 return user; 15404 } 15405 } 15406 15407 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15408 if (!allCodePaths.isEmpty()) { 15409 if (instructionSets == null) { 15410 throw new IllegalStateException("instructionSet == null"); 15411 } 15412 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15413 for (String codePath : allCodePaths) { 15414 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15415 try { 15416 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15417 } catch (InstallerException ignored) { 15418 } 15419 } 15420 } 15421 } 15422 } 15423 15424 /** 15425 * Logic to handle installation of non-ASEC applications, including copying 15426 * and renaming logic. 15427 */ 15428 class FileInstallArgs extends InstallArgs { 15429 private File codeFile; 15430 private File resourceFile; 15431 15432 // Example topology: 15433 // /data/app/com.example/base.apk 15434 // /data/app/com.example/split_foo.apk 15435 // /data/app/com.example/lib/arm/libfoo.so 15436 // /data/app/com.example/lib/arm64/libfoo.so 15437 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15438 15439 /** New install */ 15440 FileInstallArgs(InstallParams params) { 15441 super(params.origin, params.move, params.observer, params.installFlags, 15442 params.installerPackageName, params.volumeUuid, 15443 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15444 params.grantedRuntimePermissions, 15445 params.traceMethod, params.traceCookie, params.signingDetails, 15446 params.installReason); 15447 if (isFwdLocked()) { 15448 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15449 } 15450 } 15451 15452 /** Existing install */ 15453 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15454 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15455 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15456 PackageManager.INSTALL_REASON_UNKNOWN); 15457 this.codeFile = (codePath != null) ? new File(codePath) : null; 15458 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15459 } 15460 15461 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15462 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15463 try { 15464 return doCopyApk(imcs, temp); 15465 } finally { 15466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15467 } 15468 } 15469 15470 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15471 if (origin.staged) { 15472 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15473 codeFile = origin.file; 15474 resourceFile = origin.file; 15475 return PackageManager.INSTALL_SUCCEEDED; 15476 } 15477 15478 try { 15479 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15480 final File tempDir = 15481 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15482 codeFile = tempDir; 15483 resourceFile = tempDir; 15484 } catch (IOException e) { 15485 Slog.w(TAG, "Failed to create copy file: " + e); 15486 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15487 } 15488 15489 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15490 @Override 15491 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15492 if (!FileUtils.isValidExtFilename(name)) { 15493 throw new IllegalArgumentException("Invalid filename: " + name); 15494 } 15495 try { 15496 final File file = new File(codeFile, name); 15497 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15498 O_RDWR | O_CREAT, 0644); 15499 Os.chmod(file.getAbsolutePath(), 0644); 15500 return new ParcelFileDescriptor(fd); 15501 } catch (ErrnoException e) { 15502 throw new RemoteException("Failed to open: " + e.getMessage()); 15503 } 15504 } 15505 }; 15506 15507 int ret = PackageManager.INSTALL_SUCCEEDED; 15508 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15509 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15510 Slog.e(TAG, "Failed to copy package"); 15511 return ret; 15512 } 15513 15514 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15515 NativeLibraryHelper.Handle handle = null; 15516 try { 15517 handle = NativeLibraryHelper.Handle.create(codeFile); 15518 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15519 abiOverride); 15520 } catch (IOException e) { 15521 Slog.e(TAG, "Copying native libraries failed", e); 15522 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15523 } finally { 15524 IoUtils.closeQuietly(handle); 15525 } 15526 15527 return ret; 15528 } 15529 15530 int doPreInstall(int status) { 15531 if (status != PackageManager.INSTALL_SUCCEEDED) { 15532 cleanUp(); 15533 } 15534 return status; 15535 } 15536 15537 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15538 if (status != PackageManager.INSTALL_SUCCEEDED) { 15539 cleanUp(); 15540 return false; 15541 } 15542 15543 final File targetDir = codeFile.getParentFile(); 15544 final File beforeCodeFile = codeFile; 15545 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15546 15547 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15548 try { 15549 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15550 } catch (ErrnoException e) { 15551 Slog.w(TAG, "Failed to rename", e); 15552 return false; 15553 } 15554 15555 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15556 Slog.w(TAG, "Failed to restorecon"); 15557 return false; 15558 } 15559 15560 // Reflect the rename internally 15561 codeFile = afterCodeFile; 15562 resourceFile = afterCodeFile; 15563 15564 // Reflect the rename in scanned details 15565 try { 15566 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15567 } catch (IOException e) { 15568 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15569 return false; 15570 } 15571 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15572 afterCodeFile, pkg.baseCodePath)); 15573 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15574 afterCodeFile, pkg.splitCodePaths)); 15575 15576 // Reflect the rename in app info 15577 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15578 pkg.setApplicationInfoCodePath(pkg.codePath); 15579 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15580 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15581 pkg.setApplicationInfoResourcePath(pkg.codePath); 15582 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15583 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15584 15585 return true; 15586 } 15587 15588 int doPostInstall(int status, int uid) { 15589 if (status != PackageManager.INSTALL_SUCCEEDED) { 15590 cleanUp(); 15591 } 15592 return status; 15593 } 15594 15595 @Override 15596 String getCodePath() { 15597 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15598 } 15599 15600 @Override 15601 String getResourcePath() { 15602 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15603 } 15604 15605 private boolean cleanUp() { 15606 if (codeFile == null || !codeFile.exists()) { 15607 return false; 15608 } 15609 15610 removeCodePathLI(codeFile); 15611 15612 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15613 resourceFile.delete(); 15614 } 15615 15616 return true; 15617 } 15618 15619 void cleanUpResourcesLI() { 15620 // Try enumerating all code paths before deleting 15621 List<String> allCodePaths = Collections.EMPTY_LIST; 15622 if (codeFile != null && codeFile.exists()) { 15623 try { 15624 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15625 allCodePaths = pkg.getAllCodePaths(); 15626 } catch (PackageParserException e) { 15627 // Ignored; we tried our best 15628 } 15629 } 15630 15631 cleanUp(); 15632 removeDexFiles(allCodePaths, instructionSets); 15633 } 15634 15635 boolean doPostDeleteLI(boolean delete) { 15636 // XXX err, shouldn't we respect the delete flag? 15637 cleanUpResourcesLI(); 15638 return true; 15639 } 15640 } 15641 15642 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15643 PackageManagerException { 15644 if (copyRet < 0) { 15645 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15646 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15647 throw new PackageManagerException(copyRet, message); 15648 } 15649 } 15650 } 15651 15652 /** 15653 * Extract the StorageManagerService "container ID" from the full code path of an 15654 * .apk. 15655 */ 15656 static String cidFromCodePath(String fullCodePath) { 15657 int eidx = fullCodePath.lastIndexOf("/"); 15658 String subStr1 = fullCodePath.substring(0, eidx); 15659 int sidx = subStr1.lastIndexOf("/"); 15660 return subStr1.substring(sidx+1, eidx); 15661 } 15662 15663 /** 15664 * Logic to handle movement of existing installed applications. 15665 */ 15666 class MoveInstallArgs extends InstallArgs { 15667 private File codeFile; 15668 private File resourceFile; 15669 15670 /** New install */ 15671 MoveInstallArgs(InstallParams params) { 15672 super(params.origin, params.move, params.observer, params.installFlags, 15673 params.installerPackageName, params.volumeUuid, 15674 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15675 params.grantedRuntimePermissions, 15676 params.traceMethod, params.traceCookie, params.signingDetails, 15677 params.installReason); 15678 } 15679 15680 int copyApk(IMediaContainerService imcs, boolean temp) { 15681 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15682 + move.fromUuid + " to " + move.toUuid); 15683 synchronized (mInstaller) { 15684 try { 15685 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15686 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15687 } catch (InstallerException e) { 15688 Slog.w(TAG, "Failed to move app", e); 15689 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15690 } 15691 } 15692 15693 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15694 resourceFile = codeFile; 15695 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15696 15697 return PackageManager.INSTALL_SUCCEEDED; 15698 } 15699 15700 int doPreInstall(int status) { 15701 if (status != PackageManager.INSTALL_SUCCEEDED) { 15702 cleanUp(move.toUuid); 15703 } 15704 return status; 15705 } 15706 15707 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15708 if (status != PackageManager.INSTALL_SUCCEEDED) { 15709 cleanUp(move.toUuid); 15710 return false; 15711 } 15712 15713 // Reflect the move in app info 15714 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15715 pkg.setApplicationInfoCodePath(pkg.codePath); 15716 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15717 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15718 pkg.setApplicationInfoResourcePath(pkg.codePath); 15719 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15720 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15721 15722 return true; 15723 } 15724 15725 int doPostInstall(int status, int uid) { 15726 if (status == PackageManager.INSTALL_SUCCEEDED) { 15727 cleanUp(move.fromUuid); 15728 } else { 15729 cleanUp(move.toUuid); 15730 } 15731 return status; 15732 } 15733 15734 @Override 15735 String getCodePath() { 15736 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15737 } 15738 15739 @Override 15740 String getResourcePath() { 15741 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15742 } 15743 15744 private boolean cleanUp(String volumeUuid) { 15745 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15746 move.dataAppName); 15747 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15748 final int[] userIds = sUserManager.getUserIds(); 15749 synchronized (mInstallLock) { 15750 // Clean up both app data and code 15751 // All package moves are frozen until finished 15752 for (int userId : userIds) { 15753 try { 15754 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15755 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15756 } catch (InstallerException e) { 15757 Slog.w(TAG, String.valueOf(e)); 15758 } 15759 } 15760 removeCodePathLI(codeFile); 15761 } 15762 return true; 15763 } 15764 15765 void cleanUpResourcesLI() { 15766 throw new UnsupportedOperationException(); 15767 } 15768 15769 boolean doPostDeleteLI(boolean delete) { 15770 throw new UnsupportedOperationException(); 15771 } 15772 } 15773 15774 static String getAsecPackageName(String packageCid) { 15775 int idx = packageCid.lastIndexOf("-"); 15776 if (idx == -1) { 15777 return packageCid; 15778 } 15779 return packageCid.substring(0, idx); 15780 } 15781 15782 // Utility method used to create code paths based on package name and available index. 15783 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15784 String idxStr = ""; 15785 int idx = 1; 15786 // Fall back to default value of idx=1 if prefix is not 15787 // part of oldCodePath 15788 if (oldCodePath != null) { 15789 String subStr = oldCodePath; 15790 // Drop the suffix right away 15791 if (suffix != null && subStr.endsWith(suffix)) { 15792 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15793 } 15794 // If oldCodePath already contains prefix find out the 15795 // ending index to either increment or decrement. 15796 int sidx = subStr.lastIndexOf(prefix); 15797 if (sidx != -1) { 15798 subStr = subStr.substring(sidx + prefix.length()); 15799 if (subStr != null) { 15800 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15801 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15802 } 15803 try { 15804 idx = Integer.parseInt(subStr); 15805 if (idx <= 1) { 15806 idx++; 15807 } else { 15808 idx--; 15809 } 15810 } catch(NumberFormatException e) { 15811 } 15812 } 15813 } 15814 } 15815 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15816 return prefix + idxStr; 15817 } 15818 15819 private File getNextCodePath(File targetDir, String packageName) { 15820 File result; 15821 SecureRandom random = new SecureRandom(); 15822 byte[] bytes = new byte[16]; 15823 do { 15824 random.nextBytes(bytes); 15825 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15826 result = new File(targetDir, packageName + "-" + suffix); 15827 } while (result.exists()); 15828 return result; 15829 } 15830 15831 // Utility method that returns the relative package path with respect 15832 // to the installation directory. Like say for /data/data/com.test-1.apk 15833 // string com.test-1 is returned. 15834 static String deriveCodePathName(String codePath) { 15835 if (codePath == null) { 15836 return null; 15837 } 15838 final File codeFile = new File(codePath); 15839 final String name = codeFile.getName(); 15840 if (codeFile.isDirectory()) { 15841 return name; 15842 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15843 final int lastDot = name.lastIndexOf('.'); 15844 return name.substring(0, lastDot); 15845 } else { 15846 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15847 return null; 15848 } 15849 } 15850 15851 static class PackageInstalledInfo { 15852 String name; 15853 int uid; 15854 // The set of users that originally had this package installed. 15855 int[] origUsers; 15856 // The set of users that now have this package installed. 15857 int[] newUsers; 15858 PackageParser.Package pkg; 15859 int returnCode; 15860 String returnMsg; 15861 String installerPackageName; 15862 PackageRemovedInfo removedInfo; 15863 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15864 15865 public void setError(int code, String msg) { 15866 setReturnCode(code); 15867 setReturnMessage(msg); 15868 Slog.w(TAG, msg); 15869 } 15870 15871 public void setError(String msg, PackageParserException e) { 15872 setReturnCode(e.error); 15873 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15874 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15875 for (int i = 0; i < childCount; i++) { 15876 addedChildPackages.valueAt(i).setError(msg, e); 15877 } 15878 Slog.w(TAG, msg, e); 15879 } 15880 15881 public void setError(String msg, PackageManagerException e) { 15882 returnCode = e.error; 15883 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15884 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15885 for (int i = 0; i < childCount; i++) { 15886 addedChildPackages.valueAt(i).setError(msg, e); 15887 } 15888 Slog.w(TAG, msg, e); 15889 } 15890 15891 public void setReturnCode(int returnCode) { 15892 this.returnCode = returnCode; 15893 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15894 for (int i = 0; i < childCount; i++) { 15895 addedChildPackages.valueAt(i).returnCode = returnCode; 15896 } 15897 } 15898 15899 private void setReturnMessage(String returnMsg) { 15900 this.returnMsg = returnMsg; 15901 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15902 for (int i = 0; i < childCount; i++) { 15903 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15904 } 15905 } 15906 15907 // In some error cases we want to convey more info back to the observer 15908 String origPackage; 15909 String origPermission; 15910 } 15911 15912 /* 15913 * Install a non-existing package. 15914 */ 15915 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15916 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15917 String volumeUuid, PackageInstalledInfo res, int installReason) { 15918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15919 15920 // Remember this for later, in case we need to rollback this install 15921 String pkgName = pkg.packageName; 15922 15923 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15924 15925 synchronized(mPackages) { 15926 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15927 if (renamedPackage != null) { 15928 // A package with the same name is already installed, though 15929 // it has been renamed to an older name. The package we 15930 // are trying to install should be installed as an update to 15931 // the existing one, but that has not been requested, so bail. 15932 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15933 + " without first uninstalling package running as " 15934 + renamedPackage); 15935 return; 15936 } 15937 if (mPackages.containsKey(pkgName)) { 15938 // Don't allow installation over an existing package with the same name. 15939 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15940 + " without first uninstalling."); 15941 return; 15942 } 15943 } 15944 15945 try { 15946 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15947 System.currentTimeMillis(), user); 15948 15949 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15950 15951 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15952 prepareAppDataAfterInstallLIF(newPackage); 15953 15954 } else { 15955 // Remove package from internal structures, but keep around any 15956 // data that might have already existed 15957 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15958 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15959 } 15960 } catch (PackageManagerException e) { 15961 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15962 } 15963 15964 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15965 } 15966 15967 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15968 try (DigestInputStream digestStream = 15969 new DigestInputStream(new FileInputStream(file), digest)) { 15970 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15971 } 15972 } 15973 15974 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15975 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15976 PackageInstalledInfo res, int installReason) { 15977 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15978 15979 final PackageParser.Package oldPackage; 15980 final PackageSetting ps; 15981 final String pkgName = pkg.packageName; 15982 final int[] allUsers; 15983 final int[] installedUsers; 15984 15985 synchronized(mPackages) { 15986 oldPackage = mPackages.get(pkgName); 15987 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15988 15989 // don't allow upgrade to target a release SDK from a pre-release SDK 15990 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15991 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15992 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15993 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15994 if (oldTargetsPreRelease 15995 && !newTargetsPreRelease 15996 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15997 Slog.w(TAG, "Can't install package targeting released sdk"); 15998 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15999 return; 16000 } 16001 16002 ps = mSettings.mPackages.get(pkgName); 16003 16004 // verify signatures are valid 16005 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16006 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16007 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16008 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16009 "New package not signed by keys specified by upgrade-keysets: " 16010 + pkgName); 16011 return; 16012 } 16013 } else { 16014 16015 // default to original signature matching 16016 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 16017 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 16018 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16019 "New package has a different signature: " + pkgName); 16020 return; 16021 } 16022 } 16023 16024 // don't allow a system upgrade unless the upgrade hash matches 16025 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16026 byte[] digestBytes = null; 16027 try { 16028 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16029 updateDigest(digest, new File(pkg.baseCodePath)); 16030 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16031 for (String path : pkg.splitCodePaths) { 16032 updateDigest(digest, new File(path)); 16033 } 16034 } 16035 digestBytes = digest.digest(); 16036 } catch (NoSuchAlgorithmException | IOException e) { 16037 res.setError(INSTALL_FAILED_INVALID_APK, 16038 "Could not compute hash: " + pkgName); 16039 return; 16040 } 16041 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16042 res.setError(INSTALL_FAILED_INVALID_APK, 16043 "New package fails restrict-update check: " + pkgName); 16044 return; 16045 } 16046 // retain upgrade restriction 16047 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16048 } 16049 16050 // Check for shared user id changes 16051 String invalidPackageName = 16052 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16053 if (invalidPackageName != null) { 16054 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16055 "Package " + invalidPackageName + " tried to change user " 16056 + oldPackage.mSharedUserId); 16057 return; 16058 } 16059 16060 // check if the new package supports all of the abis which the old package supports 16061 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16062 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16063 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16064 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16065 "Update to package " + pkgName + " doesn't support multi arch"); 16066 return; 16067 } 16068 16069 // In case of rollback, remember per-user/profile install state 16070 allUsers = sUserManager.getUserIds(); 16071 installedUsers = ps.queryInstalledUsers(allUsers, true); 16072 16073 // don't allow an upgrade from full to ephemeral 16074 if (isInstantApp) { 16075 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16076 for (int currentUser : allUsers) { 16077 if (!ps.getInstantApp(currentUser)) { 16078 // can't downgrade from full to instant 16079 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16080 + " for user: " + currentUser); 16081 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16082 return; 16083 } 16084 } 16085 } else if (!ps.getInstantApp(user.getIdentifier())) { 16086 // can't downgrade from full to instant 16087 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16088 + " for user: " + user.getIdentifier()); 16089 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16090 return; 16091 } 16092 } 16093 } 16094 16095 // Update what is removed 16096 res.removedInfo = new PackageRemovedInfo(this); 16097 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16098 res.removedInfo.removedPackage = oldPackage.packageName; 16099 res.removedInfo.installerPackageName = ps.installerPackageName; 16100 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16101 res.removedInfo.isUpdate = true; 16102 res.removedInfo.origUsers = installedUsers; 16103 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16104 for (int i = 0; i < installedUsers.length; i++) { 16105 final int userId = installedUsers[i]; 16106 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16107 } 16108 16109 final int childCount = (oldPackage.childPackages != null) 16110 ? oldPackage.childPackages.size() : 0; 16111 for (int i = 0; i < childCount; i++) { 16112 boolean childPackageUpdated = false; 16113 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16114 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16115 if (res.addedChildPackages != null) { 16116 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16117 if (childRes != null) { 16118 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16119 childRes.removedInfo.removedPackage = childPkg.packageName; 16120 if (childPs != null) { 16121 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16122 } 16123 childRes.removedInfo.isUpdate = true; 16124 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16125 childPackageUpdated = true; 16126 } 16127 } 16128 if (!childPackageUpdated) { 16129 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16130 childRemovedRes.removedPackage = childPkg.packageName; 16131 if (childPs != null) { 16132 childRemovedRes.installerPackageName = childPs.installerPackageName; 16133 } 16134 childRemovedRes.isUpdate = false; 16135 childRemovedRes.dataRemoved = true; 16136 synchronized (mPackages) { 16137 if (childPs != null) { 16138 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16139 } 16140 } 16141 if (res.removedInfo.removedChildPackages == null) { 16142 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16143 } 16144 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16145 } 16146 } 16147 16148 boolean sysPkg = (isSystemApp(oldPackage)); 16149 if (sysPkg) { 16150 // Set the system/privileged/oem/vendor/product flags as needed 16151 final boolean privileged = 16152 (oldPackage.applicationInfo.privateFlags 16153 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16154 final boolean oem = 16155 (oldPackage.applicationInfo.privateFlags 16156 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16157 final boolean vendor = 16158 (oldPackage.applicationInfo.privateFlags 16159 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16160 final boolean product = 16161 (oldPackage.applicationInfo.privateFlags 16162 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16163 final @ParseFlags int systemParseFlags = parseFlags; 16164 final @ScanFlags int systemScanFlags = scanFlags 16165 | SCAN_AS_SYSTEM 16166 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16167 | (oem ? SCAN_AS_OEM : 0) 16168 | (vendor ? SCAN_AS_VENDOR : 0) 16169 | (product ? SCAN_AS_PRODUCT : 0); 16170 16171 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16172 user, allUsers, installerPackageName, res, installReason); 16173 } else { 16174 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16175 user, allUsers, installerPackageName, res, installReason); 16176 } 16177 } 16178 16179 @Override 16180 public List<String> getPreviousCodePaths(String packageName) { 16181 final int callingUid = Binder.getCallingUid(); 16182 final List<String> result = new ArrayList<>(); 16183 if (getInstantAppPackageName(callingUid) != null) { 16184 return result; 16185 } 16186 final PackageSetting ps = mSettings.mPackages.get(packageName); 16187 if (ps != null 16188 && ps.oldCodePaths != null 16189 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16190 result.addAll(ps.oldCodePaths); 16191 } 16192 return result; 16193 } 16194 16195 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16196 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16197 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16198 String installerPackageName, PackageInstalledInfo res, int installReason) { 16199 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16200 + deletedPackage); 16201 16202 String pkgName = deletedPackage.packageName; 16203 boolean deletedPkg = true; 16204 boolean addedPkg = false; 16205 boolean updatedSettings = false; 16206 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16207 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16208 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16209 16210 final long origUpdateTime = (pkg.mExtras != null) 16211 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16212 16213 // First delete the existing package while retaining the data directory 16214 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16215 res.removedInfo, true, pkg)) { 16216 // If the existing package wasn't successfully deleted 16217 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16218 deletedPkg = false; 16219 } else { 16220 // Successfully deleted the old package; proceed with replace. 16221 16222 // If deleted package lived in a container, give users a chance to 16223 // relinquish resources before killing. 16224 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16225 if (DEBUG_INSTALL) { 16226 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16227 } 16228 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16229 final ArrayList<String> pkgList = new ArrayList<String>(1); 16230 pkgList.add(deletedPackage.applicationInfo.packageName); 16231 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16232 } 16233 16234 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16235 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16236 16237 try { 16238 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16239 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16240 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16241 installReason); 16242 16243 // Update the in-memory copy of the previous code paths. 16244 PackageSetting ps = mSettings.mPackages.get(pkgName); 16245 if (!killApp) { 16246 if (ps.oldCodePaths == null) { 16247 ps.oldCodePaths = new ArraySet<>(); 16248 } 16249 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16250 if (deletedPackage.splitCodePaths != null) { 16251 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16252 } 16253 } else { 16254 ps.oldCodePaths = null; 16255 } 16256 if (ps.childPackageNames != null) { 16257 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16258 final String childPkgName = ps.childPackageNames.get(i); 16259 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16260 childPs.oldCodePaths = ps.oldCodePaths; 16261 } 16262 } 16263 // set instant app status, but, only if it's explicitly specified 16264 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16265 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16266 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16267 prepareAppDataAfterInstallLIF(newPackage); 16268 addedPkg = true; 16269 mDexManager.notifyPackageUpdated(newPackage.packageName, 16270 newPackage.baseCodePath, newPackage.splitCodePaths); 16271 } catch (PackageManagerException e) { 16272 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16273 } 16274 } 16275 16276 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16277 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16278 16279 // Revert all internal state mutations and added folders for the failed install 16280 if (addedPkg) { 16281 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16282 res.removedInfo, true, null); 16283 } 16284 16285 // Restore the old package 16286 if (deletedPkg) { 16287 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16288 File restoreFile = new File(deletedPackage.codePath); 16289 // Parse old package 16290 boolean oldExternal = isExternal(deletedPackage); 16291 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16292 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16293 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16294 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16295 try { 16296 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16297 null); 16298 } catch (PackageManagerException e) { 16299 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16300 + e.getMessage()); 16301 return; 16302 } 16303 16304 synchronized (mPackages) { 16305 // Ensure the installer package name up to date 16306 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16307 16308 // Update permissions for restored package 16309 mPermissionManager.updatePermissions( 16310 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16311 mPermissionCallback); 16312 16313 mSettings.writeLPr(); 16314 } 16315 16316 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16317 } 16318 } else { 16319 synchronized (mPackages) { 16320 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16321 if (ps != null) { 16322 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16323 if (res.removedInfo.removedChildPackages != null) { 16324 final int childCount = res.removedInfo.removedChildPackages.size(); 16325 // Iterate in reverse as we may modify the collection 16326 for (int i = childCount - 1; i >= 0; i--) { 16327 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16328 if (res.addedChildPackages.containsKey(childPackageName)) { 16329 res.removedInfo.removedChildPackages.removeAt(i); 16330 } else { 16331 PackageRemovedInfo childInfo = res.removedInfo 16332 .removedChildPackages.valueAt(i); 16333 childInfo.removedForAllUsers = mPackages.get( 16334 childInfo.removedPackage) == null; 16335 } 16336 } 16337 } 16338 } 16339 } 16340 } 16341 } 16342 16343 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16344 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16345 final @ScanFlags int scanFlags, UserHandle user, 16346 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16347 int installReason) { 16348 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16349 + ", old=" + deletedPackage); 16350 16351 final boolean disabledSystem; 16352 16353 // Remove existing system package 16354 removePackageLI(deletedPackage, true); 16355 16356 synchronized (mPackages) { 16357 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16358 } 16359 if (!disabledSystem) { 16360 // We didn't need to disable the .apk as a current system package, 16361 // which means we are replacing another update that is already 16362 // installed. We need to make sure to delete the older one's .apk. 16363 res.removedInfo.args = createInstallArgsForExisting(0, 16364 deletedPackage.applicationInfo.getCodePath(), 16365 deletedPackage.applicationInfo.getResourcePath(), 16366 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16367 } else { 16368 res.removedInfo.args = null; 16369 } 16370 16371 // Successfully disabled the old package. Now proceed with re-installation 16372 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16373 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16374 16375 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16376 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16377 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16378 16379 PackageParser.Package newPackage = null; 16380 try { 16381 // Add the package to the internal data structures 16382 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16383 16384 // Set the update and install times 16385 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16386 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16387 System.currentTimeMillis()); 16388 16389 // Update the package dynamic state if succeeded 16390 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16391 // Now that the install succeeded make sure we remove data 16392 // directories for any child package the update removed. 16393 final int deletedChildCount = (deletedPackage.childPackages != null) 16394 ? deletedPackage.childPackages.size() : 0; 16395 final int newChildCount = (newPackage.childPackages != null) 16396 ? newPackage.childPackages.size() : 0; 16397 for (int i = 0; i < deletedChildCount; i++) { 16398 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16399 boolean childPackageDeleted = true; 16400 for (int j = 0; j < newChildCount; j++) { 16401 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16402 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16403 childPackageDeleted = false; 16404 break; 16405 } 16406 } 16407 if (childPackageDeleted) { 16408 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16409 deletedChildPkg.packageName); 16410 if (ps != null && res.removedInfo.removedChildPackages != null) { 16411 PackageRemovedInfo removedChildRes = res.removedInfo 16412 .removedChildPackages.get(deletedChildPkg.packageName); 16413 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16414 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16415 } 16416 } 16417 } 16418 16419 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16420 installReason); 16421 prepareAppDataAfterInstallLIF(newPackage); 16422 16423 mDexManager.notifyPackageUpdated(newPackage.packageName, 16424 newPackage.baseCodePath, newPackage.splitCodePaths); 16425 } 16426 } catch (PackageManagerException e) { 16427 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16428 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16429 } 16430 16431 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16432 // Re installation failed. Restore old information 16433 // Remove new pkg information 16434 if (newPackage != null) { 16435 removeInstalledPackageLI(newPackage, true); 16436 } 16437 // Add back the old system package 16438 try { 16439 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16440 } catch (PackageManagerException e) { 16441 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16442 } 16443 16444 synchronized (mPackages) { 16445 if (disabledSystem) { 16446 enableSystemPackageLPw(deletedPackage); 16447 } 16448 16449 // Ensure the installer package name up to date 16450 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16451 16452 // Update permissions for restored package 16453 mPermissionManager.updatePermissions( 16454 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16455 mPermissionCallback); 16456 16457 mSettings.writeLPr(); 16458 } 16459 16460 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16461 + " after failed upgrade"); 16462 } 16463 } 16464 16465 /** 16466 * Checks whether the parent or any of the child packages have a change shared 16467 * user. For a package to be a valid update the shred users of the parent and 16468 * the children should match. We may later support changing child shared users. 16469 * @param oldPkg The updated package. 16470 * @param newPkg The update package. 16471 * @return The shared user that change between the versions. 16472 */ 16473 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16474 PackageParser.Package newPkg) { 16475 // Check parent shared user 16476 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16477 return newPkg.packageName; 16478 } 16479 // Check child shared users 16480 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16481 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16482 for (int i = 0; i < newChildCount; i++) { 16483 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16484 // If this child was present, did it have the same shared user? 16485 for (int j = 0; j < oldChildCount; j++) { 16486 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16487 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16488 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16489 return newChildPkg.packageName; 16490 } 16491 } 16492 } 16493 return null; 16494 } 16495 16496 private void removeNativeBinariesLI(PackageSetting ps) { 16497 // Remove the lib path for the parent package 16498 if (ps != null) { 16499 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16500 // Remove the lib path for the child packages 16501 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16502 for (int i = 0; i < childCount; i++) { 16503 PackageSetting childPs = null; 16504 synchronized (mPackages) { 16505 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16506 } 16507 if (childPs != null) { 16508 NativeLibraryHelper.removeNativeBinariesLI(childPs 16509 .legacyNativeLibraryPathString); 16510 } 16511 } 16512 } 16513 } 16514 16515 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16516 // Enable the parent package 16517 mSettings.enableSystemPackageLPw(pkg.packageName); 16518 // Enable the child packages 16519 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16520 for (int i = 0; i < childCount; i++) { 16521 PackageParser.Package childPkg = pkg.childPackages.get(i); 16522 mSettings.enableSystemPackageLPw(childPkg.packageName); 16523 } 16524 } 16525 16526 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16527 PackageParser.Package newPkg) { 16528 // Disable the parent package (parent always replaced) 16529 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16530 // Disable the child packages 16531 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16532 for (int i = 0; i < childCount; i++) { 16533 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16534 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16535 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16536 } 16537 return disabled; 16538 } 16539 16540 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16541 String installerPackageName) { 16542 // Enable the parent package 16543 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16544 // Enable the child packages 16545 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16546 for (int i = 0; i < childCount; i++) { 16547 PackageParser.Package childPkg = pkg.childPackages.get(i); 16548 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16549 } 16550 } 16551 16552 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16553 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16554 // Update the parent package setting 16555 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16556 res, user, installReason); 16557 // Update the child packages setting 16558 final int childCount = (newPackage.childPackages != null) 16559 ? newPackage.childPackages.size() : 0; 16560 for (int i = 0; i < childCount; i++) { 16561 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16562 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16563 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16564 childRes.origUsers, childRes, user, installReason); 16565 } 16566 } 16567 16568 private void updateSettingsInternalLI(PackageParser.Package pkg, 16569 String installerPackageName, int[] allUsers, int[] installedForUsers, 16570 PackageInstalledInfo res, UserHandle user, int installReason) { 16571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16572 16573 final String pkgName = pkg.packageName; 16574 16575 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16576 synchronized (mPackages) { 16577// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16578 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16579 mPermissionCallback); 16580 // For system-bundled packages, we assume that installing an upgraded version 16581 // of the package implies that the user actually wants to run that new code, 16582 // so we enable the package. 16583 PackageSetting ps = mSettings.mPackages.get(pkgName); 16584 final int userId = user.getIdentifier(); 16585 if (ps != null) { 16586 if (isSystemApp(pkg)) { 16587 if (DEBUG_INSTALL) { 16588 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16589 } 16590 // Enable system package for requested users 16591 if (res.origUsers != null) { 16592 for (int origUserId : res.origUsers) { 16593 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16594 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16595 origUserId, installerPackageName); 16596 } 16597 } 16598 } 16599 // Also convey the prior install/uninstall state 16600 if (allUsers != null && installedForUsers != null) { 16601 for (int currentUserId : allUsers) { 16602 final boolean installed = ArrayUtils.contains( 16603 installedForUsers, currentUserId); 16604 if (DEBUG_INSTALL) { 16605 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16606 } 16607 ps.setInstalled(installed, currentUserId); 16608 } 16609 // these install state changes will be persisted in the 16610 // upcoming call to mSettings.writeLPr(). 16611 } 16612 } 16613 // It's implied that when a user requests installation, they want the app to be 16614 // installed and enabled. 16615 if (userId != UserHandle.USER_ALL) { 16616 ps.setInstalled(true, userId); 16617 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16618 } else { 16619 for (int currentUserId : sUserManager.getUserIds()) { 16620 ps.setInstalled(true, currentUserId); 16621 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId, 16622 installerPackageName); 16623 } 16624 } 16625 16626 // When replacing an existing package, preserve the original install reason for all 16627 // users that had the package installed before. 16628 final Set<Integer> previousUserIds = new ArraySet<>(); 16629 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16630 final int installReasonCount = res.removedInfo.installReasons.size(); 16631 for (int i = 0; i < installReasonCount; i++) { 16632 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16633 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16634 ps.setInstallReason(previousInstallReason, previousUserId); 16635 previousUserIds.add(previousUserId); 16636 } 16637 } 16638 16639 // Set install reason for users that are having the package newly installed. 16640 if (userId == UserHandle.USER_ALL) { 16641 for (int currentUserId : sUserManager.getUserIds()) { 16642 if (!previousUserIds.contains(currentUserId)) { 16643 ps.setInstallReason(installReason, currentUserId); 16644 } 16645 } 16646 } else if (!previousUserIds.contains(userId)) { 16647 ps.setInstallReason(installReason, userId); 16648 } 16649 mSettings.writeKernelMappingLPr(ps); 16650 } 16651 res.name = pkgName; 16652 res.uid = pkg.applicationInfo.uid; 16653 res.pkg = pkg; 16654 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16655 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16656 //to update install status 16657 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16658 mSettings.writeLPr(); 16659 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16660 } 16661 16662 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16663 } 16664 16665 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16666 try { 16667 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16668 installPackageLI(args, res); 16669 } finally { 16670 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16671 } 16672 } 16673 16674 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16675 final int installFlags = args.installFlags; 16676 final String installerPackageName = args.installerPackageName; 16677 final String volumeUuid = args.volumeUuid; 16678 final File tmpPackageFile = new File(args.getCodePath()); 16679 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16680 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16681 || (args.volumeUuid != null)); 16682 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16683 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16684 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16685 final boolean virtualPreload = 16686 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16687 boolean replace = false; 16688 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16689 if (args.move != null) { 16690 // moving a complete application; perform an initial scan on the new install location 16691 scanFlags |= SCAN_INITIAL; 16692 } 16693 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16694 scanFlags |= SCAN_DONT_KILL_APP; 16695 } 16696 if (instantApp) { 16697 scanFlags |= SCAN_AS_INSTANT_APP; 16698 } 16699 if (fullApp) { 16700 scanFlags |= SCAN_AS_FULL_APP; 16701 } 16702 if (virtualPreload) { 16703 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16704 } 16705 16706 // Result object to be returned 16707 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16708 res.installerPackageName = installerPackageName; 16709 16710 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16711 16712 // Sanity check 16713 if (instantApp && (forwardLocked || onExternal)) { 16714 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16715 + " external=" + onExternal); 16716 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16717 return; 16718 } 16719 16720 // Retrieve PackageSettings and parse package 16721 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16722 | PackageParser.PARSE_ENFORCE_CODE 16723 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16724 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16725 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16726 PackageParser pp = new PackageParser(); 16727 pp.setSeparateProcesses(mSeparateProcesses); 16728 pp.setDisplayMetrics(mMetrics); 16729 pp.setCallback(mPackageParserCallback); 16730 16731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16732 final PackageParser.Package pkg; 16733 try { 16734 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16735 DexMetadataHelper.validatePackageDexMetadata(pkg); 16736 } catch (PackageParserException e) { 16737 res.setError("Failed parse during installPackageLI", e); 16738 return; 16739 } finally { 16740 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16741 } 16742 16743 // Instant apps have several additional install-time checks. 16744 if (instantApp) { 16745 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16746 Slog.w(TAG, 16747 "Instant app package " + pkg.packageName + " does not target at least O"); 16748 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16749 "Instant app package must target at least O"); 16750 return; 16751 } 16752 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16753 Slog.w(TAG, "Instant app package " + pkg.packageName 16754 + " does not target targetSandboxVersion 2"); 16755 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16756 "Instant app package must use targetSandboxVersion 2"); 16757 return; 16758 } 16759 if (pkg.mSharedUserId != null) { 16760 Slog.w(TAG, "Instant app package " + pkg.packageName 16761 + " may not declare sharedUserId."); 16762 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16763 "Instant app package may not declare a sharedUserId"); 16764 return; 16765 } 16766 } 16767 16768 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16769 // Static shared libraries have synthetic package names 16770 renameStaticSharedLibraryPackage(pkg); 16771 16772 // No static shared libs on external storage 16773 if (onExternal) { 16774 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16775 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16776 "Packages declaring static-shared libs cannot be updated"); 16777 return; 16778 } 16779 } 16780 16781 // If we are installing a clustered package add results for the children 16782 if (pkg.childPackages != null) { 16783 synchronized (mPackages) { 16784 final int childCount = pkg.childPackages.size(); 16785 for (int i = 0; i < childCount; i++) { 16786 PackageParser.Package childPkg = pkg.childPackages.get(i); 16787 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16788 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16789 childRes.pkg = childPkg; 16790 childRes.name = childPkg.packageName; 16791 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16792 if (childPs != null) { 16793 childRes.origUsers = childPs.queryInstalledUsers( 16794 sUserManager.getUserIds(), true); 16795 } 16796 if ((mPackages.containsKey(childPkg.packageName))) { 16797 childRes.removedInfo = new PackageRemovedInfo(this); 16798 childRes.removedInfo.removedPackage = childPkg.packageName; 16799 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16800 } 16801 if (res.addedChildPackages == null) { 16802 res.addedChildPackages = new ArrayMap<>(); 16803 } 16804 res.addedChildPackages.put(childPkg.packageName, childRes); 16805 } 16806 } 16807 } 16808 16809 // If package doesn't declare API override, mark that we have an install 16810 // time CPU ABI override. 16811 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16812 pkg.cpuAbiOverride = args.abiOverride; 16813 } 16814 16815 String pkgName = res.name = pkg.packageName; 16816 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16817 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16818 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16819 return; 16820 } 16821 } 16822 16823 try { 16824 // either use what we've been given or parse directly from the APK 16825 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16826 pkg.setSigningDetails(args.signingDetails); 16827 } else { 16828 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16829 } 16830 } catch (PackageParserException e) { 16831 res.setError("Failed collect during installPackageLI", e); 16832 return; 16833 } 16834 16835 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16836 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16837 Slog.w(TAG, "Instant app package " + pkg.packageName 16838 + " is not signed with at least APK Signature Scheme v2"); 16839 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16840 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16841 return; 16842 } 16843 16844 // Get rid of all references to package scan path via parser. 16845 pp = null; 16846 String oldCodePath = null; 16847 boolean systemApp = false; 16848 synchronized (mPackages) { 16849 // Check if installing already existing package 16850 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16851 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16852 if (pkg.mOriginalPackages != null 16853 && pkg.mOriginalPackages.contains(oldName) 16854 && mPackages.containsKey(oldName)) { 16855 // This package is derived from an original package, 16856 // and this device has been updating from that original 16857 // name. We must continue using the original name, so 16858 // rename the new package here. 16859 pkg.setPackageName(oldName); 16860 pkgName = pkg.packageName; 16861 replace = true; 16862 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16863 + oldName + " pkgName=" + pkgName); 16864 } else if (mPackages.containsKey(pkgName)) { 16865 // This package, under its official name, already exists 16866 // on the device; we should replace it. 16867 replace = true; 16868 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16869 } 16870 16871 // Child packages are installed through the parent package 16872 if (pkg.parentPackage != null) { 16873 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16874 "Package " + pkg.packageName + " is child of package " 16875 + pkg.parentPackage.parentPackage + ". Child packages " 16876 + "can be updated only through the parent package."); 16877 return; 16878 } 16879 16880 if (replace) { 16881 // Prevent apps opting out from runtime permissions 16882 PackageParser.Package oldPackage = mPackages.get(pkgName); 16883 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16884 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16885 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16886 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16887 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16888 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16889 + " doesn't support runtime permissions but the old" 16890 + " target SDK " + oldTargetSdk + " does."); 16891 return; 16892 } 16893 // Prevent persistent apps from being updated 16894 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16895 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16896 "Package " + oldPackage.packageName + " is a persistent app. " 16897 + "Persistent apps are not updateable."); 16898 return; 16899 } 16900 // Prevent apps from downgrading their targetSandbox. 16901 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16902 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16903 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16904 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16905 "Package " + pkg.packageName + " new target sandbox " 16906 + newTargetSandbox + " is incompatible with the previous value of" 16907 + oldTargetSandbox + "."); 16908 return; 16909 } 16910 16911 // Prevent installing of child packages 16912 if (oldPackage.parentPackage != null) { 16913 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16914 "Package " + pkg.packageName + " is child of package " 16915 + oldPackage.parentPackage + ". Child packages " 16916 + "can be updated only through the parent package."); 16917 return; 16918 } 16919 } 16920 } 16921 16922 PackageSetting ps = mSettings.mPackages.get(pkgName); 16923 if (ps != null) { 16924 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16925 16926 // Static shared libs have same package with different versions where 16927 // we internally use a synthetic package name to allow multiple versions 16928 // of the same package, therefore we need to compare signatures against 16929 // the package setting for the latest library version. 16930 PackageSetting signatureCheckPs = ps; 16931 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16932 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16933 if (libraryEntry != null) { 16934 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16935 } 16936 } 16937 16938 // Quick sanity check that we're signed correctly if updating; 16939 // we'll check this again later when scanning, but we want to 16940 // bail early here before tripping over redefined permissions. 16941 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16942 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16943 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16944 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16945 + pkg.packageName + " upgrade keys do not match the " 16946 + "previously installed version"); 16947 return; 16948 } 16949 } else { 16950 try { 16951 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16952 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16953 // We don't care about disabledPkgSetting on install for now. 16954 final boolean compatMatch = verifySignatures( 16955 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16956 compareRecover); 16957 // The new KeySets will be re-added later in the scanning process. 16958 if (compatMatch) { 16959 synchronized (mPackages) { 16960 ksms.removeAppKeySetDataLPw(pkg.packageName); 16961 } 16962 } 16963 } catch (PackageManagerException e) { 16964 res.setError(e.error, e.getMessage()); 16965 return; 16966 } 16967 } 16968 16969 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16970 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16971 systemApp = (ps.pkg.applicationInfo.flags & 16972 ApplicationInfo.FLAG_SYSTEM) != 0; 16973 } 16974 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16975 } 16976 16977 int N = pkg.permissions.size(); 16978 for (int i = N-1; i >= 0; i--) { 16979 final PackageParser.Permission perm = pkg.permissions.get(i); 16980 final BasePermission bp = 16981 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16982 16983 // Don't allow anyone but the system to define ephemeral permissions. 16984 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16985 && !systemApp) { 16986 Slog.w(TAG, "Non-System package " + pkg.packageName 16987 + " attempting to delcare ephemeral permission " 16988 + perm.info.name + "; Removing ephemeral."); 16989 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16990 } 16991 16992 // Check whether the newly-scanned package wants to define an already-defined perm 16993 if (bp != null) { 16994 // If the defining package is signed with our cert, it's okay. This 16995 // also includes the "updating the same package" case, of course. 16996 // "updating same package" could also involve key-rotation. 16997 final boolean sigsOk; 16998 final String sourcePackageName = bp.getSourcePackageName(); 16999 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17000 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17001 if (sourcePackageName.equals(pkg.packageName) 17002 && (ksms.shouldCheckUpgradeKeySetLocked( 17003 sourcePackageSetting, scanFlags))) { 17004 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17005 } else { 17006 17007 // in the event of signing certificate rotation, we need to see if the 17008 // package's certificate has rotated from the current one, or if it is an 17009 // older certificate with which the current is ok with sharing permissions 17010 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17011 pkg.mSigningDetails, 17012 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17013 sigsOk = true; 17014 } else if (pkg.mSigningDetails.checkCapability( 17015 sourcePackageSetting.signatures.mSigningDetails, 17016 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17017 17018 // the scanned package checks out, has signing certificate rotation 17019 // history, and is newer; bring it over 17020 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17021 sigsOk = true; 17022 } else { 17023 sigsOk = false; 17024 } 17025 } 17026 if (!sigsOk) { 17027 // If the owning package is the system itself, we log but allow 17028 // install to proceed; we fail the install on all other permission 17029 // redefinitions. 17030 if (!sourcePackageName.equals("android")) { 17031 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17032 + pkg.packageName + " attempting to redeclare permission " 17033 + perm.info.name + " already owned by " + sourcePackageName); 17034 res.origPermission = perm.info.name; 17035 res.origPackage = sourcePackageName; 17036 return; 17037 } else { 17038 Slog.w(TAG, "Package " + pkg.packageName 17039 + " attempting to redeclare system permission " 17040 + perm.info.name + "; ignoring new declaration"); 17041 pkg.permissions.remove(i); 17042 } 17043 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17044 // Prevent apps to change protection level to dangerous from any other 17045 // type as this would allow a privilege escalation where an app adds a 17046 // normal/signature permission in other app's group and later redefines 17047 // it as dangerous leading to the group auto-grant. 17048 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17049 == PermissionInfo.PROTECTION_DANGEROUS) { 17050 if (bp != null && !bp.isRuntime()) { 17051 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17052 + "non-runtime permission " + perm.info.name 17053 + " to runtime; keeping old protection level"); 17054 perm.info.protectionLevel = bp.getProtectionLevel(); 17055 } 17056 } 17057 } 17058 } 17059 } 17060 } 17061 17062 if (systemApp) { 17063 if (onExternal) { 17064 // Abort update; system app can't be replaced with app on sdcard 17065 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17066 "Cannot install updates to system apps on sdcard"); 17067 return; 17068 } else if (instantApp) { 17069 // Abort update; system app can't be replaced with an instant app 17070 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17071 "Cannot update a system app with an instant app"); 17072 return; 17073 } 17074 } 17075 17076 if (args.move != null) { 17077 // We did an in-place move, so dex is ready to roll 17078 scanFlags |= SCAN_NO_DEX; 17079 scanFlags |= SCAN_MOVE; 17080 17081 synchronized (mPackages) { 17082 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17083 if (ps == null) { 17084 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17085 "Missing settings for moved package " + pkgName); 17086 } 17087 17088 // We moved the entire application as-is, so bring over the 17089 // previously derived ABI information. 17090 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17091 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17092 } 17093 17094 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17095 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17096 scanFlags |= SCAN_NO_DEX; 17097 17098 try { 17099 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17100 args.abiOverride : pkg.cpuAbiOverride); 17101 final boolean extractNativeLibs = !pkg.isLibrary(); 17102 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17103 } catch (PackageManagerException pme) { 17104 Slog.e(TAG, "Error deriving application ABI", pme); 17105 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17106 return; 17107 } 17108 17109 // Shared libraries for the package need to be updated. 17110 synchronized (mPackages) { 17111 try { 17112 updateSharedLibrariesLPr(pkg, null); 17113 } catch (PackageManagerException e) { 17114 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17115 } 17116 } 17117 } 17118 17119 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17120 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17121 return; 17122 } 17123 17124 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17125 String apkPath = null; 17126 synchronized (mPackages) { 17127 // Note that if the attacker managed to skip verify setup, for example by tampering 17128 // with the package settings, upon reboot we will do full apk verification when 17129 // verity is not detected. 17130 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17131 if (ps != null && ps.isPrivileged()) { 17132 apkPath = pkg.baseCodePath; 17133 } 17134 } 17135 17136 if (apkPath != null) { 17137 final VerityUtils.SetupResult result = 17138 VerityUtils.generateApkVeritySetupData(apkPath); 17139 if (result.isOk()) { 17140 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17141 FileDescriptor fd = result.getUnownedFileDescriptor(); 17142 try { 17143 mInstaller.installApkVerity(apkPath, fd); 17144 } catch (InstallerException e) { 17145 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17146 "Failed to set up verity: " + e); 17147 return; 17148 } finally { 17149 IoUtils.closeQuietly(fd); 17150 } 17151 } else if (result.isFailed()) { 17152 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17153 return; 17154 } else { 17155 // Do nothing if verity is skipped. Will fall back to full apk verification on 17156 // reboot. 17157 } 17158 } 17159 } 17160 17161 if (!instantApp) { 17162 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17163 } else { 17164 if (DEBUG_DOMAIN_VERIFICATION) { 17165 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17166 } 17167 } 17168 17169 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17170 "installPackageLI")) { 17171 if (replace) { 17172 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17173 // Static libs have a synthetic package name containing the version 17174 // and cannot be updated as an update would get a new package name, 17175 // unless this is the exact same version code which is useful for 17176 // development. 17177 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17178 if (existingPkg != null && 17179 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17180 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17181 + "static-shared libs cannot be updated"); 17182 return; 17183 } 17184 } 17185 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17186 installerPackageName, res, args.installReason); 17187 } else { 17188 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17189 args.user, installerPackageName, volumeUuid, res, args.installReason); 17190 } 17191 } 17192 17193 // Prepare the application profiles for the new code paths. 17194 // This needs to be done before invoking dexopt so that any install-time profile 17195 // can be used for optimizations. 17196 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17197 17198 // Check whether we need to dexopt the app. 17199 // 17200 // NOTE: it is IMPORTANT to call dexopt: 17201 // - after doRename which will sync the package data from PackageParser.Package and its 17202 // corresponding ApplicationInfo. 17203 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17204 // uid of the application (pkg.applicationInfo.uid). 17205 // This update happens in place! 17206 // 17207 // We only need to dexopt if the package meets ALL of the following conditions: 17208 // 1) it is not forward locked. 17209 // 2) it is not on on an external ASEC container. 17210 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17211 // 17212 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17213 // complete, so we skip this step during installation. Instead, we'll take extra time 17214 // the first time the instant app starts. It's preferred to do it this way to provide 17215 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17216 // middle of running an instant app. The default behaviour can be overridden 17217 // via gservices. 17218 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17219 && !forwardLocked 17220 && !pkg.applicationInfo.isExternalAsec() 17221 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17222 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17223 17224 if (performDexopt) { 17225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17226 // Do not run PackageDexOptimizer through the local performDexOpt 17227 // method because `pkg` may not be in `mPackages` yet. 17228 // 17229 // Also, don't fail application installs if the dexopt step fails. 17230 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17231 REASON_INSTALL, 17232 DexoptOptions.DEXOPT_BOOT_COMPLETE | 17233 DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17234 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17235 null /* instructionSets */, 17236 getOrCreateCompilerPackageStats(pkg), 17237 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17238 dexoptOptions); 17239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17240 } 17241 17242 // Notify BackgroundDexOptService that the package has been changed. 17243 // If this is an update of a package which used to fail to compile, 17244 // BackgroundDexOptService will remove it from its blacklist. 17245 // TODO: Layering violation 17246 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17247 17248 synchronized (mPackages) { 17249 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17250 if (ps != null) { 17251 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17252 ps.setUpdateAvailable(false /*updateAvailable*/); 17253 } 17254 17255 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17256 for (int i = 0; i < childCount; i++) { 17257 PackageParser.Package childPkg = pkg.childPackages.get(i); 17258 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17259 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17260 if (childPs != null) { 17261 childRes.newUsers = childPs.queryInstalledUsers( 17262 sUserManager.getUserIds(), true); 17263 } 17264 } 17265 17266 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17267 updateSequenceNumberLP(ps, res.newUsers); 17268 updateInstantAppInstallerLocked(pkgName); 17269 } 17270 } 17271 } 17272 17273 private void startIntentFilterVerifications(int userId, boolean replacing, 17274 PackageParser.Package pkg) { 17275 if (mIntentFilterVerifierComponent == null) { 17276 Slog.w(TAG, "No IntentFilter verification will not be done as " 17277 + "there is no IntentFilterVerifier available!"); 17278 return; 17279 } 17280 17281 final int verifierUid = getPackageUid( 17282 mIntentFilterVerifierComponent.getPackageName(), 17283 MATCH_DEBUG_TRIAGED_MISSING, 17284 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17285 17286 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17287 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17288 mHandler.sendMessage(msg); 17289 17290 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17291 for (int i = 0; i < childCount; i++) { 17292 PackageParser.Package childPkg = pkg.childPackages.get(i); 17293 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17294 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17295 mHandler.sendMessage(msg); 17296 } 17297 } 17298 17299 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17300 PackageParser.Package pkg) { 17301 int size = pkg.activities.size(); 17302 if (size == 0) { 17303 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17304 "No activity, so no need to verify any IntentFilter!"); 17305 return; 17306 } 17307 17308 final boolean hasDomainURLs = hasDomainURLs(pkg); 17309 if (!hasDomainURLs) { 17310 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17311 "No domain URLs, so no need to verify any IntentFilter!"); 17312 return; 17313 } 17314 17315 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17316 + " if any IntentFilter from the " + size 17317 + " Activities needs verification ..."); 17318 17319 int count = 0; 17320 final String packageName = pkg.packageName; 17321 17322 synchronized (mPackages) { 17323 // If this is a new install and we see that we've already run verification for this 17324 // package, we have nothing to do: it means the state was restored from backup. 17325 if (!replacing) { 17326 IntentFilterVerificationInfo ivi = 17327 mSettings.getIntentFilterVerificationLPr(packageName); 17328 if (ivi != null) { 17329 if (DEBUG_DOMAIN_VERIFICATION) { 17330 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17331 + ivi.getStatusString()); 17332 } 17333 return; 17334 } 17335 } 17336 17337 // If any filters need to be verified, then all need to be. 17338 boolean needToVerify = false; 17339 for (PackageParser.Activity a : pkg.activities) { 17340 for (ActivityIntentInfo filter : a.intents) { 17341 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17342 if (DEBUG_DOMAIN_VERIFICATION) { 17343 Slog.d(TAG, 17344 "Intent filter needs verification, so processing all filters"); 17345 } 17346 needToVerify = true; 17347 break; 17348 } 17349 } 17350 } 17351 17352 if (needToVerify) { 17353 final int verificationId = mIntentFilterVerificationToken++; 17354 for (PackageParser.Activity a : pkg.activities) { 17355 for (ActivityIntentInfo filter : a.intents) { 17356 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17357 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17358 "Verification needed for IntentFilter:" + filter.toString()); 17359 mIntentFilterVerifier.addOneIntentFilterVerification( 17360 verifierUid, userId, verificationId, filter, packageName); 17361 count++; 17362 } 17363 } 17364 } 17365 } 17366 } 17367 17368 if (count > 0) { 17369 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17370 + " IntentFilter verification" + (count > 1 ? "s" : "") 17371 + " for userId:" + userId); 17372 mIntentFilterVerifier.startVerifications(userId); 17373 } else { 17374 if (DEBUG_DOMAIN_VERIFICATION) { 17375 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17376 } 17377 } 17378 } 17379 17380 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17381 final ComponentName cn = filter.activity.getComponentName(); 17382 final String packageName = cn.getPackageName(); 17383 17384 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17385 packageName); 17386 if (ivi == null) { 17387 return true; 17388 } 17389 int status = ivi.getStatus(); 17390 switch (status) { 17391 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17392 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17393 return true; 17394 17395 default: 17396 // Nothing to do 17397 return false; 17398 } 17399 } 17400 17401 private static boolean isMultiArch(ApplicationInfo info) { 17402 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17403 } 17404 17405 private static boolean isExternal(PackageParser.Package pkg) { 17406 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17407 } 17408 17409 private static boolean isExternal(PackageSetting ps) { 17410 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17411 } 17412 17413 private static boolean isSystemApp(PackageParser.Package pkg) { 17414 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17415 } 17416 17417 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17418 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17419 } 17420 17421 private static boolean isOemApp(PackageParser.Package pkg) { 17422 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17423 } 17424 17425 private static boolean isVendorApp(PackageParser.Package pkg) { 17426 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17427 } 17428 17429 private static boolean isProductApp(PackageParser.Package pkg) { 17430 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17431 } 17432 17433 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17434 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17435 } 17436 17437 private static boolean isSystemApp(PackageSetting ps) { 17438 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17439 } 17440 17441 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17442 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17443 } 17444 17445 private int packageFlagsToInstallFlags(PackageSetting ps) { 17446 int installFlags = 0; 17447 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17448 // This existing package was an external ASEC install when we have 17449 // the external flag without a UUID 17450 installFlags |= PackageManager.INSTALL_EXTERNAL; 17451 } 17452 if (ps.isForwardLocked()) { 17453 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17454 } 17455 return installFlags; 17456 } 17457 17458 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17459 if (isExternal(pkg)) { 17460 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17461 return mSettings.getExternalVersion(); 17462 } else { 17463 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17464 } 17465 } else { 17466 return mSettings.getInternalVersion(); 17467 } 17468 } 17469 17470 private void deleteTempPackageFiles() { 17471 final FilenameFilter filter = new FilenameFilter() { 17472 public boolean accept(File dir, String name) { 17473 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17474 } 17475 }; 17476 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17477 file.delete(); 17478 } 17479 } 17480 17481 @Override 17482 public void deletePackageAsUser(String packageName, int versionCode, 17483 IPackageDeleteObserver observer, int userId, int flags) { 17484 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17485 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17486 } 17487 17488 @Override 17489 public void deletePackageVersioned(VersionedPackage versionedPackage, 17490 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17491 final int callingUid = Binder.getCallingUid(); 17492 mContext.enforceCallingOrSelfPermission( 17493 android.Manifest.permission.DELETE_PACKAGES, null); 17494 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17495 Preconditions.checkNotNull(versionedPackage); 17496 Preconditions.checkNotNull(observer); 17497 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17498 PackageManager.VERSION_CODE_HIGHEST, 17499 Long.MAX_VALUE, "versionCode must be >= -1"); 17500 17501 final String packageName = versionedPackage.getPackageName(); 17502 final long versionCode = versionedPackage.getLongVersionCode(); 17503 final String internalPackageName; 17504 synchronized (mPackages) { 17505 // Normalize package name to handle renamed packages and static libs 17506 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17507 } 17508 17509 final int uid = Binder.getCallingUid(); 17510 if (!isOrphaned(internalPackageName) 17511 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17512 try { 17513 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17514 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17515 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17516 observer.onUserActionRequired(intent); 17517 } catch (RemoteException re) { 17518 } 17519 return; 17520 } 17521 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17522 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17523 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17524 mContext.enforceCallingOrSelfPermission( 17525 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17526 "deletePackage for user " + userId); 17527 } 17528 17529 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17530 try { 17531 observer.onPackageDeleted(packageName, 17532 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17533 } catch (RemoteException re) { 17534 } 17535 return; 17536 } 17537 17538 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17539 try { 17540 observer.onPackageDeleted(packageName, 17541 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17542 } catch (RemoteException re) { 17543 } 17544 return; 17545 } 17546 17547 if (DEBUG_REMOVE) { 17548 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17549 + " deleteAllUsers: " + deleteAllUsers + " version=" 17550 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17551 ? "VERSION_CODE_HIGHEST" : versionCode)); 17552 } 17553 // Queue up an async operation since the package deletion may take a little while. 17554 mHandler.post(new Runnable() { 17555 public void run() { 17556 mHandler.removeCallbacks(this); 17557 int returnCode; 17558 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17559 boolean doDeletePackage = true; 17560 if (ps != null) { 17561 final boolean targetIsInstantApp = 17562 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17563 doDeletePackage = !targetIsInstantApp 17564 || canViewInstantApps; 17565 } 17566 if (doDeletePackage) { 17567 if (!deleteAllUsers) { 17568 returnCode = deletePackageX(internalPackageName, versionCode, 17569 userId, deleteFlags); 17570 } else { 17571 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17572 internalPackageName, users); 17573 // If nobody is blocking uninstall, proceed with delete for all users 17574 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17575 returnCode = deletePackageX(internalPackageName, versionCode, 17576 userId, deleteFlags); 17577 } else { 17578 // Otherwise uninstall individually for users with blockUninstalls=false 17579 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17580 for (int userId : users) { 17581 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17582 returnCode = deletePackageX(internalPackageName, versionCode, 17583 userId, userFlags); 17584 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17585 Slog.w(TAG, "Package delete failed for user " + userId 17586 + ", returnCode " + returnCode); 17587 } 17588 } 17589 } 17590 // The app has only been marked uninstalled for certain users. 17591 // We still need to report that delete was blocked 17592 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17593 } 17594 } 17595 } else { 17596 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17597 } 17598 try { 17599 observer.onPackageDeleted(packageName, returnCode, null); 17600 } catch (RemoteException e) { 17601 Log.i(TAG, "Observer no longer exists."); 17602 } //end catch 17603 } //end run 17604 }); 17605 } 17606 17607 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17608 if (pkg.staticSharedLibName != null) { 17609 return pkg.manifestPackageName; 17610 } 17611 return pkg.packageName; 17612 } 17613 17614 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17615 // Handle renamed packages 17616 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17617 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17618 17619 // Is this a static library? 17620 LongSparseArray<SharedLibraryEntry> versionedLib = 17621 mStaticLibsByDeclaringPackage.get(packageName); 17622 if (versionedLib == null || versionedLib.size() <= 0) { 17623 return packageName; 17624 } 17625 17626 // Figure out which lib versions the caller can see 17627 LongSparseLongArray versionsCallerCanSee = null; 17628 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17629 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17630 && callingAppId != Process.ROOT_UID) { 17631 versionsCallerCanSee = new LongSparseLongArray(); 17632 String libName = versionedLib.valueAt(0).info.getName(); 17633 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17634 if (uidPackages != null) { 17635 for (String uidPackage : uidPackages) { 17636 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17637 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17638 if (libIdx >= 0) { 17639 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17640 versionsCallerCanSee.append(libVersion, libVersion); 17641 } 17642 } 17643 } 17644 } 17645 17646 // Caller can see nothing - done 17647 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17648 return packageName; 17649 } 17650 17651 // Find the version the caller can see and the app version code 17652 SharedLibraryEntry highestVersion = null; 17653 final int versionCount = versionedLib.size(); 17654 for (int i = 0; i < versionCount; i++) { 17655 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17656 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17657 libEntry.info.getLongVersion()) < 0) { 17658 continue; 17659 } 17660 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17661 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17662 if (libVersionCode == versionCode) { 17663 return libEntry.apk; 17664 } 17665 } else if (highestVersion == null) { 17666 highestVersion = libEntry; 17667 } else if (libVersionCode > highestVersion.info 17668 .getDeclaringPackage().getLongVersionCode()) { 17669 highestVersion = libEntry; 17670 } 17671 } 17672 17673 if (highestVersion != null) { 17674 return highestVersion.apk; 17675 } 17676 17677 return packageName; 17678 } 17679 17680 boolean isCallerVerifier(int callingUid) { 17681 final int callingUserId = UserHandle.getUserId(callingUid); 17682 return mRequiredVerifierPackage != null && 17683 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17684 } 17685 17686 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17687 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17688 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17689 return true; 17690 } 17691 final int callingUserId = UserHandle.getUserId(callingUid); 17692 // If the caller installed the pkgName, then allow it to silently uninstall. 17693 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17694 return true; 17695 } 17696 17697 // Allow package verifier to silently uninstall. 17698 if (mRequiredVerifierPackage != null && 17699 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17700 return true; 17701 } 17702 17703 // Allow package uninstaller to silently uninstall. 17704 if (mRequiredUninstallerPackage != null && 17705 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17706 return true; 17707 } 17708 17709 // Allow storage manager to silently uninstall. 17710 if (mStorageManagerPackage != null && 17711 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17712 return true; 17713 } 17714 17715 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17716 // uninstall for device owner provisioning. 17717 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17718 == PERMISSION_GRANTED) { 17719 return true; 17720 } 17721 17722 return false; 17723 } 17724 17725 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17726 int[] result = EMPTY_INT_ARRAY; 17727 for (int userId : userIds) { 17728 if (getBlockUninstallForUser(packageName, userId)) { 17729 result = ArrayUtils.appendInt(result, userId); 17730 } 17731 } 17732 return result; 17733 } 17734 17735 @Override 17736 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17737 final int callingUid = Binder.getCallingUid(); 17738 if (getInstantAppPackageName(callingUid) != null 17739 && !isCallerSameApp(packageName, callingUid)) { 17740 return false; 17741 } 17742 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17743 } 17744 17745 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17746 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17747 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17748 try { 17749 if (dpm != null) { 17750 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17751 /* callingUserOnly =*/ false); 17752 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17753 : deviceOwnerComponentName.getPackageName(); 17754 // Does the package contains the device owner? 17755 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17756 // this check is probably not needed, since DO should be registered as a device 17757 // admin on some user too. (Original bug for this: b/17657954) 17758 if (packageName.equals(deviceOwnerPackageName)) { 17759 return true; 17760 } 17761 // Does it contain a device admin for any user? 17762 int[] users; 17763 if (userId == UserHandle.USER_ALL) { 17764 users = sUserManager.getUserIds(); 17765 } else { 17766 users = new int[]{userId}; 17767 } 17768 for (int i = 0; i < users.length; ++i) { 17769 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17770 return true; 17771 } 17772 } 17773 } 17774 } catch (RemoteException e) { 17775 } 17776 return false; 17777 } 17778 17779 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17780 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17781 } 17782 17783 /** 17784 * This method is an internal method that could be get invoked either 17785 * to delete an installed package or to clean up a failed installation. 17786 * After deleting an installed package, a broadcast is sent to notify any 17787 * listeners that the package has been removed. For cleaning up a failed 17788 * installation, the broadcast is not necessary since the package's 17789 * installation wouldn't have sent the initial broadcast either 17790 * The key steps in deleting a package are 17791 * deleting the package information in internal structures like mPackages, 17792 * deleting the packages base directories through installd 17793 * updating mSettings to reflect current status 17794 * persisting settings for later use 17795 * sending a broadcast if necessary 17796 */ 17797 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17798 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17799 final boolean res; 17800 17801 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17802 ? UserHandle.USER_ALL : userId; 17803 17804 if (isPackageDeviceAdmin(packageName, removeUser)) { 17805 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17806 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17807 } 17808 17809 PackageSetting uninstalledPs = null; 17810 PackageParser.Package pkg = null; 17811 17812 // for the uninstall-updates case and restricted profiles, remember the per- 17813 // user handle installed state 17814 int[] allUsers; 17815 synchronized (mPackages) { 17816 uninstalledPs = mSettings.mPackages.get(packageName); 17817 if (uninstalledPs == null) { 17818 Slog.w(TAG, "Not removing non-existent package " + packageName); 17819 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17820 } 17821 17822 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17823 && uninstalledPs.versionCode != versionCode) { 17824 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17825 + uninstalledPs.versionCode + " != " + versionCode); 17826 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17827 } 17828 17829 // Static shared libs can be declared by any package, so let us not 17830 // allow removing a package if it provides a lib others depend on. 17831 pkg = mPackages.get(packageName); 17832 17833 allUsers = sUserManager.getUserIds(); 17834 17835 if (pkg != null && pkg.staticSharedLibName != null) { 17836 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17837 pkg.staticSharedLibVersion); 17838 if (libEntry != null) { 17839 for (int currUserId : allUsers) { 17840 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17841 continue; 17842 } 17843 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17844 libEntry.info, 0, currUserId); 17845 if (!ArrayUtils.isEmpty(libClientPackages)) { 17846 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17847 + " hosting lib " + libEntry.info.getName() + " version " 17848 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17849 + " for user " + currUserId); 17850 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17851 } 17852 } 17853 } 17854 } 17855 17856 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17857 } 17858 17859 final int freezeUser; 17860 if (isUpdatedSystemApp(uninstalledPs) 17861 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17862 // We're downgrading a system app, which will apply to all users, so 17863 // freeze them all during the downgrade 17864 freezeUser = UserHandle.USER_ALL; 17865 } else { 17866 freezeUser = removeUser; 17867 } 17868 17869 synchronized (mInstallLock) { 17870 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17871 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17872 deleteFlags, "deletePackageX")) { 17873 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17874 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17875 } 17876 synchronized (mPackages) { 17877 if (res) { 17878 if (pkg != null) { 17879 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17880 } 17881 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17882 updateInstantAppInstallerLocked(packageName); 17883 } 17884 } 17885 } 17886 17887 if (res) { 17888 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17889 info.sendPackageRemovedBroadcasts(killApp); 17890 info.sendSystemPackageUpdatedBroadcasts(); 17891 info.sendSystemPackageAppearedBroadcasts(); 17892 } 17893 // Force a gc here. 17894 Runtime.getRuntime().gc(); 17895 // Delete the resources here after sending the broadcast to let 17896 // other processes clean up before deleting resources. 17897 if (info.args != null) { 17898 synchronized (mInstallLock) { 17899 info.args.doPostDeleteLI(true); 17900 } 17901 } 17902 17903 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17904 } 17905 17906 static class PackageRemovedInfo { 17907 final PackageSender packageSender; 17908 String removedPackage; 17909 String installerPackageName; 17910 int uid = -1; 17911 int removedAppId = -1; 17912 int[] origUsers; 17913 int[] removedUsers = null; 17914 int[] broadcastUsers = null; 17915 int[] instantUserIds = null; 17916 SparseArray<Integer> installReasons; 17917 boolean isRemovedPackageSystemUpdate = false; 17918 boolean isUpdate; 17919 boolean dataRemoved; 17920 boolean removedForAllUsers; 17921 boolean isStaticSharedLib; 17922 // Clean up resources deleted packages. 17923 InstallArgs args = null; 17924 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17925 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17926 17927 PackageRemovedInfo(PackageSender packageSender) { 17928 this.packageSender = packageSender; 17929 } 17930 17931 void sendPackageRemovedBroadcasts(boolean killApp) { 17932 sendPackageRemovedBroadcastInternal(killApp); 17933 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17934 for (int i = 0; i < childCount; i++) { 17935 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17936 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17937 } 17938 } 17939 17940 void sendSystemPackageUpdatedBroadcasts() { 17941 if (isRemovedPackageSystemUpdate) { 17942 sendSystemPackageUpdatedBroadcastsInternal(); 17943 final int childCount = (removedChildPackages != null) 17944 ? removedChildPackages.size() : 0; 17945 for (int i = 0; i < childCount; i++) { 17946 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17947 if (childInfo.isRemovedPackageSystemUpdate) { 17948 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17949 } 17950 } 17951 } 17952 } 17953 17954 void sendSystemPackageAppearedBroadcasts() { 17955 final int packageCount = (appearedChildPackages != null) 17956 ? appearedChildPackages.size() : 0; 17957 for (int i = 0; i < packageCount; i++) { 17958 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17959 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17960 true /*sendBootCompleted*/, false /*startReceiver*/, 17961 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17962 } 17963 } 17964 17965 private void sendSystemPackageUpdatedBroadcastsInternal() { 17966 Bundle extras = new Bundle(2); 17967 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17968 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17969 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17970 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17971 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17972 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17973 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17974 null, null, 0, removedPackage, null, null, null); 17975 if (installerPackageName != null) { 17976 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17977 removedPackage, extras, 0 /*flags*/, 17978 installerPackageName, null, null, null); 17979 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17980 removedPackage, extras, 0 /*flags*/, 17981 installerPackageName, null, null, null); 17982 } 17983 } 17984 17985 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17986 // Don't send static shared library removal broadcasts as these 17987 // libs are visible only the the apps that depend on them an one 17988 // cannot remove the library if it has a dependency. 17989 if (isStaticSharedLib) { 17990 return; 17991 } 17992 Bundle extras = new Bundle(2); 17993 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17994 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17995 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17996 if (isUpdate || isRemovedPackageSystemUpdate) { 17997 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17998 } 17999 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18000 if (removedPackage != null) { 18001 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18002 removedPackage, extras, 0, null /*targetPackage*/, null, 18003 broadcastUsers, instantUserIds); 18004 if (installerPackageName != null) { 18005 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18006 removedPackage, extras, 0 /*flags*/, 18007 installerPackageName, null, broadcastUsers, instantUserIds); 18008 } 18009 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18010 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18011 removedPackage, extras, 18012 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18013 null, null, broadcastUsers, instantUserIds); 18014 packageSender.notifyPackageRemoved(removedPackage); 18015 } 18016 } 18017 if (removedAppId >= 0) { 18018 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18019 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18020 null, null, broadcastUsers, instantUserIds); 18021 } 18022 } 18023 18024 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18025 removedUsers = userIds; 18026 if (removedUsers == null) { 18027 broadcastUsers = null; 18028 return; 18029 } 18030 18031 broadcastUsers = EMPTY_INT_ARRAY; 18032 instantUserIds = EMPTY_INT_ARRAY; 18033 for (int i = userIds.length - 1; i >= 0; --i) { 18034 final int userId = userIds[i]; 18035 if (deletedPackageSetting.getInstantApp(userId)) { 18036 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18037 } else { 18038 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18039 } 18040 } 18041 } 18042 } 18043 18044 /* 18045 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18046 * flag is not set, the data directory is removed as well. 18047 * make sure this flag is set for partially installed apps. If not its meaningless to 18048 * delete a partially installed application. 18049 */ 18050 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18051 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18052 String packageName = ps.name; 18053 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18054 // Retrieve object to delete permissions for shared user later on 18055 final PackageParser.Package deletedPkg; 18056 final PackageSetting deletedPs; 18057 // reader 18058 synchronized (mPackages) { 18059 deletedPkg = mPackages.get(packageName); 18060 deletedPs = mSettings.mPackages.get(packageName); 18061 if (outInfo != null) { 18062 outInfo.removedPackage = packageName; 18063 outInfo.installerPackageName = ps.installerPackageName; 18064 outInfo.isStaticSharedLib = deletedPkg != null 18065 && deletedPkg.staticSharedLibName != null; 18066 outInfo.populateUsers(deletedPs == null ? null 18067 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18068 } 18069 } 18070 18071 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18072 18073 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18074 final PackageParser.Package resolvedPkg; 18075 if (deletedPkg != null) { 18076 resolvedPkg = deletedPkg; 18077 } else { 18078 // We don't have a parsed package when it lives on an ejected 18079 // adopted storage device, so fake something together 18080 resolvedPkg = new PackageParser.Package(ps.name); 18081 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18082 } 18083 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18084 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18085 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18086 if (outInfo != null) { 18087 outInfo.dataRemoved = true; 18088 } 18089 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18090 } 18091 18092 int removedAppId = -1; 18093 18094 // writer 18095 synchronized (mPackages) { 18096 boolean installedStateChanged = false; 18097 if (deletedPs != null) { 18098 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18099 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18100 clearDefaultBrowserIfNeeded(packageName); 18101 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18102 removedAppId = mSettings.removePackageLPw(packageName); 18103 if (outInfo != null) { 18104 outInfo.removedAppId = removedAppId; 18105 } 18106 mPermissionManager.updatePermissions( 18107 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18108 if (deletedPs.sharedUser != null) { 18109 // Remove permissions associated with package. Since runtime 18110 // permissions are per user we have to kill the removed package 18111 // or packages running under the shared user of the removed 18112 // package if revoking the permissions requested only by the removed 18113 // package is successful and this causes a change in gids. 18114 for (int userId : UserManagerService.getInstance().getUserIds()) { 18115 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18116 userId); 18117 if (userIdToKill == UserHandle.USER_ALL 18118 || userIdToKill >= UserHandle.USER_SYSTEM) { 18119 // If gids changed for this user, kill all affected packages. 18120 mHandler.post(new Runnable() { 18121 @Override 18122 public void run() { 18123 // This has to happen with no lock held. 18124 killApplication(deletedPs.name, deletedPs.appId, 18125 KILL_APP_REASON_GIDS_CHANGED); 18126 } 18127 }); 18128 break; 18129 } 18130 } 18131 } 18132 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18133 } 18134 // make sure to preserve per-user disabled state if this removal was just 18135 // a downgrade of a system app to the factory package 18136 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18137 if (DEBUG_REMOVE) { 18138 Slog.d(TAG, "Propagating install state across downgrade"); 18139 } 18140 for (int userId : allUserHandles) { 18141 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18142 if (DEBUG_REMOVE) { 18143 Slog.d(TAG, " user " + userId + " => " + installed); 18144 } 18145 if (installed != ps.getInstalled(userId)) { 18146 installedStateChanged = true; 18147 } 18148 ps.setInstalled(installed, userId); 18149 } 18150 } 18151 } 18152 // can downgrade to reader 18153 if (writeSettings) { 18154 // Save settings now 18155 mSettings.writeLPr(); 18156 } 18157 if (installedStateChanged) { 18158 mSettings.writeKernelMappingLPr(ps); 18159 } 18160 } 18161 if (removedAppId != -1) { 18162 // A user ID was deleted here. Go through all users and remove it 18163 // from KeyStore. 18164 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18165 } 18166 } 18167 18168 static boolean locationIsPrivileged(String path) { 18169 try { 18170 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18171 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18172 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18173 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18174 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18175 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18176 } catch (IOException e) { 18177 Slog.e(TAG, "Unable to access code path " + path); 18178 } 18179 return false; 18180 } 18181 18182 static boolean locationIsOem(String path) { 18183 try { 18184 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18185 } catch (IOException e) { 18186 Slog.e(TAG, "Unable to access code path " + path); 18187 } 18188 return false; 18189 } 18190 18191 static boolean locationIsVendor(String path) { 18192 try { 18193 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18194 } catch (IOException e) { 18195 Slog.e(TAG, "Unable to access code path " + path); 18196 } 18197 return false; 18198 } 18199 18200 static boolean locationIsProduct(String path) { 18201 try { 18202 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18203 } catch (IOException e) { 18204 Slog.e(TAG, "Unable to access code path " + path); 18205 } 18206 return false; 18207 } 18208 18209 /* 18210 * Tries to delete system package. 18211 */ 18212 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18213 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18214 boolean writeSettings) { 18215 if (deletedPs.parentPackageName != null) { 18216 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18217 return false; 18218 } 18219 18220 final boolean applyUserRestrictions 18221 = (allUserHandles != null) && (outInfo.origUsers != null); 18222 final PackageSetting disabledPs; 18223 // Confirm if the system package has been updated 18224 // An updated system app can be deleted. This will also have to restore 18225 // the system pkg from system partition 18226 // reader 18227 synchronized (mPackages) { 18228 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18229 } 18230 18231 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18232 + " disabledPs=" + disabledPs); 18233 18234 if (disabledPs == null) { 18235 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18236 return false; 18237 } else if (DEBUG_REMOVE) { 18238 Slog.d(TAG, "Deleting system pkg from data partition"); 18239 } 18240 18241 if (DEBUG_REMOVE) { 18242 if (applyUserRestrictions) { 18243 Slog.d(TAG, "Remembering install states:"); 18244 for (int userId : allUserHandles) { 18245 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18246 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18247 } 18248 } 18249 } 18250 18251 // Delete the updated package 18252 outInfo.isRemovedPackageSystemUpdate = true; 18253 if (outInfo.removedChildPackages != null) { 18254 final int childCount = (deletedPs.childPackageNames != null) 18255 ? deletedPs.childPackageNames.size() : 0; 18256 for (int i = 0; i < childCount; i++) { 18257 String childPackageName = deletedPs.childPackageNames.get(i); 18258 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18259 .contains(childPackageName)) { 18260 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18261 childPackageName); 18262 if (childInfo != null) { 18263 childInfo.isRemovedPackageSystemUpdate = true; 18264 } 18265 } 18266 } 18267 } 18268 18269 if (disabledPs.versionCode < deletedPs.versionCode) { 18270 // Delete data for downgrades 18271 flags &= ~PackageManager.DELETE_KEEP_DATA; 18272 } else { 18273 // Preserve data by setting flag 18274 flags |= PackageManager.DELETE_KEEP_DATA; 18275 } 18276 18277 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18278 outInfo, writeSettings, disabledPs.pkg); 18279 if (!ret) { 18280 return false; 18281 } 18282 18283 // writer 18284 synchronized (mPackages) { 18285 // NOTE: The system package always needs to be enabled; even if it's for 18286 // a compressed stub. If we don't, installing the system package fails 18287 // during scan [scanning checks the disabled packages]. We will reverse 18288 // this later, after we've "installed" the stub. 18289 // Reinstate the old system package 18290 enableSystemPackageLPw(disabledPs.pkg); 18291 // Remove any native libraries from the upgraded package. 18292 removeNativeBinariesLI(deletedPs); 18293 } 18294 18295 // Install the system package 18296 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18297 try { 18298 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18299 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18300 } catch (PackageManagerException e) { 18301 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18302 + e.getMessage()); 18303 return false; 18304 } finally { 18305 if (disabledPs.pkg.isStub) { 18306 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18307 } 18308 } 18309 return true; 18310 } 18311 18312 /** 18313 * Installs a package that's already on the system partition. 18314 */ 18315 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18316 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18317 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18318 throws PackageManagerException { 18319 @ParseFlags int parseFlags = 18320 mDefParseFlags 18321 | PackageParser.PARSE_MUST_BE_APK 18322 | PackageParser.PARSE_IS_SYSTEM_DIR; 18323 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18324 if (isPrivileged || locationIsPrivileged(codePathString)) { 18325 scanFlags |= SCAN_AS_PRIVILEGED; 18326 } 18327 if (locationIsOem(codePathString)) { 18328 scanFlags |= SCAN_AS_OEM; 18329 } 18330 if (locationIsVendor(codePathString)) { 18331 scanFlags |= SCAN_AS_VENDOR; 18332 } 18333 if (locationIsProduct(codePathString)) { 18334 scanFlags |= SCAN_AS_PRODUCT; 18335 } 18336 18337 final File codePath = new File(codePathString); 18338 final PackageParser.Package pkg = 18339 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18340 18341 try { 18342 // update shared libraries for the newly re-installed system package 18343 updateSharedLibrariesLPr(pkg, null); 18344 } catch (PackageManagerException e) { 18345 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18346 } 18347 18348 prepareAppDataAfterInstallLIF(pkg); 18349 18350 // writer 18351 synchronized (mPackages) { 18352 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18353 18354 // Propagate the permissions state as we do not want to drop on the floor 18355 // runtime permissions. The update permissions method below will take 18356 // care of removing obsolete permissions and grant install permissions. 18357 if (origPermissionState != null) { 18358 ps.getPermissionsState().copyFrom(origPermissionState); 18359 } 18360 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18361 mPermissionCallback); 18362 18363 final boolean applyUserRestrictions 18364 = (allUserHandles != null) && (origUserHandles != null); 18365 if (applyUserRestrictions) { 18366 boolean installedStateChanged = false; 18367 if (DEBUG_REMOVE) { 18368 Slog.d(TAG, "Propagating install state across reinstall"); 18369 } 18370 for (int userId : allUserHandles) { 18371 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18372 if (DEBUG_REMOVE) { 18373 Slog.d(TAG, " user " + userId + " => " + installed); 18374 } 18375 if (installed != ps.getInstalled(userId)) { 18376 installedStateChanged = true; 18377 } 18378 ps.setInstalled(installed, userId); 18379 18380 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18381 } 18382 // Regardless of writeSettings we need to ensure that this restriction 18383 // state propagation is persisted 18384 mSettings.writeAllUsersPackageRestrictionsLPr(); 18385 if (installedStateChanged) { 18386 mSettings.writeKernelMappingLPr(ps); 18387 } 18388 } 18389 // can downgrade to reader here 18390 if (writeSettings) { 18391 mSettings.writeLPr(); 18392 } 18393 } 18394 return pkg; 18395 } 18396 18397 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18398 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18399 PackageRemovedInfo outInfo, boolean writeSettings, 18400 PackageParser.Package replacingPackage) { 18401 synchronized (mPackages) { 18402 if (outInfo != null) { 18403 outInfo.uid = ps.appId; 18404 } 18405 18406 if (outInfo != null && outInfo.removedChildPackages != null) { 18407 final int childCount = (ps.childPackageNames != null) 18408 ? ps.childPackageNames.size() : 0; 18409 for (int i = 0; i < childCount; i++) { 18410 String childPackageName = ps.childPackageNames.get(i); 18411 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18412 if (childPs == null) { 18413 return false; 18414 } 18415 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18416 childPackageName); 18417 if (childInfo != null) { 18418 childInfo.uid = childPs.appId; 18419 } 18420 } 18421 } 18422 } 18423 18424 // Delete package data from internal structures and also remove data if flag is set 18425 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18426 18427 // Delete the child packages data 18428 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18429 for (int i = 0; i < childCount; i++) { 18430 PackageSetting childPs; 18431 synchronized (mPackages) { 18432 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18433 } 18434 if (childPs != null) { 18435 PackageRemovedInfo childOutInfo = (outInfo != null 18436 && outInfo.removedChildPackages != null) 18437 ? outInfo.removedChildPackages.get(childPs.name) : null; 18438 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18439 && (replacingPackage != null 18440 && !replacingPackage.hasChildPackage(childPs.name)) 18441 ? flags & ~DELETE_KEEP_DATA : flags; 18442 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18443 deleteFlags, writeSettings); 18444 } 18445 } 18446 18447 // Delete application code and resources only for parent packages 18448 if (ps.parentPackageName == null) { 18449 if (deleteCodeAndResources && (outInfo != null)) { 18450 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18451 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18452 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18453 } 18454 } 18455 18456 return true; 18457 } 18458 18459 @Override 18460 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18461 int userId) { 18462 mContext.enforceCallingOrSelfPermission( 18463 android.Manifest.permission.DELETE_PACKAGES, null); 18464 synchronized (mPackages) { 18465 // Cannot block uninstall of static shared libs as they are 18466 // considered a part of the using app (emulating static linking). 18467 // Also static libs are installed always on internal storage. 18468 PackageParser.Package pkg = mPackages.get(packageName); 18469 if (pkg != null && pkg.staticSharedLibName != null) { 18470 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18471 + " providing static shared library: " + pkg.staticSharedLibName); 18472 return false; 18473 } 18474 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18475 mSettings.writePackageRestrictionsLPr(userId); 18476 } 18477 return true; 18478 } 18479 18480 @Override 18481 public boolean getBlockUninstallForUser(String packageName, int userId) { 18482 synchronized (mPackages) { 18483 final PackageSetting ps = mSettings.mPackages.get(packageName); 18484 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18485 return false; 18486 } 18487 return mSettings.getBlockUninstallLPr(userId, packageName); 18488 } 18489 } 18490 18491 @Override 18492 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18493 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18494 synchronized (mPackages) { 18495 PackageSetting ps = mSettings.mPackages.get(packageName); 18496 if (ps == null) { 18497 Log.w(TAG, "Package doesn't exist: " + packageName); 18498 return false; 18499 } 18500 if (systemUserApp) { 18501 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18502 } else { 18503 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18504 } 18505 mSettings.writeLPr(); 18506 } 18507 return true; 18508 } 18509 18510 /* 18511 * This method handles package deletion in general 18512 */ 18513 private boolean deletePackageLIF(String packageName, UserHandle user, 18514 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18515 PackageRemovedInfo outInfo, boolean writeSettings, 18516 PackageParser.Package replacingPackage) { 18517 if (packageName == null) { 18518 Slog.w(TAG, "Attempt to delete null packageName."); 18519 return false; 18520 } 18521 18522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18523 18524 PackageSetting ps; 18525 synchronized (mPackages) { 18526 ps = mSettings.mPackages.get(packageName); 18527 if (ps == null) { 18528 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18529 return false; 18530 } 18531 18532 if (ps.parentPackageName != null && (!isSystemApp(ps) 18533 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18534 if (DEBUG_REMOVE) { 18535 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18536 + ((user == null) ? UserHandle.USER_ALL : user)); 18537 } 18538 final int removedUserId = (user != null) ? user.getIdentifier() 18539 : UserHandle.USER_ALL; 18540 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18541 return false; 18542 } 18543 markPackageUninstalledForUserLPw(ps, user); 18544 scheduleWritePackageRestrictionsLocked(user); 18545 return true; 18546 } 18547 } 18548 18549 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18550 && user.getIdentifier() != UserHandle.USER_ALL)) { 18551 // The caller is asking that the package only be deleted for a single 18552 // user. To do this, we just mark its uninstalled state and delete 18553 // its data. If this is a system app, we only allow this to happen if 18554 // they have set the special DELETE_SYSTEM_APP which requests different 18555 // semantics than normal for uninstalling system apps. 18556 markPackageUninstalledForUserLPw(ps, user); 18557 18558 if (!isSystemApp(ps)) { 18559 // Do not uninstall the APK if an app should be cached 18560 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18561 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18562 // Other user still have this package installed, so all 18563 // we need to do is clear this user's data and save that 18564 // it is uninstalled. 18565 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18566 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18567 return false; 18568 } 18569 scheduleWritePackageRestrictionsLocked(user); 18570 return true; 18571 } else { 18572 // We need to set it back to 'installed' so the uninstall 18573 // broadcasts will be sent correctly. 18574 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18575 ps.setInstalled(true, user.getIdentifier()); 18576 mSettings.writeKernelMappingLPr(ps); 18577 } 18578 } else { 18579 // This is a system app, so we assume that the 18580 // other users still have this package installed, so all 18581 // we need to do is clear this user's data and save that 18582 // it is uninstalled. 18583 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18584 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18585 return false; 18586 } 18587 scheduleWritePackageRestrictionsLocked(user); 18588 return true; 18589 } 18590 } 18591 18592 // If we are deleting a composite package for all users, keep track 18593 // of result for each child. 18594 if (ps.childPackageNames != null && outInfo != null) { 18595 synchronized (mPackages) { 18596 final int childCount = ps.childPackageNames.size(); 18597 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18598 for (int i = 0; i < childCount; i++) { 18599 String childPackageName = ps.childPackageNames.get(i); 18600 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18601 childInfo.removedPackage = childPackageName; 18602 childInfo.installerPackageName = ps.installerPackageName; 18603 outInfo.removedChildPackages.put(childPackageName, childInfo); 18604 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18605 if (childPs != null) { 18606 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18607 } 18608 } 18609 } 18610 } 18611 18612 boolean ret = false; 18613 if (isSystemApp(ps)) { 18614 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18615 // When an updated system application is deleted we delete the existing resources 18616 // as well and fall back to existing code in system partition 18617 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18618 } else { 18619 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18620 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18621 outInfo, writeSettings, replacingPackage); 18622 } 18623 18624 // Take a note whether we deleted the package for all users 18625 if (outInfo != null) { 18626 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18627 if (outInfo.removedChildPackages != null) { 18628 synchronized (mPackages) { 18629 final int childCount = outInfo.removedChildPackages.size(); 18630 for (int i = 0; i < childCount; i++) { 18631 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18632 if (childInfo != null) { 18633 childInfo.removedForAllUsers = mPackages.get( 18634 childInfo.removedPackage) == null; 18635 } 18636 } 18637 } 18638 } 18639 // If we uninstalled an update to a system app there may be some 18640 // child packages that appeared as they are declared in the system 18641 // app but were not declared in the update. 18642 if (isSystemApp(ps)) { 18643 synchronized (mPackages) { 18644 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18645 final int childCount = (updatedPs.childPackageNames != null) 18646 ? updatedPs.childPackageNames.size() : 0; 18647 for (int i = 0; i < childCount; i++) { 18648 String childPackageName = updatedPs.childPackageNames.get(i); 18649 if (outInfo.removedChildPackages == null 18650 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18651 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18652 if (childPs == null) { 18653 continue; 18654 } 18655 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18656 installRes.name = childPackageName; 18657 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18658 installRes.pkg = mPackages.get(childPackageName); 18659 installRes.uid = childPs.pkg.applicationInfo.uid; 18660 if (outInfo.appearedChildPackages == null) { 18661 outInfo.appearedChildPackages = new ArrayMap<>(); 18662 } 18663 outInfo.appearedChildPackages.put(childPackageName, installRes); 18664 } 18665 } 18666 } 18667 } 18668 } 18669 18670 return ret; 18671 } 18672 18673 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18674 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18675 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18676 for (int nextUserId : userIds) { 18677 if (DEBUG_REMOVE) { 18678 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18679 } 18680 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18681 false /*installed*/, 18682 true /*stopped*/, 18683 true /*notLaunched*/, 18684 false /*hidden*/, 18685 false /*suspended*/, 18686 false /*instantApp*/, 18687 false /*virtualPreload*/, 18688 null /*lastDisableAppCaller*/, 18689 null /*enabledComponents*/, 18690 null /*disabledComponents*/, 18691 ps.readUserState(nextUserId).domainVerificationStatus, 18692 0, PackageManager.INSTALL_REASON_UNKNOWN, 18693 null /*harmfulAppWarning*/); 18694 } 18695 mSettings.writeKernelMappingLPr(ps); 18696 } 18697 18698 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18699 PackageRemovedInfo outInfo) { 18700 final PackageParser.Package pkg; 18701 synchronized (mPackages) { 18702 pkg = mPackages.get(ps.name); 18703 } 18704 18705 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18706 : new int[] {userId}; 18707 for (int nextUserId : userIds) { 18708 if (DEBUG_REMOVE) { 18709 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18710 + nextUserId); 18711 } 18712 18713 destroyAppDataLIF(pkg, userId, 18714 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18715 destroyAppProfilesLIF(pkg, userId); 18716 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18717 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18718 schedulePackageCleaning(ps.name, nextUserId, false); 18719 synchronized (mPackages) { 18720 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18721 scheduleWritePackageRestrictionsLocked(nextUserId); 18722 } 18723 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18724 } 18725 } 18726 18727 if (outInfo != null) { 18728 outInfo.removedPackage = ps.name; 18729 outInfo.installerPackageName = ps.installerPackageName; 18730 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18731 outInfo.removedAppId = ps.appId; 18732 outInfo.removedUsers = userIds; 18733 outInfo.broadcastUsers = userIds; 18734 } 18735 18736 return true; 18737 } 18738 18739 private static final class ClearStorageConnection implements ServiceConnection { 18740 IMediaContainerService mContainerService; 18741 18742 @Override 18743 public void onServiceConnected(ComponentName name, IBinder service) { 18744 synchronized (this) { 18745 mContainerService = IMediaContainerService.Stub 18746 .asInterface(Binder.allowBlocking(service)); 18747 notifyAll(); 18748 } 18749 } 18750 18751 @Override 18752 public void onServiceDisconnected(ComponentName name) { 18753 } 18754 } 18755 18756 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18757 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18758 18759 final boolean mounted; 18760 if (Environment.isExternalStorageEmulated()) { 18761 mounted = true; 18762 } else { 18763 final String status = Environment.getExternalStorageState(); 18764 18765 mounted = status.equals(Environment.MEDIA_MOUNTED) 18766 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18767 } 18768 18769 if (!mounted) { 18770 return; 18771 } 18772 18773 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18774 int[] users; 18775 if (userId == UserHandle.USER_ALL) { 18776 users = sUserManager.getUserIds(); 18777 } else { 18778 users = new int[] { userId }; 18779 } 18780 final ClearStorageConnection conn = new ClearStorageConnection(); 18781 if (mContext.bindServiceAsUser( 18782 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18783 try { 18784 for (int curUser : users) { 18785 long timeout = SystemClock.uptimeMillis() + 5000; 18786 synchronized (conn) { 18787 long now; 18788 while (conn.mContainerService == null && 18789 (now = SystemClock.uptimeMillis()) < timeout) { 18790 try { 18791 conn.wait(timeout - now); 18792 } catch (InterruptedException e) { 18793 } 18794 } 18795 } 18796 if (conn.mContainerService == null) { 18797 return; 18798 } 18799 18800 final UserEnvironment userEnv = new UserEnvironment(curUser); 18801 clearDirectory(conn.mContainerService, 18802 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18803 if (allData) { 18804 clearDirectory(conn.mContainerService, 18805 userEnv.buildExternalStorageAppDataDirs(packageName)); 18806 clearDirectory(conn.mContainerService, 18807 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18808 } 18809 } 18810 } finally { 18811 mContext.unbindService(conn); 18812 } 18813 } 18814 } 18815 18816 @Override 18817 public void clearApplicationProfileData(String packageName) { 18818 enforceSystemOrRoot("Only the system can clear all profile data"); 18819 18820 final PackageParser.Package pkg; 18821 synchronized (mPackages) { 18822 pkg = mPackages.get(packageName); 18823 } 18824 18825 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18826 synchronized (mInstallLock) { 18827 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18828 } 18829 } 18830 } 18831 18832 @Override 18833 public void clearApplicationUserData(final String packageName, 18834 final IPackageDataObserver observer, final int userId) { 18835 mContext.enforceCallingOrSelfPermission( 18836 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18837 18838 final int callingUid = Binder.getCallingUid(); 18839 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18840 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18841 18842 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18843 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18844 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18845 throw new SecurityException("Cannot clear data for a protected package: " 18846 + packageName); 18847 } 18848 // Queue up an async operation since the package deletion may take a little while. 18849 mHandler.post(new Runnable() { 18850 public void run() { 18851 mHandler.removeCallbacks(this); 18852 final boolean succeeded; 18853 if (!filterApp) { 18854 try (PackageFreezer freezer = freezePackage(packageName, 18855 "clearApplicationUserData")) { 18856 synchronized (mInstallLock) { 18857 succeeded = clearApplicationUserDataLIF(packageName, userId); 18858 } 18859 clearExternalStorageDataSync(packageName, userId, true); 18860 synchronized (mPackages) { 18861 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18862 packageName, userId); 18863 } 18864 } 18865 if (succeeded) { 18866 // invoke DeviceStorageMonitor's update method to clear any notifications 18867 DeviceStorageMonitorInternal dsm = LocalServices 18868 .getService(DeviceStorageMonitorInternal.class); 18869 if (dsm != null) { 18870 dsm.checkMemory(); 18871 } 18872 } 18873 } else { 18874 succeeded = false; 18875 } 18876 if (observer != null) { 18877 try { 18878 observer.onRemoveCompleted(packageName, succeeded); 18879 } catch (RemoteException e) { 18880 Log.i(TAG, "Observer no longer exists."); 18881 } 18882 } //end if observer 18883 } //end run 18884 }); 18885 } 18886 18887 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18888 if (packageName == null) { 18889 Slog.w(TAG, "Attempt to delete null packageName."); 18890 return false; 18891 } 18892 18893 // Try finding details about the requested package 18894 PackageParser.Package pkg; 18895 synchronized (mPackages) { 18896 pkg = mPackages.get(packageName); 18897 if (pkg == null) { 18898 final PackageSetting ps = mSettings.mPackages.get(packageName); 18899 if (ps != null) { 18900 pkg = ps.pkg; 18901 } 18902 } 18903 18904 if (pkg == null) { 18905 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18906 return false; 18907 } 18908 18909 PackageSetting ps = (PackageSetting) pkg.mExtras; 18910 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18911 } 18912 18913 clearAppDataLIF(pkg, userId, 18914 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18915 18916 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18917 removeKeystoreDataIfNeeded(userId, appId); 18918 18919 UserManagerInternal umInternal = getUserManagerInternal(); 18920 final int flags; 18921 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18922 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18923 } else if (umInternal.isUserRunning(userId)) { 18924 flags = StorageManager.FLAG_STORAGE_DE; 18925 } else { 18926 flags = 0; 18927 } 18928 prepareAppDataContentsLIF(pkg, userId, flags); 18929 18930 return true; 18931 } 18932 18933 /** 18934 * Reverts user permission state changes (permissions and flags) in 18935 * all packages for a given user. 18936 * 18937 * @param userId The device user for which to do a reset. 18938 */ 18939 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18940 final int packageCount = mPackages.size(); 18941 for (int i = 0; i < packageCount; i++) { 18942 PackageParser.Package pkg = mPackages.valueAt(i); 18943 PackageSetting ps = (PackageSetting) pkg.mExtras; 18944 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18945 } 18946 } 18947 18948 private void resetNetworkPolicies(int userId) { 18949 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18950 } 18951 18952 /** 18953 * Reverts user permission state changes (permissions and flags). 18954 * 18955 * @param ps The package for which to reset. 18956 * @param userId The device user for which to do a reset. 18957 */ 18958 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18959 final PackageSetting ps, final int userId) { 18960 if (ps.pkg == null) { 18961 return; 18962 } 18963 18964 // These are flags that can change base on user actions. 18965 final int userSettableMask = FLAG_PERMISSION_USER_SET 18966 | FLAG_PERMISSION_USER_FIXED 18967 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18968 | FLAG_PERMISSION_REVIEW_REQUIRED; 18969 18970 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18971 | FLAG_PERMISSION_POLICY_FIXED; 18972 18973 boolean writeInstallPermissions = false; 18974 boolean writeRuntimePermissions = false; 18975 18976 final int permissionCount = ps.pkg.requestedPermissions.size(); 18977 for (int i = 0; i < permissionCount; i++) { 18978 final String permName = ps.pkg.requestedPermissions.get(i); 18979 final BasePermission bp = 18980 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18981 if (bp == null) { 18982 continue; 18983 } 18984 18985 // If shared user we just reset the state to which only this app contributed. 18986 if (ps.sharedUser != null) { 18987 boolean used = false; 18988 final int packageCount = ps.sharedUser.packages.size(); 18989 for (int j = 0; j < packageCount; j++) { 18990 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18991 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18992 && pkg.pkg.requestedPermissions.contains(permName)) { 18993 used = true; 18994 break; 18995 } 18996 } 18997 if (used) { 18998 continue; 18999 } 19000 } 19001 19002 final PermissionsState permissionsState = ps.getPermissionsState(); 19003 19004 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19005 19006 // Always clear the user settable flags. 19007 final boolean hasInstallState = 19008 permissionsState.getInstallPermissionState(permName) != null; 19009 // If permission review is enabled and this is a legacy app, mark the 19010 // permission as requiring a review as this is the initial state. 19011 int flags = 0; 19012 if (mSettings.mPermissions.mPermissionReviewRequired 19013 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19014 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19015 } 19016 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19017 if (hasInstallState) { 19018 writeInstallPermissions = true; 19019 } else { 19020 writeRuntimePermissions = true; 19021 } 19022 } 19023 19024 // Below is only runtime permission handling. 19025 if (!bp.isRuntime()) { 19026 continue; 19027 } 19028 19029 // Never clobber system or policy. 19030 if ((oldFlags & policyOrSystemFlags) != 0) { 19031 continue; 19032 } 19033 19034 // If this permission was granted by default, make sure it is. 19035 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19036 if (permissionsState.grantRuntimePermission(bp, userId) 19037 != PERMISSION_OPERATION_FAILURE) { 19038 writeRuntimePermissions = true; 19039 } 19040 // If permission review is enabled the permissions for a legacy apps 19041 // are represented as constantly granted runtime ones, so don't revoke. 19042 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19043 // Otherwise, reset the permission. 19044 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19045 switch (revokeResult) { 19046 case PERMISSION_OPERATION_SUCCESS: 19047 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19048 writeRuntimePermissions = true; 19049 final int appId = ps.appId; 19050 mHandler.post(new Runnable() { 19051 @Override 19052 public void run() { 19053 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19054 } 19055 }); 19056 } break; 19057 } 19058 } 19059 } 19060 19061 // Synchronously write as we are taking permissions away. 19062 if (writeRuntimePermissions) { 19063 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19064 } 19065 19066 // Synchronously write as we are taking permissions away. 19067 if (writeInstallPermissions) { 19068 mSettings.writeLPr(); 19069 } 19070 } 19071 19072 /** 19073 * Remove entries from the keystore daemon. Will only remove it if the 19074 * {@code appId} is valid. 19075 */ 19076 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19077 if (appId < 0) { 19078 return; 19079 } 19080 19081 final KeyStore keyStore = KeyStore.getInstance(); 19082 if (keyStore != null) { 19083 if (userId == UserHandle.USER_ALL) { 19084 for (final int individual : sUserManager.getUserIds()) { 19085 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19086 } 19087 } else { 19088 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19089 } 19090 } else { 19091 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19092 } 19093 } 19094 19095 @Override 19096 public void deleteApplicationCacheFiles(final String packageName, 19097 final IPackageDataObserver observer) { 19098 final int userId = UserHandle.getCallingUserId(); 19099 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19100 } 19101 19102 @Override 19103 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19104 final IPackageDataObserver observer) { 19105 final int callingUid = Binder.getCallingUid(); 19106 if (mContext.checkCallingOrSelfPermission( 19107 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19108 != PackageManager.PERMISSION_GRANTED) { 19109 // If the caller has the old delete cache permission, silently ignore. Else throw. 19110 if (mContext.checkCallingOrSelfPermission( 19111 android.Manifest.permission.DELETE_CACHE_FILES) 19112 == PackageManager.PERMISSION_GRANTED) { 19113 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19114 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19115 ", silently ignoring"); 19116 return; 19117 } 19118 mContext.enforceCallingOrSelfPermission( 19119 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19120 } 19121 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19122 /* requireFullPermission= */ true, /* checkShell= */ false, 19123 "delete application cache files"); 19124 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19125 android.Manifest.permission.ACCESS_INSTANT_APPS); 19126 19127 final PackageParser.Package pkg; 19128 synchronized (mPackages) { 19129 pkg = mPackages.get(packageName); 19130 } 19131 19132 // Queue up an async operation since the package deletion may take a little while. 19133 mHandler.post(new Runnable() { 19134 public void run() { 19135 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19136 boolean doClearData = true; 19137 if (ps != null) { 19138 final boolean targetIsInstantApp = 19139 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19140 doClearData = !targetIsInstantApp 19141 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19142 } 19143 if (doClearData) { 19144 synchronized (mInstallLock) { 19145 final int flags = StorageManager.FLAG_STORAGE_DE 19146 | StorageManager.FLAG_STORAGE_CE; 19147 // We're only clearing cache files, so we don't care if the 19148 // app is unfrozen and still able to run 19149 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19150 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19151 } 19152 clearExternalStorageDataSync(packageName, userId, false); 19153 } 19154 if (observer != null) { 19155 try { 19156 observer.onRemoveCompleted(packageName, true); 19157 } catch (RemoteException e) { 19158 Log.i(TAG, "Observer no longer exists."); 19159 } 19160 } 19161 } 19162 }); 19163 } 19164 19165 @Override 19166 public void getPackageSizeInfo(final String packageName, int userHandle, 19167 final IPackageStatsObserver observer) { 19168 throw new UnsupportedOperationException( 19169 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19170 } 19171 19172 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19173 final PackageSetting ps; 19174 synchronized (mPackages) { 19175 ps = mSettings.mPackages.get(packageName); 19176 if (ps == null) { 19177 Slog.w(TAG, "Failed to find settings for " + packageName); 19178 return false; 19179 } 19180 } 19181 19182 final String[] packageNames = { packageName }; 19183 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19184 final String[] codePaths = { ps.codePathString }; 19185 19186 try { 19187 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19188 ps.appId, ceDataInodes, codePaths, stats); 19189 19190 // For now, ignore code size of packages on system partition 19191 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19192 stats.codeSize = 0; 19193 } 19194 19195 // External clients expect these to be tracked separately 19196 stats.dataSize -= stats.cacheSize; 19197 19198 } catch (InstallerException e) { 19199 Slog.w(TAG, String.valueOf(e)); 19200 return false; 19201 } 19202 19203 return true; 19204 } 19205 19206 private int getUidTargetSdkVersionLockedLPr(int uid) { 19207 Object obj = mSettings.getUserIdLPr(uid); 19208 if (obj instanceof SharedUserSetting) { 19209 final SharedUserSetting sus = (SharedUserSetting) obj; 19210 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19211 final Iterator<PackageSetting> it = sus.packages.iterator(); 19212 while (it.hasNext()) { 19213 final PackageSetting ps = it.next(); 19214 if (ps.pkg != null) { 19215 int v = ps.pkg.applicationInfo.targetSdkVersion; 19216 if (v < vers) vers = v; 19217 } 19218 } 19219 return vers; 19220 } else if (obj instanceof PackageSetting) { 19221 final PackageSetting ps = (PackageSetting) obj; 19222 if (ps.pkg != null) { 19223 return ps.pkg.applicationInfo.targetSdkVersion; 19224 } 19225 } 19226 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19227 } 19228 19229 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19230 final PackageParser.Package p = mPackages.get(packageName); 19231 if (p != null) { 19232 return p.applicationInfo.targetSdkVersion; 19233 } 19234 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19235 } 19236 19237 @Override 19238 public void addPreferredActivity(IntentFilter filter, int match, 19239 ComponentName[] set, ComponentName activity, int userId) { 19240 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19241 "Adding preferred"); 19242 } 19243 19244 private void addPreferredActivityInternal(IntentFilter filter, int match, 19245 ComponentName[] set, ComponentName activity, boolean always, int userId, 19246 String opname) { 19247 // writer 19248 int callingUid = Binder.getCallingUid(); 19249 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19250 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19251 if (filter.countActions() == 0) { 19252 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19253 return; 19254 } 19255 synchronized (mPackages) { 19256 if (mContext.checkCallingOrSelfPermission( 19257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19258 != PackageManager.PERMISSION_GRANTED) { 19259 if (getUidTargetSdkVersionLockedLPr(callingUid) 19260 < Build.VERSION_CODES.FROYO) { 19261 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19262 + callingUid); 19263 return; 19264 } 19265 mContext.enforceCallingOrSelfPermission( 19266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19267 } 19268 19269 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19270 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19271 + userId + ":"); 19272 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19273 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19274 scheduleWritePackageRestrictionsLocked(userId); 19275 postPreferredActivityChangedBroadcast(userId); 19276 } 19277 } 19278 19279 private void postPreferredActivityChangedBroadcast(int userId) { 19280 mHandler.post(() -> { 19281 final IActivityManager am = ActivityManager.getService(); 19282 if (am == null) { 19283 return; 19284 } 19285 19286 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19287 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19288 try { 19289 am.broadcastIntent(null, intent, null, null, 19290 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19291 null, false, false, userId); 19292 } catch (RemoteException e) { 19293 } 19294 }); 19295 } 19296 19297 @Override 19298 public void replacePreferredActivity(IntentFilter filter, int match, 19299 ComponentName[] set, ComponentName activity, int userId) { 19300 if (filter.countActions() != 1) { 19301 throw new IllegalArgumentException( 19302 "replacePreferredActivity expects filter to have only 1 action."); 19303 } 19304 if (filter.countDataAuthorities() != 0 19305 || filter.countDataPaths() != 0 19306 || filter.countDataSchemes() > 1 19307 || filter.countDataTypes() != 0) { 19308 throw new IllegalArgumentException( 19309 "replacePreferredActivity expects filter to have no data authorities, " + 19310 "paths, or types; and at most one scheme."); 19311 } 19312 19313 final int callingUid = Binder.getCallingUid(); 19314 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19315 true /* requireFullPermission */, false /* checkShell */, 19316 "replace preferred activity"); 19317 synchronized (mPackages) { 19318 if (mContext.checkCallingOrSelfPermission( 19319 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19320 != PackageManager.PERMISSION_GRANTED) { 19321 if (getUidTargetSdkVersionLockedLPr(callingUid) 19322 < Build.VERSION_CODES.FROYO) { 19323 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19324 + Binder.getCallingUid()); 19325 return; 19326 } 19327 mContext.enforceCallingOrSelfPermission( 19328 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19329 } 19330 19331 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19332 if (pir != null) { 19333 // Get all of the existing entries that exactly match this filter. 19334 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19335 if (existing != null && existing.size() == 1) { 19336 PreferredActivity cur = existing.get(0); 19337 if (DEBUG_PREFERRED) { 19338 Slog.i(TAG, "Checking replace of preferred:"); 19339 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19340 if (!cur.mPref.mAlways) { 19341 Slog.i(TAG, " -- CUR; not mAlways!"); 19342 } else { 19343 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19344 Slog.i(TAG, " -- CUR: mSet=" 19345 + Arrays.toString(cur.mPref.mSetComponents)); 19346 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19347 Slog.i(TAG, " -- NEW: mMatch=" 19348 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19349 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19350 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19351 } 19352 } 19353 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19354 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19355 && cur.mPref.sameSet(set)) { 19356 // Setting the preferred activity to what it happens to be already 19357 if (DEBUG_PREFERRED) { 19358 Slog.i(TAG, "Replacing with same preferred activity " 19359 + cur.mPref.mShortComponent + " for user " 19360 + userId + ":"); 19361 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19362 } 19363 return; 19364 } 19365 } 19366 19367 if (existing != null) { 19368 if (DEBUG_PREFERRED) { 19369 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19370 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19371 } 19372 for (int i = 0; i < existing.size(); i++) { 19373 PreferredActivity pa = existing.get(i); 19374 if (DEBUG_PREFERRED) { 19375 Slog.i(TAG, "Removing existing preferred activity " 19376 + pa.mPref.mComponent + ":"); 19377 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19378 } 19379 pir.removeFilter(pa); 19380 } 19381 } 19382 } 19383 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19384 "Replacing preferred"); 19385 } 19386 } 19387 19388 @Override 19389 public void clearPackagePreferredActivities(String packageName) { 19390 final int callingUid = Binder.getCallingUid(); 19391 if (getInstantAppPackageName(callingUid) != null) { 19392 return; 19393 } 19394 // writer 19395 synchronized (mPackages) { 19396 PackageParser.Package pkg = mPackages.get(packageName); 19397 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19398 if (mContext.checkCallingOrSelfPermission( 19399 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19400 != PackageManager.PERMISSION_GRANTED) { 19401 if (getUidTargetSdkVersionLockedLPr(callingUid) 19402 < Build.VERSION_CODES.FROYO) { 19403 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19404 + callingUid); 19405 return; 19406 } 19407 mContext.enforceCallingOrSelfPermission( 19408 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19409 } 19410 } 19411 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19412 if (ps != null 19413 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19414 return; 19415 } 19416 int user = UserHandle.getCallingUserId(); 19417 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19418 scheduleWritePackageRestrictionsLocked(user); 19419 } 19420 } 19421 } 19422 19423 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19424 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19425 ArrayList<PreferredActivity> removed = null; 19426 boolean changed = false; 19427 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19428 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19429 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19430 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19431 continue; 19432 } 19433 Iterator<PreferredActivity> it = pir.filterIterator(); 19434 while (it.hasNext()) { 19435 PreferredActivity pa = it.next(); 19436 // Mark entry for removal only if it matches the package name 19437 // and the entry is of type "always". 19438 if (packageName == null || 19439 (pa.mPref.mComponent.getPackageName().equals(packageName) 19440 && pa.mPref.mAlways)) { 19441 if (removed == null) { 19442 removed = new ArrayList<PreferredActivity>(); 19443 } 19444 removed.add(pa); 19445 } 19446 } 19447 if (removed != null) { 19448 for (int j=0; j<removed.size(); j++) { 19449 PreferredActivity pa = removed.get(j); 19450 pir.removeFilter(pa); 19451 } 19452 changed = true; 19453 } 19454 } 19455 if (changed) { 19456 postPreferredActivityChangedBroadcast(userId); 19457 } 19458 return changed; 19459 } 19460 19461 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19462 private void clearIntentFilterVerificationsLPw(int userId) { 19463 final int packageCount = mPackages.size(); 19464 for (int i = 0; i < packageCount; i++) { 19465 PackageParser.Package pkg = mPackages.valueAt(i); 19466 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19467 } 19468 } 19469 19470 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19471 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19472 if (userId == UserHandle.USER_ALL) { 19473 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19474 sUserManager.getUserIds())) { 19475 for (int oneUserId : sUserManager.getUserIds()) { 19476 scheduleWritePackageRestrictionsLocked(oneUserId); 19477 } 19478 } 19479 } else { 19480 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19481 scheduleWritePackageRestrictionsLocked(userId); 19482 } 19483 } 19484 } 19485 19486 /** Clears state for all users, and touches intent filter verification policy */ 19487 void clearDefaultBrowserIfNeeded(String packageName) { 19488 for (int oneUserId : sUserManager.getUserIds()) { 19489 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19490 } 19491 } 19492 19493 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19494 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19495 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19496 if (packageName.equals(defaultBrowserPackageName)) { 19497 setDefaultBrowserPackageName(null, userId); 19498 } 19499 } 19500 } 19501 19502 @Override 19503 public void resetApplicationPreferences(int userId) { 19504 mContext.enforceCallingOrSelfPermission( 19505 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19506 final long identity = Binder.clearCallingIdentity(); 19507 // writer 19508 try { 19509 synchronized (mPackages) { 19510 clearPackagePreferredActivitiesLPw(null, userId); 19511 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19512 // TODO: We have to reset the default SMS and Phone. This requires 19513 // significant refactoring to keep all default apps in the package 19514 // manager (cleaner but more work) or have the services provide 19515 // callbacks to the package manager to request a default app reset. 19516 applyFactoryDefaultBrowserLPw(userId); 19517 clearIntentFilterVerificationsLPw(userId); 19518 primeDomainVerificationsLPw(userId); 19519 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19520 scheduleWritePackageRestrictionsLocked(userId); 19521 } 19522 resetNetworkPolicies(userId); 19523 } finally { 19524 Binder.restoreCallingIdentity(identity); 19525 } 19526 } 19527 19528 @Override 19529 public int getPreferredActivities(List<IntentFilter> outFilters, 19530 List<ComponentName> outActivities, String packageName) { 19531 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19532 return 0; 19533 } 19534 int num = 0; 19535 final int userId = UserHandle.getCallingUserId(); 19536 // reader 19537 synchronized (mPackages) { 19538 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19539 if (pir != null) { 19540 final Iterator<PreferredActivity> it = pir.filterIterator(); 19541 while (it.hasNext()) { 19542 final PreferredActivity pa = it.next(); 19543 if (packageName == null 19544 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19545 && pa.mPref.mAlways)) { 19546 if (outFilters != null) { 19547 outFilters.add(new IntentFilter(pa)); 19548 } 19549 if (outActivities != null) { 19550 outActivities.add(pa.mPref.mComponent); 19551 } 19552 } 19553 } 19554 } 19555 } 19556 19557 return num; 19558 } 19559 19560 @Override 19561 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19562 int userId) { 19563 int callingUid = Binder.getCallingUid(); 19564 if (callingUid != Process.SYSTEM_UID) { 19565 throw new SecurityException( 19566 "addPersistentPreferredActivity can only be run by the system"); 19567 } 19568 if (filter.countActions() == 0) { 19569 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19570 return; 19571 } 19572 synchronized (mPackages) { 19573 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19574 ":"); 19575 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19576 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19577 new PersistentPreferredActivity(filter, activity)); 19578 scheduleWritePackageRestrictionsLocked(userId); 19579 postPreferredActivityChangedBroadcast(userId); 19580 } 19581 } 19582 19583 @Override 19584 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19585 int callingUid = Binder.getCallingUid(); 19586 if (callingUid != Process.SYSTEM_UID) { 19587 throw new SecurityException( 19588 "clearPackagePersistentPreferredActivities can only be run by the system"); 19589 } 19590 ArrayList<PersistentPreferredActivity> removed = null; 19591 boolean changed = false; 19592 synchronized (mPackages) { 19593 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19594 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19595 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19596 .valueAt(i); 19597 if (userId != thisUserId) { 19598 continue; 19599 } 19600 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19601 while (it.hasNext()) { 19602 PersistentPreferredActivity ppa = it.next(); 19603 // Mark entry for removal only if it matches the package name. 19604 if (ppa.mComponent.getPackageName().equals(packageName)) { 19605 if (removed == null) { 19606 removed = new ArrayList<PersistentPreferredActivity>(); 19607 } 19608 removed.add(ppa); 19609 } 19610 } 19611 if (removed != null) { 19612 for (int j=0; j<removed.size(); j++) { 19613 PersistentPreferredActivity ppa = removed.get(j); 19614 ppir.removeFilter(ppa); 19615 } 19616 changed = true; 19617 } 19618 } 19619 19620 if (changed) { 19621 scheduleWritePackageRestrictionsLocked(userId); 19622 postPreferredActivityChangedBroadcast(userId); 19623 } 19624 } 19625 } 19626 19627 /** 19628 * Common machinery for picking apart a restored XML blob and passing 19629 * it to a caller-supplied functor to be applied to the running system. 19630 */ 19631 private void restoreFromXml(XmlPullParser parser, int userId, 19632 String expectedStartTag, BlobXmlRestorer functor) 19633 throws IOException, XmlPullParserException { 19634 int type; 19635 while ((type = parser.next()) != XmlPullParser.START_TAG 19636 && type != XmlPullParser.END_DOCUMENT) { 19637 } 19638 if (type != XmlPullParser.START_TAG) { 19639 // oops didn't find a start tag?! 19640 if (DEBUG_BACKUP) { 19641 Slog.e(TAG, "Didn't find start tag during restore"); 19642 } 19643 return; 19644 } 19645Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19646 // this is supposed to be TAG_PREFERRED_BACKUP 19647 if (!expectedStartTag.equals(parser.getName())) { 19648 if (DEBUG_BACKUP) { 19649 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19650 } 19651 return; 19652 } 19653 19654 // skip interfering stuff, then we're aligned with the backing implementation 19655 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19656Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19657 functor.apply(parser, userId); 19658 } 19659 19660 private interface BlobXmlRestorer { 19661 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19662 } 19663 19664 /** 19665 * Non-Binder method, support for the backup/restore mechanism: write the 19666 * full set of preferred activities in its canonical XML format. Returns the 19667 * XML output as a byte array, or null if there is none. 19668 */ 19669 @Override 19670 public byte[] getPreferredActivityBackup(int userId) { 19671 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19672 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19673 } 19674 19675 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19676 try { 19677 final XmlSerializer serializer = new FastXmlSerializer(); 19678 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19679 serializer.startDocument(null, true); 19680 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19681 19682 synchronized (mPackages) { 19683 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19684 } 19685 19686 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19687 serializer.endDocument(); 19688 serializer.flush(); 19689 } catch (Exception e) { 19690 if (DEBUG_BACKUP) { 19691 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19692 } 19693 return null; 19694 } 19695 19696 return dataStream.toByteArray(); 19697 } 19698 19699 @Override 19700 public void restorePreferredActivities(byte[] backup, int userId) { 19701 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19702 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19703 } 19704 19705 try { 19706 final XmlPullParser parser = Xml.newPullParser(); 19707 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19708 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19709 new BlobXmlRestorer() { 19710 @Override 19711 public void apply(XmlPullParser parser, int userId) 19712 throws XmlPullParserException, IOException { 19713 synchronized (mPackages) { 19714 mSettings.readPreferredActivitiesLPw(parser, userId); 19715 } 19716 } 19717 } ); 19718 } catch (Exception e) { 19719 if (DEBUG_BACKUP) { 19720 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19721 } 19722 } 19723 } 19724 19725 /** 19726 * Non-Binder method, support for the backup/restore mechanism: write the 19727 * default browser (etc) settings in its canonical XML format. Returns the default 19728 * browser XML representation as a byte array, or null if there is none. 19729 */ 19730 @Override 19731 public byte[] getDefaultAppsBackup(int userId) { 19732 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19733 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19734 } 19735 19736 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19737 try { 19738 final XmlSerializer serializer = new FastXmlSerializer(); 19739 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19740 serializer.startDocument(null, true); 19741 serializer.startTag(null, TAG_DEFAULT_APPS); 19742 19743 synchronized (mPackages) { 19744 mSettings.writeDefaultAppsLPr(serializer, userId); 19745 } 19746 19747 serializer.endTag(null, TAG_DEFAULT_APPS); 19748 serializer.endDocument(); 19749 serializer.flush(); 19750 } catch (Exception e) { 19751 if (DEBUG_BACKUP) { 19752 Slog.e(TAG, "Unable to write default apps for backup", e); 19753 } 19754 return null; 19755 } 19756 19757 return dataStream.toByteArray(); 19758 } 19759 19760 @Override 19761 public void restoreDefaultApps(byte[] backup, int userId) { 19762 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19763 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19764 } 19765 19766 try { 19767 final XmlPullParser parser = Xml.newPullParser(); 19768 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19769 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19770 new BlobXmlRestorer() { 19771 @Override 19772 public void apply(XmlPullParser parser, int userId) 19773 throws XmlPullParserException, IOException { 19774 synchronized (mPackages) { 19775 mSettings.readDefaultAppsLPw(parser, userId); 19776 } 19777 } 19778 } ); 19779 } catch (Exception e) { 19780 if (DEBUG_BACKUP) { 19781 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19782 } 19783 } 19784 } 19785 19786 @Override 19787 public byte[] getIntentFilterVerificationBackup(int userId) { 19788 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19789 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19790 } 19791 19792 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19793 try { 19794 final XmlSerializer serializer = new FastXmlSerializer(); 19795 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19796 serializer.startDocument(null, true); 19797 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19798 19799 synchronized (mPackages) { 19800 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19801 } 19802 19803 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19804 serializer.endDocument(); 19805 serializer.flush(); 19806 } catch (Exception e) { 19807 if (DEBUG_BACKUP) { 19808 Slog.e(TAG, "Unable to write default apps for backup", e); 19809 } 19810 return null; 19811 } 19812 19813 return dataStream.toByteArray(); 19814 } 19815 19816 @Override 19817 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19818 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19819 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19820 } 19821 19822 try { 19823 final XmlPullParser parser = Xml.newPullParser(); 19824 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19825 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19826 new BlobXmlRestorer() { 19827 @Override 19828 public void apply(XmlPullParser parser, int userId) 19829 throws XmlPullParserException, IOException { 19830 synchronized (mPackages) { 19831 mSettings.readAllDomainVerificationsLPr(parser, userId); 19832 mSettings.writeLPr(); 19833 } 19834 } 19835 } ); 19836 } catch (Exception e) { 19837 if (DEBUG_BACKUP) { 19838 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19839 } 19840 } 19841 } 19842 19843 @Override 19844 public byte[] getPermissionGrantBackup(int userId) { 19845 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19846 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19847 } 19848 19849 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19850 try { 19851 final XmlSerializer serializer = new FastXmlSerializer(); 19852 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19853 serializer.startDocument(null, true); 19854 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19855 19856 synchronized (mPackages) { 19857 serializeRuntimePermissionGrantsLPr(serializer, userId); 19858 } 19859 19860 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19861 serializer.endDocument(); 19862 serializer.flush(); 19863 } catch (Exception e) { 19864 if (DEBUG_BACKUP) { 19865 Slog.e(TAG, "Unable to write default apps for backup", e); 19866 } 19867 return null; 19868 } 19869 19870 return dataStream.toByteArray(); 19871 } 19872 19873 @Override 19874 public void restorePermissionGrants(byte[] backup, int userId) { 19875 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19876 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19877 } 19878 19879 try { 19880 final XmlPullParser parser = Xml.newPullParser(); 19881 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19882 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19883 new BlobXmlRestorer() { 19884 @Override 19885 public void apply(XmlPullParser parser, int userId) 19886 throws XmlPullParserException, IOException { 19887 synchronized (mPackages) { 19888 processRestoredPermissionGrantsLPr(parser, userId); 19889 } 19890 } 19891 } ); 19892 } catch (Exception e) { 19893 if (DEBUG_BACKUP) { 19894 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19895 } 19896 } 19897 } 19898 19899 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19900 throws IOException { 19901 serializer.startTag(null, TAG_ALL_GRANTS); 19902 19903 final int N = mSettings.mPackages.size(); 19904 for (int i = 0; i < N; i++) { 19905 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19906 boolean pkgGrantsKnown = false; 19907 19908 PermissionsState packagePerms = ps.getPermissionsState(); 19909 19910 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19911 final int grantFlags = state.getFlags(); 19912 // only look at grants that are not system/policy fixed 19913 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19914 final boolean isGranted = state.isGranted(); 19915 // And only back up the user-twiddled state bits 19916 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19917 final String packageName = mSettings.mPackages.keyAt(i); 19918 if (!pkgGrantsKnown) { 19919 serializer.startTag(null, TAG_GRANT); 19920 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19921 pkgGrantsKnown = true; 19922 } 19923 19924 final boolean userSet = 19925 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19926 final boolean userFixed = 19927 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19928 final boolean revoke = 19929 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19930 19931 serializer.startTag(null, TAG_PERMISSION); 19932 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19933 if (isGranted) { 19934 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19935 } 19936 if (userSet) { 19937 serializer.attribute(null, ATTR_USER_SET, "true"); 19938 } 19939 if (userFixed) { 19940 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19941 } 19942 if (revoke) { 19943 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19944 } 19945 serializer.endTag(null, TAG_PERMISSION); 19946 } 19947 } 19948 } 19949 19950 if (pkgGrantsKnown) { 19951 serializer.endTag(null, TAG_GRANT); 19952 } 19953 } 19954 19955 serializer.endTag(null, TAG_ALL_GRANTS); 19956 } 19957 19958 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19959 throws XmlPullParserException, IOException { 19960 String pkgName = null; 19961 int outerDepth = parser.getDepth(); 19962 int type; 19963 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19964 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19965 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19966 continue; 19967 } 19968 19969 final String tagName = parser.getName(); 19970 if (tagName.equals(TAG_GRANT)) { 19971 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19972 if (DEBUG_BACKUP) { 19973 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19974 } 19975 } else if (tagName.equals(TAG_PERMISSION)) { 19976 19977 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19978 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19979 19980 int newFlagSet = 0; 19981 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19982 newFlagSet |= FLAG_PERMISSION_USER_SET; 19983 } 19984 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19985 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19986 } 19987 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19988 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19989 } 19990 if (DEBUG_BACKUP) { 19991 Slog.v(TAG, " + Restoring grant:" 19992 + " pkg=" + pkgName 19993 + " perm=" + permName 19994 + " granted=" + isGranted 19995 + " bits=0x" + Integer.toHexString(newFlagSet)); 19996 } 19997 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19998 if (ps != null) { 19999 // Already installed so we apply the grant immediately 20000 if (DEBUG_BACKUP) { 20001 Slog.v(TAG, " + already installed; applying"); 20002 } 20003 PermissionsState perms = ps.getPermissionsState(); 20004 BasePermission bp = 20005 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20006 if (bp != null) { 20007 if (isGranted) { 20008 perms.grantRuntimePermission(bp, userId); 20009 } 20010 if (newFlagSet != 0) { 20011 perms.updatePermissionFlags( 20012 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20013 } 20014 } 20015 } else { 20016 // Need to wait for post-restore install to apply the grant 20017 if (DEBUG_BACKUP) { 20018 Slog.v(TAG, " - not yet installed; saving for later"); 20019 } 20020 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20021 isGranted, newFlagSet, userId); 20022 } 20023 } else { 20024 PackageManagerService.reportSettingsProblem(Log.WARN, 20025 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20026 XmlUtils.skipCurrentTag(parser); 20027 } 20028 } 20029 20030 scheduleWriteSettingsLocked(); 20031 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20032 } 20033 20034 @Override 20035 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20036 int sourceUserId, int targetUserId, int flags) { 20037 mContext.enforceCallingOrSelfPermission( 20038 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20039 int callingUid = Binder.getCallingUid(); 20040 enforceOwnerRights(ownerPackage, callingUid); 20041 PackageManagerServiceUtils.enforceShellRestriction( 20042 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20043 if (intentFilter.countActions() == 0) { 20044 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20045 return; 20046 } 20047 synchronized (mPackages) { 20048 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20049 ownerPackage, targetUserId, flags); 20050 CrossProfileIntentResolver resolver = 20051 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20052 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20053 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20054 if (existing != null) { 20055 int size = existing.size(); 20056 for (int i = 0; i < size; i++) { 20057 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20058 return; 20059 } 20060 } 20061 } 20062 resolver.addFilter(newFilter); 20063 scheduleWritePackageRestrictionsLocked(sourceUserId); 20064 } 20065 } 20066 20067 @Override 20068 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20069 mContext.enforceCallingOrSelfPermission( 20070 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20071 final int callingUid = Binder.getCallingUid(); 20072 enforceOwnerRights(ownerPackage, callingUid); 20073 PackageManagerServiceUtils.enforceShellRestriction( 20074 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20075 synchronized (mPackages) { 20076 CrossProfileIntentResolver resolver = 20077 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20078 ArraySet<CrossProfileIntentFilter> set = 20079 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20080 for (CrossProfileIntentFilter filter : set) { 20081 if (filter.getOwnerPackage().equals(ownerPackage)) { 20082 resolver.removeFilter(filter); 20083 } 20084 } 20085 scheduleWritePackageRestrictionsLocked(sourceUserId); 20086 } 20087 } 20088 20089 // Enforcing that callingUid is owning pkg on userId 20090 private void enforceOwnerRights(String pkg, int callingUid) { 20091 // The system owns everything. 20092 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20093 return; 20094 } 20095 final int callingUserId = UserHandle.getUserId(callingUid); 20096 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20097 if (pi == null) { 20098 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20099 + callingUserId); 20100 } 20101 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20102 throw new SecurityException("Calling uid " + callingUid 20103 + " does not own package " + pkg); 20104 } 20105 } 20106 20107 @Override 20108 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20109 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20110 return null; 20111 } 20112 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20113 } 20114 20115 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20116 UserManagerService ums = UserManagerService.getInstance(); 20117 if (ums != null) { 20118 final UserInfo parent = ums.getProfileParent(userId); 20119 final int launcherUid = (parent != null) ? parent.id : userId; 20120 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20121 if (launcherComponent != null) { 20122 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20123 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20124 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20125 .setPackage(launcherComponent.getPackageName()); 20126 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20127 } 20128 } 20129 } 20130 20131 /** 20132 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20133 * then reports the most likely home activity or null if there are more than one. 20134 */ 20135 private ComponentName getDefaultHomeActivity(int userId) { 20136 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20137 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20138 if (cn != null) { 20139 return cn; 20140 } 20141 20142 // Find the launcher with the highest priority and return that component if there are no 20143 // other home activity with the same priority. 20144 int lastPriority = Integer.MIN_VALUE; 20145 ComponentName lastComponent = null; 20146 final int size = allHomeCandidates.size(); 20147 for (int i = 0; i < size; i++) { 20148 final ResolveInfo ri = allHomeCandidates.get(i); 20149 if (ri.priority > lastPriority) { 20150 lastComponent = ri.activityInfo.getComponentName(); 20151 lastPriority = ri.priority; 20152 } else if (ri.priority == lastPriority) { 20153 // Two components found with same priority. 20154 lastComponent = null; 20155 } 20156 } 20157 return lastComponent; 20158 } 20159 20160 private Intent getHomeIntent() { 20161 Intent intent = new Intent(Intent.ACTION_MAIN); 20162 intent.addCategory(Intent.CATEGORY_HOME); 20163 intent.addCategory(Intent.CATEGORY_DEFAULT); 20164 return intent; 20165 } 20166 20167 private IntentFilter getHomeFilter() { 20168 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20169 filter.addCategory(Intent.CATEGORY_HOME); 20170 filter.addCategory(Intent.CATEGORY_DEFAULT); 20171 return filter; 20172 } 20173 20174 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20175 int userId) { 20176 Intent intent = getHomeIntent(); 20177 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20178 PackageManager.GET_META_DATA, userId); 20179 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20180 true, false, false, userId); 20181 20182 allHomeCandidates.clear(); 20183 if (list != null) { 20184 for (ResolveInfo ri : list) { 20185 allHomeCandidates.add(ri); 20186 } 20187 } 20188 return (preferred == null || preferred.activityInfo == null) 20189 ? null 20190 : new ComponentName(preferred.activityInfo.packageName, 20191 preferred.activityInfo.name); 20192 } 20193 20194 @Override 20195 public void setHomeActivity(ComponentName comp, int userId) { 20196 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20197 return; 20198 } 20199 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20200 getHomeActivitiesAsUser(homeActivities, userId); 20201 20202 boolean found = false; 20203 20204 final int size = homeActivities.size(); 20205 final ComponentName[] set = new ComponentName[size]; 20206 for (int i = 0; i < size; i++) { 20207 final ResolveInfo candidate = homeActivities.get(i); 20208 final ActivityInfo info = candidate.activityInfo; 20209 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20210 set[i] = activityName; 20211 if (!found && activityName.equals(comp)) { 20212 found = true; 20213 } 20214 } 20215 if (!found) { 20216 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20217 + userId); 20218 } 20219 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20220 set, comp, userId); 20221 } 20222 20223 private @Nullable String getSetupWizardPackageName() { 20224 final Intent intent = new Intent(Intent.ACTION_MAIN); 20225 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20226 20227 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20228 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20229 | MATCH_DISABLED_COMPONENTS, 20230 UserHandle.myUserId()); 20231 if (matches.size() == 1) { 20232 return matches.get(0).getComponentInfo().packageName; 20233 } else { 20234 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20235 + ": matches=" + matches); 20236 return null; 20237 } 20238 } 20239 20240 private @Nullable String getStorageManagerPackageName() { 20241 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20242 20243 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20244 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20245 | MATCH_DISABLED_COMPONENTS, 20246 UserHandle.myUserId()); 20247 if (matches.size() == 1) { 20248 return matches.get(0).getComponentInfo().packageName; 20249 } else { 20250 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20251 + matches.size() + ": matches=" + matches); 20252 return null; 20253 } 20254 } 20255 20256 @Override 20257 public String getSystemTextClassifierPackageName() { 20258 return mContext.getString(R.string.config_defaultTextClassifierPackage); 20259 } 20260 20261 @Override 20262 public void setApplicationEnabledSetting(String appPackageName, 20263 int newState, int flags, int userId, String callingPackage) { 20264 if (!sUserManager.exists(userId)) return; 20265 if (callingPackage == null) { 20266 callingPackage = Integer.toString(Binder.getCallingUid()); 20267 } 20268 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20269 } 20270 20271 @Override 20272 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20274 synchronized (mPackages) { 20275 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20276 if (pkgSetting != null) { 20277 pkgSetting.setUpdateAvailable(updateAvailable); 20278 } 20279 } 20280 } 20281 20282 @Override 20283 public void setComponentEnabledSetting(ComponentName componentName, 20284 int newState, int flags, int userId) { 20285 if (!sUserManager.exists(userId)) return; 20286 setEnabledSetting(componentName.getPackageName(), 20287 componentName.getClassName(), newState, flags, userId, null); 20288 } 20289 20290 private void setEnabledSetting(final String packageName, String className, int newState, 20291 final int flags, int userId, String callingPackage) { 20292 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20293 || newState == COMPONENT_ENABLED_STATE_ENABLED 20294 || newState == COMPONENT_ENABLED_STATE_DISABLED 20295 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20296 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20297 throw new IllegalArgumentException("Invalid new component state: " 20298 + newState); 20299 } 20300 PackageSetting pkgSetting; 20301 final int callingUid = Binder.getCallingUid(); 20302 final int permission; 20303 if (callingUid == Process.SYSTEM_UID) { 20304 permission = PackageManager.PERMISSION_GRANTED; 20305 } else { 20306 permission = mContext.checkCallingOrSelfPermission( 20307 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20308 } 20309 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20310 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20311 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20312 boolean sendNow = false; 20313 boolean isApp = (className == null); 20314 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20315 String componentName = isApp ? packageName : className; 20316 int packageUid = -1; 20317 ArrayList<String> components; 20318 20319 // reader 20320 synchronized (mPackages) { 20321 pkgSetting = mSettings.mPackages.get(packageName); 20322 if (pkgSetting == null) { 20323 if (!isCallerInstantApp) { 20324 if (className == null) { 20325 throw new IllegalArgumentException("Unknown package: " + packageName); 20326 } 20327 throw new IllegalArgumentException( 20328 "Unknown component: " + packageName + "/" + className); 20329 } else { 20330 // throw SecurityException to prevent leaking package information 20331 throw new SecurityException( 20332 "Attempt to change component state; " 20333 + "pid=" + Binder.getCallingPid() 20334 + ", uid=" + callingUid 20335 + (className == null 20336 ? ", package=" + packageName 20337 : ", component=" + packageName + "/" + className)); 20338 } 20339 } 20340 } 20341 20342 // Limit who can change which apps 20343 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20344 // Don't allow apps that don't have permission to modify other apps 20345 if (!allowedByPermission 20346 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20347 throw new SecurityException( 20348 "Attempt to change component state; " 20349 + "pid=" + Binder.getCallingPid() 20350 + ", uid=" + callingUid 20351 + (className == null 20352 ? ", package=" + packageName 20353 : ", component=" + packageName + "/" + className)); 20354 } 20355 // Don't allow changing protected packages. 20356 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20357 throw new SecurityException("Cannot disable a protected package: " + packageName); 20358 } 20359 } 20360 20361 synchronized (mPackages) { 20362 if (callingUid == Process.SHELL_UID 20363 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20364 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20365 // unless it is a test package. 20366 int oldState = pkgSetting.getEnabled(userId); 20367 if (className == null 20368 && 20369 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20370 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20371 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20372 && 20373 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20374 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20375 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20376 // ok 20377 } else { 20378 throw new SecurityException( 20379 "Shell cannot change component state for " + packageName + "/" 20380 + className + " to " + newState); 20381 } 20382 } 20383 } 20384 if (className == null) { 20385 // We're dealing with an application/package level state change 20386 synchronized (mPackages) { 20387 if (pkgSetting.getEnabled(userId) == newState) { 20388 // Nothing to do 20389 return; 20390 } 20391 } 20392 // If we're enabling a system stub, there's a little more work to do. 20393 // Prior to enabling the package, we need to decompress the APK(s) to the 20394 // data partition and then replace the version on the system partition. 20395 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20396 final boolean isSystemStub = deletedPkg.isStub 20397 && deletedPkg.isSystem(); 20398 if (isSystemStub 20399 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20400 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20401 final File codePath = decompressPackage(deletedPkg); 20402 if (codePath == null) { 20403 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20404 return; 20405 } 20406 // TODO remove direct parsing of the package object during internal cleanup 20407 // of scan package 20408 // We need to call parse directly here for no other reason than we need 20409 // the new package in order to disable the old one [we use the information 20410 // for some internal optimization to optionally create a new package setting 20411 // object on replace]. However, we can't get the package from the scan 20412 // because the scan modifies live structures and we need to remove the 20413 // old [system] package from the system before a scan can be attempted. 20414 // Once scan is indempotent we can remove this parse and use the package 20415 // object we scanned, prior to adding it to package settings. 20416 final PackageParser pp = new PackageParser(); 20417 pp.setSeparateProcesses(mSeparateProcesses); 20418 pp.setDisplayMetrics(mMetrics); 20419 pp.setCallback(mPackageParserCallback); 20420 final PackageParser.Package tmpPkg; 20421 try { 20422 final @ParseFlags int parseFlags = mDefParseFlags 20423 | PackageParser.PARSE_MUST_BE_APK 20424 | PackageParser.PARSE_IS_SYSTEM_DIR; 20425 tmpPkg = pp.parsePackage(codePath, parseFlags); 20426 } catch (PackageParserException e) { 20427 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20428 return; 20429 } 20430 synchronized (mInstallLock) { 20431 // Disable the stub and remove any package entries 20432 removePackageLI(deletedPkg, true); 20433 synchronized (mPackages) { 20434 disableSystemPackageLPw(deletedPkg, tmpPkg); 20435 } 20436 final PackageParser.Package pkg; 20437 try (PackageFreezer freezer = 20438 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20439 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20440 | PackageParser.PARSE_ENFORCE_CODE; 20441 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20442 0 /*currentTime*/, null /*user*/); 20443 prepareAppDataAfterInstallLIF(pkg); 20444 synchronized (mPackages) { 20445 try { 20446 updateSharedLibrariesLPr(pkg, null); 20447 } catch (PackageManagerException e) { 20448 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20449 } 20450 mPermissionManager.updatePermissions( 20451 pkg.packageName, pkg, true, mPackages.values(), 20452 mPermissionCallback); 20453 mSettings.writeLPr(); 20454 } 20455 } catch (PackageManagerException e) { 20456 // Whoops! Something went wrong; try to roll back to the stub 20457 Slog.w(TAG, "Failed to install compressed system package:" 20458 + pkgSetting.name, e); 20459 // Remove the failed install 20460 removeCodePathLI(codePath); 20461 20462 // Install the system package 20463 try (PackageFreezer freezer = 20464 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20465 synchronized (mPackages) { 20466 // NOTE: The system package always needs to be enabled; even 20467 // if it's for a compressed stub. If we don't, installing the 20468 // system package fails during scan [scanning checks the disabled 20469 // packages]. We will reverse this later, after we've "installed" 20470 // the stub. 20471 // This leaves us in a fragile state; the stub should never be 20472 // enabled, so, cross your fingers and hope nothing goes wrong 20473 // until we can disable the package later. 20474 enableSystemPackageLPw(deletedPkg); 20475 } 20476 installPackageFromSystemLIF(deletedPkg.codePath, 20477 false /*isPrivileged*/, null /*allUserHandles*/, 20478 null /*origUserHandles*/, null /*origPermissionsState*/, 20479 true /*writeSettings*/); 20480 } catch (PackageManagerException pme) { 20481 Slog.w(TAG, "Failed to restore system package:" 20482 + deletedPkg.packageName, pme); 20483 } finally { 20484 synchronized (mPackages) { 20485 mSettings.disableSystemPackageLPw( 20486 deletedPkg.packageName, true /*replaced*/); 20487 mSettings.writeLPr(); 20488 } 20489 } 20490 return; 20491 } 20492 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20493 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20494 mDexManager.notifyPackageUpdated(pkg.packageName, 20495 pkg.baseCodePath, pkg.splitCodePaths); 20496 } 20497 } 20498 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20499 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20500 // Don't care about who enables an app. 20501 callingPackage = null; 20502 } 20503 synchronized (mPackages) { 20504 pkgSetting.setEnabled(newState, userId, callingPackage); 20505 } 20506 } else { 20507 synchronized (mPackages) { 20508 // We're dealing with a component level state change 20509 // First, verify that this is a valid class name. 20510 PackageParser.Package pkg = pkgSetting.pkg; 20511 if (pkg == null || !pkg.hasComponentClassName(className)) { 20512 if (pkg != null && 20513 pkg.applicationInfo.targetSdkVersion >= 20514 Build.VERSION_CODES.JELLY_BEAN) { 20515 throw new IllegalArgumentException("Component class " + className 20516 + " does not exist in " + packageName); 20517 } else { 20518 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20519 + className + " does not exist in " + packageName); 20520 } 20521 } 20522 switch (newState) { 20523 case COMPONENT_ENABLED_STATE_ENABLED: 20524 if (!pkgSetting.enableComponentLPw(className, userId)) { 20525 return; 20526 } 20527 break; 20528 case COMPONENT_ENABLED_STATE_DISABLED: 20529 if (!pkgSetting.disableComponentLPw(className, userId)) { 20530 return; 20531 } 20532 break; 20533 case COMPONENT_ENABLED_STATE_DEFAULT: 20534 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20535 return; 20536 } 20537 break; 20538 default: 20539 Slog.e(TAG, "Invalid new component state: " + newState); 20540 return; 20541 } 20542 } 20543 } 20544 synchronized (mPackages) { 20545 scheduleWritePackageRestrictionsLocked(userId); 20546 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20547 final long callingId = Binder.clearCallingIdentity(); 20548 try { 20549 updateInstantAppInstallerLocked(packageName); 20550 } finally { 20551 Binder.restoreCallingIdentity(callingId); 20552 } 20553 components = mPendingBroadcasts.get(userId, packageName); 20554 final boolean newPackage = components == null; 20555 if (newPackage) { 20556 components = new ArrayList<String>(); 20557 } 20558 if (!components.contains(componentName)) { 20559 components.add(componentName); 20560 } 20561 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20562 sendNow = true; 20563 // Purge entry from pending broadcast list if another one exists already 20564 // since we are sending one right away. 20565 mPendingBroadcasts.remove(userId, packageName); 20566 } else { 20567 if (newPackage) { 20568 mPendingBroadcasts.put(userId, packageName, components); 20569 } 20570 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20571 // Schedule a message 20572 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20573 } 20574 } 20575 } 20576 20577 long callingId = Binder.clearCallingIdentity(); 20578 try { 20579 if (sendNow) { 20580 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20581 sendPackageChangedBroadcast(packageName, 20582 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20583 } 20584 } finally { 20585 Binder.restoreCallingIdentity(callingId); 20586 } 20587 } 20588 20589 @Override 20590 public void flushPackageRestrictionsAsUser(int userId) { 20591 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20592 return; 20593 } 20594 if (!sUserManager.exists(userId)) { 20595 return; 20596 } 20597 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20598 false /* checkShell */, "flushPackageRestrictions"); 20599 synchronized (mPackages) { 20600 mSettings.writePackageRestrictionsLPr(userId); 20601 mDirtyUsers.remove(userId); 20602 if (mDirtyUsers.isEmpty()) { 20603 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20604 } 20605 } 20606 } 20607 20608 private void sendPackageChangedBroadcast(String packageName, 20609 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20610 if (DEBUG_INSTALL) 20611 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20612 + componentNames); 20613 Bundle extras = new Bundle(4); 20614 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20615 String nameList[] = new String[componentNames.size()]; 20616 componentNames.toArray(nameList); 20617 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20618 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20619 extras.putInt(Intent.EXTRA_UID, packageUid); 20620 // If this is not reporting a change of the overall package, then only send it 20621 // to registered receivers. We don't want to launch a swath of apps for every 20622 // little component state change. 20623 final int flags = !componentNames.contains(packageName) 20624 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20625 final int userId = UserHandle.getUserId(packageUid); 20626 final boolean isInstantApp = isInstantApp(packageName, userId); 20627 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20628 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20629 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20630 userIds, instantUserIds); 20631 } 20632 20633 @Override 20634 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20635 if (!sUserManager.exists(userId)) return; 20636 final int callingUid = Binder.getCallingUid(); 20637 if (getInstantAppPackageName(callingUid) != null) { 20638 return; 20639 } 20640 final int permission = mContext.checkCallingOrSelfPermission( 20641 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20642 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20643 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20644 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20645 // writer 20646 synchronized (mPackages) { 20647 final PackageSetting ps = mSettings.mPackages.get(packageName); 20648 if (!filterAppAccessLPr(ps, callingUid, userId) 20649 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20650 allowedByPermission, callingUid, userId)) { 20651 scheduleWritePackageRestrictionsLocked(userId); 20652 } 20653 } 20654 } 20655 20656 @Override 20657 public String getInstallerPackageName(String packageName) { 20658 final int callingUid = Binder.getCallingUid(); 20659 synchronized (mPackages) { 20660 final PackageSetting ps = mSettings.mPackages.get(packageName); 20661 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20662 return null; 20663 } 20664 return mSettings.getInstallerPackageNameLPr(packageName); 20665 } 20666 } 20667 20668 public boolean isOrphaned(String packageName) { 20669 // reader 20670 synchronized (mPackages) { 20671 return mSettings.isOrphaned(packageName); 20672 } 20673 } 20674 20675 @Override 20676 public int getApplicationEnabledSetting(String packageName, int userId) { 20677 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20678 int callingUid = Binder.getCallingUid(); 20679 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20680 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20681 // reader 20682 synchronized (mPackages) { 20683 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20684 return COMPONENT_ENABLED_STATE_DISABLED; 20685 } 20686 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20687 } 20688 } 20689 20690 @Override 20691 public int getComponentEnabledSetting(ComponentName component, int userId) { 20692 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20693 int callingUid = Binder.getCallingUid(); 20694 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20695 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20696 synchronized (mPackages) { 20697 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20698 component, TYPE_UNKNOWN, userId)) { 20699 return COMPONENT_ENABLED_STATE_DISABLED; 20700 } 20701 return mSettings.getComponentEnabledSettingLPr(component, userId); 20702 } 20703 } 20704 20705 @Override 20706 public void enterSafeMode() { 20707 enforceSystemOrRoot("Only the system can request entering safe mode"); 20708 20709 if (!mSystemReady) { 20710 mSafeMode = true; 20711 } 20712 } 20713 20714 @Override 20715 public void systemReady() { 20716 enforceSystemOrRoot("Only the system can claim the system is ready"); 20717 20718 mSystemReady = true; 20719 final ContentResolver resolver = mContext.getContentResolver(); 20720 ContentObserver co = new ContentObserver(mHandler) { 20721 @Override 20722 public void onChange(boolean selfChange) { 20723 mWebInstantAppsDisabled = 20724 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20725 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20726 } 20727 }; 20728 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20729 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20730 false, co, UserHandle.USER_SYSTEM); 20731 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 20732 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20733 co.onChange(true); 20734 20735 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20736 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20737 // it is done. 20738 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20739 @Override 20740 public void onChange(boolean selfChange) { 20741 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20742 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20743 oobEnabled == 1 ? "true" : "false"); 20744 } 20745 }; 20746 mContext.getContentResolver().registerContentObserver( 20747 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20748 UserHandle.USER_SYSTEM); 20749 // At boot, restore the value from the setting, which persists across reboot. 20750 privAppOobObserver.onChange(true); 20751 20752 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20753 // disabled after already being started. 20754 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20755 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20756 20757 // Read the compatibilty setting when the system is ready. 20758 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20759 mContext.getContentResolver(), 20760 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20761 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20762 if (DEBUG_SETTINGS) { 20763 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20764 } 20765 20766 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20767 20768 synchronized (mPackages) { 20769 // Verify that all of the preferred activity components actually 20770 // exist. It is possible for applications to be updated and at 20771 // that point remove a previously declared activity component that 20772 // had been set as a preferred activity. We try to clean this up 20773 // the next time we encounter that preferred activity, but it is 20774 // possible for the user flow to never be able to return to that 20775 // situation so here we do a sanity check to make sure we haven't 20776 // left any junk around. 20777 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20778 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20779 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20780 removed.clear(); 20781 for (PreferredActivity pa : pir.filterSet()) { 20782 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20783 removed.add(pa); 20784 } 20785 } 20786 if (removed.size() > 0) { 20787 for (int r=0; r<removed.size(); r++) { 20788 PreferredActivity pa = removed.get(r); 20789 Slog.w(TAG, "Removing dangling preferred activity: " 20790 + pa.mPref.mComponent); 20791 pir.removeFilter(pa); 20792 } 20793 mSettings.writePackageRestrictionsLPr( 20794 mSettings.mPreferredActivities.keyAt(i)); 20795 } 20796 } 20797 20798 for (int userId : UserManagerService.getInstance().getUserIds()) { 20799 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20800 grantPermissionsUserIds = ArrayUtils.appendInt( 20801 grantPermissionsUserIds, userId); 20802 } 20803 } 20804 } 20805 sUserManager.systemReady(); 20806 // If we upgraded grant all default permissions before kicking off. 20807 for (int userId : grantPermissionsUserIds) { 20808 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20809 } 20810 20811 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20812 // If we did not grant default permissions, we preload from this the 20813 // default permission exceptions lazily to ensure we don't hit the 20814 // disk on a new user creation. 20815 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20816 } 20817 20818 // Now that we've scanned all packages, and granted any default 20819 // permissions, ensure permissions are updated. Beware of dragons if you 20820 // try optimizing this. 20821 synchronized (mPackages) { 20822 mPermissionManager.updateAllPermissions( 20823 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20824 mPermissionCallback); 20825 } 20826 20827 // Kick off any messages waiting for system ready 20828 if (mPostSystemReadyMessages != null) { 20829 for (Message msg : mPostSystemReadyMessages) { 20830 msg.sendToTarget(); 20831 } 20832 mPostSystemReadyMessages = null; 20833 } 20834 20835 // Watch for external volumes that come and go over time 20836 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20837 storage.registerListener(mStorageListener); 20838 20839 mInstallerService.systemReady(); 20840 mPackageDexOptimizer.systemReady(); 20841 20842 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20843 StorageManagerInternal.class); 20844 StorageManagerInternal.addExternalStoragePolicy( 20845 new StorageManagerInternal.ExternalStorageMountPolicy() { 20846 @Override 20847 public int getMountMode(int uid, String packageName) { 20848 if (Process.isIsolated(uid)) { 20849 return Zygote.MOUNT_EXTERNAL_NONE; 20850 } 20851 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20852 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20853 } 20854 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20855 return Zygote.MOUNT_EXTERNAL_READ; 20856 } 20857 return Zygote.MOUNT_EXTERNAL_WRITE; 20858 } 20859 20860 @Override 20861 public boolean hasExternalStorage(int uid, String packageName) { 20862 return true; 20863 } 20864 }); 20865 20866 // Now that we're mostly running, clean up stale users and apps 20867 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20868 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20869 20870 mPermissionManager.systemReady(); 20871 20872 if (mInstantAppResolverConnection != null) { 20873 mContext.registerReceiver(new BroadcastReceiver() { 20874 @Override 20875 public void onReceive(Context context, Intent intent) { 20876 mInstantAppResolverConnection.optimisticBind(); 20877 mContext.unregisterReceiver(this); 20878 } 20879 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 20880 } 20881 } 20882 20883 public void waitForAppDataPrepared() { 20884 if (mPrepareAppDataFuture == null) { 20885 return; 20886 } 20887 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20888 mPrepareAppDataFuture = null; 20889 } 20890 20891 @Override 20892 public boolean isSafeMode() { 20893 // allow instant applications 20894 return mSafeMode; 20895 } 20896 20897 @Override 20898 public boolean hasSystemUidErrors() { 20899 // allow instant applications 20900 return mHasSystemUidErrors; 20901 } 20902 20903 static String arrayToString(int[] array) { 20904 StringBuffer buf = new StringBuffer(128); 20905 buf.append('['); 20906 if (array != null) { 20907 for (int i=0; i<array.length; i++) { 20908 if (i > 0) buf.append(", "); 20909 buf.append(array[i]); 20910 } 20911 } 20912 buf.append(']'); 20913 return buf.toString(); 20914 } 20915 20916 @Override 20917 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20918 FileDescriptor err, String[] args, ShellCallback callback, 20919 ResultReceiver resultReceiver) { 20920 (new PackageManagerShellCommand(this)).exec( 20921 this, in, out, err, args, callback, resultReceiver); 20922 } 20923 20924 @Override 20925 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20926 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20927 20928 DumpState dumpState = new DumpState(); 20929 boolean fullPreferred = false; 20930 boolean checkin = false; 20931 20932 String packageName = null; 20933 ArraySet<String> permissionNames = null; 20934 20935 int opti = 0; 20936 while (opti < args.length) { 20937 String opt = args[opti]; 20938 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20939 break; 20940 } 20941 opti++; 20942 20943 if ("-a".equals(opt)) { 20944 // Right now we only know how to print all. 20945 } else if ("-h".equals(opt)) { 20946 pw.println("Package manager dump options:"); 20947 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20948 pw.println(" --checkin: dump for a checkin"); 20949 pw.println(" -f: print details of intent filters"); 20950 pw.println(" -h: print this help"); 20951 pw.println(" cmd may be one of:"); 20952 pw.println(" l[ibraries]: list known shared libraries"); 20953 pw.println(" f[eatures]: list device features"); 20954 pw.println(" k[eysets]: print known keysets"); 20955 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20956 pw.println(" perm[issions]: dump permissions"); 20957 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20958 pw.println(" pref[erred]: print preferred package settings"); 20959 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20960 pw.println(" prov[iders]: dump content providers"); 20961 pw.println(" p[ackages]: dump installed packages"); 20962 pw.println(" s[hared-users]: dump shared user IDs"); 20963 pw.println(" m[essages]: print collected runtime messages"); 20964 pw.println(" v[erifiers]: print package verifier info"); 20965 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20966 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20967 pw.println(" version: print database version info"); 20968 pw.println(" write: write current settings now"); 20969 pw.println(" installs: details about install sessions"); 20970 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20971 pw.println(" dexopt: dump dexopt state"); 20972 pw.println(" compiler-stats: dump compiler statistics"); 20973 pw.println(" service-permissions: dump permissions required by services"); 20974 pw.println(" <package.name>: info about given package"); 20975 return; 20976 } else if ("--checkin".equals(opt)) { 20977 checkin = true; 20978 } else if ("-f".equals(opt)) { 20979 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20980 } else if ("--proto".equals(opt)) { 20981 dumpProto(fd); 20982 return; 20983 } else { 20984 pw.println("Unknown argument: " + opt + "; use -h for help"); 20985 } 20986 } 20987 20988 // Is the caller requesting to dump a particular piece of data? 20989 if (opti < args.length) { 20990 String cmd = args[opti]; 20991 opti++; 20992 // Is this a package name? 20993 if ("android".equals(cmd) || cmd.contains(".")) { 20994 packageName = cmd; 20995 // When dumping a single package, we always dump all of its 20996 // filter information since the amount of data will be reasonable. 20997 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20998 } else if ("check-permission".equals(cmd)) { 20999 if (opti >= args.length) { 21000 pw.println("Error: check-permission missing permission argument"); 21001 return; 21002 } 21003 String perm = args[opti]; 21004 opti++; 21005 if (opti >= args.length) { 21006 pw.println("Error: check-permission missing package argument"); 21007 return; 21008 } 21009 21010 String pkg = args[opti]; 21011 opti++; 21012 int user = UserHandle.getUserId(Binder.getCallingUid()); 21013 if (opti < args.length) { 21014 try { 21015 user = Integer.parseInt(args[opti]); 21016 } catch (NumberFormatException e) { 21017 pw.println("Error: check-permission user argument is not a number: " 21018 + args[opti]); 21019 return; 21020 } 21021 } 21022 21023 // Normalize package name to handle renamed packages and static libs 21024 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21025 21026 pw.println(checkPermission(perm, pkg, user)); 21027 return; 21028 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21029 dumpState.setDump(DumpState.DUMP_LIBS); 21030 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21031 dumpState.setDump(DumpState.DUMP_FEATURES); 21032 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21033 if (opti >= args.length) { 21034 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21035 | DumpState.DUMP_SERVICE_RESOLVERS 21036 | DumpState.DUMP_RECEIVER_RESOLVERS 21037 | DumpState.DUMP_CONTENT_RESOLVERS); 21038 } else { 21039 while (opti < args.length) { 21040 String name = args[opti]; 21041 if ("a".equals(name) || "activity".equals(name)) { 21042 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21043 } else if ("s".equals(name) || "service".equals(name)) { 21044 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21045 } else if ("r".equals(name) || "receiver".equals(name)) { 21046 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21047 } else if ("c".equals(name) || "content".equals(name)) { 21048 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21049 } else { 21050 pw.println("Error: unknown resolver table type: " + name); 21051 return; 21052 } 21053 opti++; 21054 } 21055 } 21056 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21057 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21058 } else if ("permission".equals(cmd)) { 21059 if (opti >= args.length) { 21060 pw.println("Error: permission requires permission name"); 21061 return; 21062 } 21063 permissionNames = new ArraySet<>(); 21064 while (opti < args.length) { 21065 permissionNames.add(args[opti]); 21066 opti++; 21067 } 21068 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21069 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21070 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21071 dumpState.setDump(DumpState.DUMP_PREFERRED); 21072 } else if ("preferred-xml".equals(cmd)) { 21073 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21074 if (opti < args.length && "--full".equals(args[opti])) { 21075 fullPreferred = true; 21076 opti++; 21077 } 21078 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21079 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21080 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21081 dumpState.setDump(DumpState.DUMP_PACKAGES); 21082 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21083 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21084 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21085 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21086 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21087 dumpState.setDump(DumpState.DUMP_MESSAGES); 21088 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21089 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21090 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21091 || "intent-filter-verifiers".equals(cmd)) { 21092 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21093 } else if ("version".equals(cmd)) { 21094 dumpState.setDump(DumpState.DUMP_VERSION); 21095 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21096 dumpState.setDump(DumpState.DUMP_KEYSETS); 21097 } else if ("installs".equals(cmd)) { 21098 dumpState.setDump(DumpState.DUMP_INSTALLS); 21099 } else if ("frozen".equals(cmd)) { 21100 dumpState.setDump(DumpState.DUMP_FROZEN); 21101 } else if ("volumes".equals(cmd)) { 21102 dumpState.setDump(DumpState.DUMP_VOLUMES); 21103 } else if ("dexopt".equals(cmd)) { 21104 dumpState.setDump(DumpState.DUMP_DEXOPT); 21105 } else if ("compiler-stats".equals(cmd)) { 21106 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21107 } else if ("changes".equals(cmd)) { 21108 dumpState.setDump(DumpState.DUMP_CHANGES); 21109 } else if ("service-permissions".equals(cmd)) { 21110 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21111 } else if ("write".equals(cmd)) { 21112 synchronized (mPackages) { 21113 mSettings.writeLPr(); 21114 pw.println("Settings written."); 21115 return; 21116 } 21117 } 21118 } 21119 21120 if (checkin) { 21121 pw.println("vers,1"); 21122 } 21123 21124 // reader 21125 synchronized (mPackages) { 21126 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21127 if (!checkin) { 21128 if (dumpState.onTitlePrinted()) 21129 pw.println(); 21130 pw.println("Database versions:"); 21131 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21132 } 21133 } 21134 21135 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21136 if (!checkin) { 21137 if (dumpState.onTitlePrinted()) 21138 pw.println(); 21139 pw.println("Verifiers:"); 21140 pw.print(" Required: "); 21141 pw.print(mRequiredVerifierPackage); 21142 pw.print(" (uid="); 21143 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21144 UserHandle.USER_SYSTEM)); 21145 pw.println(")"); 21146 } else if (mRequiredVerifierPackage != null) { 21147 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21148 pw.print(","); 21149 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21150 UserHandle.USER_SYSTEM)); 21151 } 21152 } 21153 21154 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21155 packageName == null) { 21156 if (mIntentFilterVerifierComponent != null) { 21157 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21158 if (!checkin) { 21159 if (dumpState.onTitlePrinted()) 21160 pw.println(); 21161 pw.println("Intent Filter Verifier:"); 21162 pw.print(" Using: "); 21163 pw.print(verifierPackageName); 21164 pw.print(" (uid="); 21165 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21166 UserHandle.USER_SYSTEM)); 21167 pw.println(")"); 21168 } else if (verifierPackageName != null) { 21169 pw.print("ifv,"); pw.print(verifierPackageName); 21170 pw.print(","); 21171 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21172 UserHandle.USER_SYSTEM)); 21173 } 21174 } else { 21175 pw.println(); 21176 pw.println("No Intent Filter Verifier available!"); 21177 } 21178 } 21179 21180 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21181 boolean printedHeader = false; 21182 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21183 while (it.hasNext()) { 21184 String libName = it.next(); 21185 LongSparseArray<SharedLibraryEntry> versionedLib 21186 = mSharedLibraries.get(libName); 21187 if (versionedLib == null) { 21188 continue; 21189 } 21190 final int versionCount = versionedLib.size(); 21191 for (int i = 0; i < versionCount; i++) { 21192 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21193 if (!checkin) { 21194 if (!printedHeader) { 21195 if (dumpState.onTitlePrinted()) 21196 pw.println(); 21197 pw.println("Libraries:"); 21198 printedHeader = true; 21199 } 21200 pw.print(" "); 21201 } else { 21202 pw.print("lib,"); 21203 } 21204 pw.print(libEntry.info.getName()); 21205 if (libEntry.info.isStatic()) { 21206 pw.print(" version=" + libEntry.info.getLongVersion()); 21207 } 21208 if (!checkin) { 21209 pw.print(" -> "); 21210 } 21211 if (libEntry.path != null) { 21212 pw.print(" (jar) "); 21213 pw.print(libEntry.path); 21214 } else { 21215 pw.print(" (apk) "); 21216 pw.print(libEntry.apk); 21217 } 21218 pw.println(); 21219 } 21220 } 21221 } 21222 21223 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21224 if (dumpState.onTitlePrinted()) 21225 pw.println(); 21226 if (!checkin) { 21227 pw.println("Features:"); 21228 } 21229 21230 synchronized (mAvailableFeatures) { 21231 for (FeatureInfo feat : mAvailableFeatures.values()) { 21232 if (checkin) { 21233 pw.print("feat,"); 21234 pw.print(feat.name); 21235 pw.print(","); 21236 pw.println(feat.version); 21237 } else { 21238 pw.print(" "); 21239 pw.print(feat.name); 21240 if (feat.version > 0) { 21241 pw.print(" version="); 21242 pw.print(feat.version); 21243 } 21244 pw.println(); 21245 } 21246 } 21247 } 21248 } 21249 21250 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21251 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21252 : "Activity Resolver Table:", " ", packageName, 21253 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21254 dumpState.setTitlePrinted(true); 21255 } 21256 } 21257 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21258 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21259 : "Receiver Resolver Table:", " ", packageName, 21260 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21261 dumpState.setTitlePrinted(true); 21262 } 21263 } 21264 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21265 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21266 : "Service Resolver Table:", " ", packageName, 21267 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21268 dumpState.setTitlePrinted(true); 21269 } 21270 } 21271 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21272 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21273 : "Provider Resolver Table:", " ", packageName, 21274 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21275 dumpState.setTitlePrinted(true); 21276 } 21277 } 21278 21279 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21280 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21281 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21282 int user = mSettings.mPreferredActivities.keyAt(i); 21283 if (pir.dump(pw, 21284 dumpState.getTitlePrinted() 21285 ? "\nPreferred Activities User " + user + ":" 21286 : "Preferred Activities User " + user + ":", " ", 21287 packageName, true, false)) { 21288 dumpState.setTitlePrinted(true); 21289 } 21290 } 21291 } 21292 21293 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21294 pw.flush(); 21295 FileOutputStream fout = new FileOutputStream(fd); 21296 BufferedOutputStream str = new BufferedOutputStream(fout); 21297 XmlSerializer serializer = new FastXmlSerializer(); 21298 try { 21299 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21300 serializer.startDocument(null, true); 21301 serializer.setFeature( 21302 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21303 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21304 serializer.endDocument(); 21305 serializer.flush(); 21306 } catch (IllegalArgumentException e) { 21307 pw.println("Failed writing: " + e); 21308 } catch (IllegalStateException e) { 21309 pw.println("Failed writing: " + e); 21310 } catch (IOException e) { 21311 pw.println("Failed writing: " + e); 21312 } 21313 } 21314 21315 if (!checkin 21316 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21317 && packageName == null) { 21318 pw.println(); 21319 int count = mSettings.mPackages.size(); 21320 if (count == 0) { 21321 pw.println("No applications!"); 21322 pw.println(); 21323 } else { 21324 final String prefix = " "; 21325 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21326 if (allPackageSettings.size() == 0) { 21327 pw.println("No domain preferred apps!"); 21328 pw.println(); 21329 } else { 21330 pw.println("App verification status:"); 21331 pw.println(); 21332 count = 0; 21333 for (PackageSetting ps : allPackageSettings) { 21334 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21335 if (ivi == null || ivi.getPackageName() == null) continue; 21336 pw.println(prefix + "Package: " + ivi.getPackageName()); 21337 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21338 pw.println(prefix + "Status: " + ivi.getStatusString()); 21339 pw.println(); 21340 count++; 21341 } 21342 if (count == 0) { 21343 pw.println(prefix + "No app verification established."); 21344 pw.println(); 21345 } 21346 for (int userId : sUserManager.getUserIds()) { 21347 pw.println("App linkages for user " + userId + ":"); 21348 pw.println(); 21349 count = 0; 21350 for (PackageSetting ps : allPackageSettings) { 21351 final long status = ps.getDomainVerificationStatusForUser(userId); 21352 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21353 && !DEBUG_DOMAIN_VERIFICATION) { 21354 continue; 21355 } 21356 pw.println(prefix + "Package: " + ps.name); 21357 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21358 String statusStr = IntentFilterVerificationInfo. 21359 getStatusStringFromValue(status); 21360 pw.println(prefix + "Status: " + statusStr); 21361 pw.println(); 21362 count++; 21363 } 21364 if (count == 0) { 21365 pw.println(prefix + "No configured app linkages."); 21366 pw.println(); 21367 } 21368 } 21369 } 21370 } 21371 } 21372 21373 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21374 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21375 } 21376 21377 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21378 boolean printedSomething = false; 21379 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21380 if (packageName != null && !packageName.equals(p.info.packageName)) { 21381 continue; 21382 } 21383 if (!printedSomething) { 21384 if (dumpState.onTitlePrinted()) 21385 pw.println(); 21386 pw.println("Registered ContentProviders:"); 21387 printedSomething = true; 21388 } 21389 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21390 pw.print(" "); pw.println(p.toString()); 21391 } 21392 printedSomething = false; 21393 for (Map.Entry<String, PackageParser.Provider> entry : 21394 mProvidersByAuthority.entrySet()) { 21395 PackageParser.Provider p = entry.getValue(); 21396 if (packageName != null && !packageName.equals(p.info.packageName)) { 21397 continue; 21398 } 21399 if (!printedSomething) { 21400 if (dumpState.onTitlePrinted()) 21401 pw.println(); 21402 pw.println("ContentProvider Authorities:"); 21403 printedSomething = true; 21404 } 21405 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21406 pw.print(" "); pw.println(p.toString()); 21407 if (p.info != null && p.info.applicationInfo != null) { 21408 final String appInfo = p.info.applicationInfo.toString(); 21409 pw.print(" applicationInfo="); pw.println(appInfo); 21410 } 21411 } 21412 } 21413 21414 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21415 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21416 } 21417 21418 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21419 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21420 } 21421 21422 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21423 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21424 } 21425 21426 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21427 if (dumpState.onTitlePrinted()) pw.println(); 21428 pw.println("Package Changes:"); 21429 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21430 final int K = mChangedPackages.size(); 21431 for (int i = 0; i < K; i++) { 21432 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21433 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21434 final int N = changes.size(); 21435 if (N == 0) { 21436 pw.print(" "); pw.println("No packages changed"); 21437 } else { 21438 for (int j = 0; j < N; j++) { 21439 final String pkgName = changes.valueAt(j); 21440 final int sequenceNumber = changes.keyAt(j); 21441 pw.print(" "); 21442 pw.print("seq="); 21443 pw.print(sequenceNumber); 21444 pw.print(", package="); 21445 pw.println(pkgName); 21446 } 21447 } 21448 } 21449 } 21450 21451 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21452 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21453 } 21454 21455 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21456 // XXX should handle packageName != null by dumping only install data that 21457 // the given package is involved with. 21458 if (dumpState.onTitlePrinted()) pw.println(); 21459 21460 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21461 ipw.println(); 21462 ipw.println("Frozen packages:"); 21463 ipw.increaseIndent(); 21464 if (mFrozenPackages.size() == 0) { 21465 ipw.println("(none)"); 21466 } else { 21467 for (int i = 0; i < mFrozenPackages.size(); i++) { 21468 ipw.println(mFrozenPackages.valueAt(i)); 21469 } 21470 } 21471 ipw.decreaseIndent(); 21472 } 21473 } 21474 21475 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21476 if (dumpState.onTitlePrinted()) pw.println(); 21477 21478 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21479 ipw.println(); 21480 ipw.println("Loaded volumes:"); 21481 ipw.increaseIndent(); 21482 if (mLoadedVolumes.size() == 0) { 21483 ipw.println("(none)"); 21484 } else { 21485 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21486 ipw.println(mLoadedVolumes.valueAt(i)); 21487 } 21488 } 21489 ipw.decreaseIndent(); 21490 } 21491 } 21492 21493 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21494 && packageName == null) { 21495 if (dumpState.onTitlePrinted()) pw.println(); 21496 pw.println("Service permissions:"); 21497 21498 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21499 while (filterIterator.hasNext()) { 21500 final ServiceIntentInfo info = filterIterator.next(); 21501 final ServiceInfo serviceInfo = info.service.info; 21502 final String permission = serviceInfo.permission; 21503 if (permission != null) { 21504 pw.print(" "); 21505 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21506 pw.print(": "); 21507 pw.println(permission); 21508 } 21509 } 21510 } 21511 21512 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21513 if (dumpState.onTitlePrinted()) pw.println(); 21514 dumpDexoptStateLPr(pw, packageName); 21515 } 21516 21517 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21518 if (dumpState.onTitlePrinted()) pw.println(); 21519 dumpCompilerStatsLPr(pw, packageName); 21520 } 21521 21522 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21523 if (dumpState.onTitlePrinted()) pw.println(); 21524 mSettings.dumpReadMessagesLPr(pw, dumpState); 21525 21526 pw.println(); 21527 pw.println("Package warning messages:"); 21528 dumpCriticalInfo(pw, null); 21529 } 21530 21531 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21532 dumpCriticalInfo(pw, "msg,"); 21533 } 21534 } 21535 21536 // PackageInstaller should be called outside of mPackages lock 21537 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21538 // XXX should handle packageName != null by dumping only install data that 21539 // the given package is involved with. 21540 if (dumpState.onTitlePrinted()) pw.println(); 21541 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21542 } 21543 } 21544 21545 private void dumpProto(FileDescriptor fd) { 21546 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21547 21548 synchronized (mPackages) { 21549 final long requiredVerifierPackageToken = 21550 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21551 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21552 proto.write( 21553 PackageServiceDumpProto.PackageShortProto.UID, 21554 getPackageUid( 21555 mRequiredVerifierPackage, 21556 MATCH_DEBUG_TRIAGED_MISSING, 21557 UserHandle.USER_SYSTEM)); 21558 proto.end(requiredVerifierPackageToken); 21559 21560 if (mIntentFilterVerifierComponent != null) { 21561 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21562 final long verifierPackageToken = 21563 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21564 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21565 proto.write( 21566 PackageServiceDumpProto.PackageShortProto.UID, 21567 getPackageUid( 21568 verifierPackageName, 21569 MATCH_DEBUG_TRIAGED_MISSING, 21570 UserHandle.USER_SYSTEM)); 21571 proto.end(verifierPackageToken); 21572 } 21573 21574 dumpSharedLibrariesProto(proto); 21575 dumpFeaturesProto(proto); 21576 mSettings.dumpPackagesProto(proto); 21577 mSettings.dumpSharedUsersProto(proto); 21578 dumpCriticalInfo(proto); 21579 } 21580 proto.flush(); 21581 } 21582 21583 private void dumpFeaturesProto(ProtoOutputStream proto) { 21584 synchronized (mAvailableFeatures) { 21585 final int count = mAvailableFeatures.size(); 21586 for (int i = 0; i < count; i++) { 21587 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21588 } 21589 } 21590 } 21591 21592 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21593 final int count = mSharedLibraries.size(); 21594 for (int i = 0; i < count; i++) { 21595 final String libName = mSharedLibraries.keyAt(i); 21596 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21597 if (versionedLib == null) { 21598 continue; 21599 } 21600 final int versionCount = versionedLib.size(); 21601 for (int j = 0; j < versionCount; j++) { 21602 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21603 final long sharedLibraryToken = 21604 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21605 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21606 final boolean isJar = (libEntry.path != null); 21607 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21608 if (isJar) { 21609 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21610 } else { 21611 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21612 } 21613 proto.end(sharedLibraryToken); 21614 } 21615 } 21616 } 21617 21618 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21619 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21620 ipw.println(); 21621 ipw.println("Dexopt state:"); 21622 ipw.increaseIndent(); 21623 Collection<PackageParser.Package> packages = null; 21624 if (packageName != null) { 21625 PackageParser.Package targetPackage = mPackages.get(packageName); 21626 if (targetPackage != null) { 21627 packages = Collections.singletonList(targetPackage); 21628 } else { 21629 ipw.println("Unable to find package: " + packageName); 21630 return; 21631 } 21632 } else { 21633 packages = mPackages.values(); 21634 } 21635 21636 for (PackageParser.Package pkg : packages) { 21637 ipw.println("[" + pkg.packageName + "]"); 21638 ipw.increaseIndent(); 21639 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21640 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21641 ipw.decreaseIndent(); 21642 } 21643 } 21644 } 21645 21646 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21647 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21648 ipw.println(); 21649 ipw.println("Compiler stats:"); 21650 ipw.increaseIndent(); 21651 Collection<PackageParser.Package> packages = null; 21652 if (packageName != null) { 21653 PackageParser.Package targetPackage = mPackages.get(packageName); 21654 if (targetPackage != null) { 21655 packages = Collections.singletonList(targetPackage); 21656 } else { 21657 ipw.println("Unable to find package: " + packageName); 21658 return; 21659 } 21660 } else { 21661 packages = mPackages.values(); 21662 } 21663 21664 for (PackageParser.Package pkg : packages) { 21665 ipw.println("[" + pkg.packageName + "]"); 21666 ipw.increaseIndent(); 21667 21668 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21669 if (stats == null) { 21670 ipw.println("(No recorded stats)"); 21671 } else { 21672 stats.dump(ipw); 21673 } 21674 ipw.decreaseIndent(); 21675 } 21676 } 21677 } 21678 21679 private String dumpDomainString(String packageName) { 21680 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21681 .getList(); 21682 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21683 21684 ArraySet<String> result = new ArraySet<>(); 21685 if (iviList.size() > 0) { 21686 for (IntentFilterVerificationInfo ivi : iviList) { 21687 for (String host : ivi.getDomains()) { 21688 result.add(host); 21689 } 21690 } 21691 } 21692 if (filters != null && filters.size() > 0) { 21693 for (IntentFilter filter : filters) { 21694 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21695 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21696 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21697 result.addAll(filter.getHostsList()); 21698 } 21699 } 21700 } 21701 21702 StringBuilder sb = new StringBuilder(result.size() * 16); 21703 for (String domain : result) { 21704 if (sb.length() > 0) sb.append(" "); 21705 sb.append(domain); 21706 } 21707 return sb.toString(); 21708 } 21709 21710 // ------- apps on sdcard specific code ------- 21711 static final boolean DEBUG_SD_INSTALL = false; 21712 21713 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21714 21715 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21716 21717 private boolean mMediaMounted = false; 21718 21719 static String getEncryptKey() { 21720 try { 21721 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21722 SD_ENCRYPTION_KEYSTORE_NAME); 21723 if (sdEncKey == null) { 21724 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21725 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21726 if (sdEncKey == null) { 21727 Slog.e(TAG, "Failed to create encryption keys"); 21728 return null; 21729 } 21730 } 21731 return sdEncKey; 21732 } catch (NoSuchAlgorithmException nsae) { 21733 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21734 return null; 21735 } catch (IOException ioe) { 21736 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21737 return null; 21738 } 21739 } 21740 21741 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21742 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21743 final int size = infos.size(); 21744 final String[] packageNames = new String[size]; 21745 final int[] packageUids = new int[size]; 21746 for (int i = 0; i < size; i++) { 21747 final ApplicationInfo info = infos.get(i); 21748 packageNames[i] = info.packageName; 21749 packageUids[i] = info.uid; 21750 } 21751 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21752 finishedReceiver); 21753 } 21754 21755 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21756 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21757 sendResourcesChangedBroadcast(mediaStatus, replacing, 21758 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21759 } 21760 21761 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21762 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21763 int size = pkgList.length; 21764 if (size > 0) { 21765 // Send broadcasts here 21766 Bundle extras = new Bundle(); 21767 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21768 if (uidArr != null) { 21769 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21770 } 21771 if (replacing) { 21772 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21773 } 21774 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21775 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21776 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21777 } 21778 } 21779 21780 private void loadPrivatePackages(final VolumeInfo vol) { 21781 mHandler.post(new Runnable() { 21782 @Override 21783 public void run() { 21784 loadPrivatePackagesInner(vol); 21785 } 21786 }); 21787 } 21788 21789 private void loadPrivatePackagesInner(VolumeInfo vol) { 21790 final String volumeUuid = vol.fsUuid; 21791 if (TextUtils.isEmpty(volumeUuid)) { 21792 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21793 return; 21794 } 21795 21796 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21797 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21798 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21799 21800 final VersionInfo ver; 21801 final List<PackageSetting> packages; 21802 synchronized (mPackages) { 21803 ver = mSettings.findOrCreateVersion(volumeUuid); 21804 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21805 } 21806 21807 for (PackageSetting ps : packages) { 21808 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21809 synchronized (mInstallLock) { 21810 final PackageParser.Package pkg; 21811 try { 21812 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21813 loaded.add(pkg.applicationInfo); 21814 21815 } catch (PackageManagerException e) { 21816 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21817 } 21818 21819 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21820 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21821 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21822 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21823 } 21824 } 21825 } 21826 21827 // Reconcile app data for all started/unlocked users 21828 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21829 final UserManager um = mContext.getSystemService(UserManager.class); 21830 UserManagerInternal umInternal = getUserManagerInternal(); 21831 for (UserInfo user : um.getUsers()) { 21832 final int flags; 21833 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21834 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21835 } else if (umInternal.isUserRunning(user.id)) { 21836 flags = StorageManager.FLAG_STORAGE_DE; 21837 } else { 21838 continue; 21839 } 21840 21841 try { 21842 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21843 synchronized (mInstallLock) { 21844 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21845 } 21846 } catch (IllegalStateException e) { 21847 // Device was probably ejected, and we'll process that event momentarily 21848 Slog.w(TAG, "Failed to prepare storage: " + e); 21849 } 21850 } 21851 21852 synchronized (mPackages) { 21853 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21854 if (sdkUpdated) { 21855 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21856 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21857 } 21858 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21859 mPermissionCallback); 21860 21861 // Yay, everything is now upgraded 21862 ver.forceCurrent(); 21863 21864 mSettings.writeLPr(); 21865 } 21866 21867 for (PackageFreezer freezer : freezers) { 21868 freezer.close(); 21869 } 21870 21871 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21872 sendResourcesChangedBroadcast(true, false, loaded, null); 21873 mLoadedVolumes.add(vol.getId()); 21874 } 21875 21876 private void unloadPrivatePackages(final VolumeInfo vol) { 21877 mHandler.post(new Runnable() { 21878 @Override 21879 public void run() { 21880 unloadPrivatePackagesInner(vol); 21881 } 21882 }); 21883 } 21884 21885 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21886 final String volumeUuid = vol.fsUuid; 21887 if (TextUtils.isEmpty(volumeUuid)) { 21888 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21889 return; 21890 } 21891 21892 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21893 synchronized (mInstallLock) { 21894 synchronized (mPackages) { 21895 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21896 for (PackageSetting ps : packages) { 21897 if (ps.pkg == null) continue; 21898 21899 final ApplicationInfo info = ps.pkg.applicationInfo; 21900 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21901 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21902 21903 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21904 "unloadPrivatePackagesInner")) { 21905 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21906 false, null)) { 21907 unloaded.add(info); 21908 } else { 21909 Slog.w(TAG, "Failed to unload " + ps.codePath); 21910 } 21911 } 21912 21913 // Try very hard to release any references to this package 21914 // so we don't risk the system server being killed due to 21915 // open FDs 21916 AttributeCache.instance().removePackage(ps.name); 21917 } 21918 21919 mSettings.writeLPr(); 21920 } 21921 } 21922 21923 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21924 sendResourcesChangedBroadcast(false, false, unloaded, null); 21925 mLoadedVolumes.remove(vol.getId()); 21926 21927 // Try very hard to release any references to this path so we don't risk 21928 // the system server being killed due to open FDs 21929 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21930 21931 for (int i = 0; i < 3; i++) { 21932 System.gc(); 21933 System.runFinalization(); 21934 } 21935 } 21936 21937 private void assertPackageKnown(String volumeUuid, String packageName) 21938 throws PackageManagerException { 21939 synchronized (mPackages) { 21940 // Normalize package name to handle renamed packages 21941 packageName = normalizePackageNameLPr(packageName); 21942 21943 final PackageSetting ps = mSettings.mPackages.get(packageName); 21944 if (ps == null) { 21945 throw new PackageManagerException("Package " + packageName + " is unknown"); 21946 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21947 throw new PackageManagerException( 21948 "Package " + packageName + " found on unknown volume " + volumeUuid 21949 + "; expected volume " + ps.volumeUuid); 21950 } 21951 } 21952 } 21953 21954 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21955 throws PackageManagerException { 21956 synchronized (mPackages) { 21957 // Normalize package name to handle renamed packages 21958 packageName = normalizePackageNameLPr(packageName); 21959 21960 final PackageSetting ps = mSettings.mPackages.get(packageName); 21961 if (ps == null) { 21962 throw new PackageManagerException("Package " + packageName + " is unknown"); 21963 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21964 throw new PackageManagerException( 21965 "Package " + packageName + " found on unknown volume " + volumeUuid 21966 + "; expected volume " + ps.volumeUuid); 21967 } else if (!ps.getInstalled(userId)) { 21968 throw new PackageManagerException( 21969 "Package " + packageName + " not installed for user " + userId); 21970 } 21971 } 21972 } 21973 21974 private List<String> collectAbsoluteCodePaths() { 21975 synchronized (mPackages) { 21976 List<String> codePaths = new ArrayList<>(); 21977 final int packageCount = mSettings.mPackages.size(); 21978 for (int i = 0; i < packageCount; i++) { 21979 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21980 codePaths.add(ps.codePath.getAbsolutePath()); 21981 } 21982 return codePaths; 21983 } 21984 } 21985 21986 /** 21987 * Examine all apps present on given mounted volume, and destroy apps that 21988 * aren't expected, either due to uninstallation or reinstallation on 21989 * another volume. 21990 */ 21991 private void reconcileApps(String volumeUuid) { 21992 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21993 List<File> filesToDelete = null; 21994 21995 final File[] files = FileUtils.listFilesOrEmpty( 21996 Environment.getDataAppDirectory(volumeUuid)); 21997 for (File file : files) { 21998 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21999 && !PackageInstallerService.isStageName(file.getName()); 22000 if (!isPackage) { 22001 // Ignore entries which are not packages 22002 continue; 22003 } 22004 22005 String absolutePath = file.getAbsolutePath(); 22006 22007 boolean pathValid = false; 22008 final int absoluteCodePathCount = absoluteCodePaths.size(); 22009 for (int i = 0; i < absoluteCodePathCount; i++) { 22010 String absoluteCodePath = absoluteCodePaths.get(i); 22011 if (absolutePath.startsWith(absoluteCodePath)) { 22012 pathValid = true; 22013 break; 22014 } 22015 } 22016 22017 if (!pathValid) { 22018 if (filesToDelete == null) { 22019 filesToDelete = new ArrayList<>(); 22020 } 22021 filesToDelete.add(file); 22022 } 22023 } 22024 22025 if (filesToDelete != null) { 22026 final int fileToDeleteCount = filesToDelete.size(); 22027 for (int i = 0; i < fileToDeleteCount; i++) { 22028 File fileToDelete = filesToDelete.get(i); 22029 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22030 synchronized (mInstallLock) { 22031 removeCodePathLI(fileToDelete); 22032 } 22033 } 22034 } 22035 } 22036 22037 /** 22038 * Reconcile all app data for the given user. 22039 * <p> 22040 * Verifies that directories exist and that ownership and labeling is 22041 * correct for all installed apps on all mounted volumes. 22042 */ 22043 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22044 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22045 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22046 final String volumeUuid = vol.getFsUuid(); 22047 synchronized (mInstallLock) { 22048 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22049 } 22050 } 22051 } 22052 22053 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22054 boolean migrateAppData) { 22055 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22056 } 22057 22058 /** 22059 * Reconcile all app data on given mounted volume. 22060 * <p> 22061 * Destroys app data that isn't expected, either due to uninstallation or 22062 * reinstallation on another volume. 22063 * <p> 22064 * Verifies that directories exist and that ownership and labeling is 22065 * correct for all installed apps. 22066 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22067 */ 22068 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22069 boolean migrateAppData, boolean onlyCoreApps) { 22070 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22071 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22072 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22073 22074 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22075 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22076 22077 // First look for stale data that doesn't belong, and check if things 22078 // have changed since we did our last restorecon 22079 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22080 if (StorageManager.isFileEncryptedNativeOrEmulated() 22081 && !StorageManager.isUserKeyUnlocked(userId)) { 22082 throw new RuntimeException( 22083 "Yikes, someone asked us to reconcile CE storage while " + userId 22084 + " was still locked; this would have caused massive data loss!"); 22085 } 22086 22087 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22088 for (File file : files) { 22089 final String packageName = file.getName(); 22090 try { 22091 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22092 } catch (PackageManagerException e) { 22093 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22094 try { 22095 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22096 StorageManager.FLAG_STORAGE_CE, 0); 22097 } catch (InstallerException e2) { 22098 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22099 } 22100 } 22101 } 22102 } 22103 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22104 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22105 for (File file : files) { 22106 final String packageName = file.getName(); 22107 try { 22108 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22109 } catch (PackageManagerException e) { 22110 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22111 try { 22112 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22113 StorageManager.FLAG_STORAGE_DE, 0); 22114 } catch (InstallerException e2) { 22115 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22116 } 22117 } 22118 } 22119 } 22120 22121 // Ensure that data directories are ready to roll for all packages 22122 // installed for this volume and user 22123 final List<PackageSetting> packages; 22124 synchronized (mPackages) { 22125 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22126 } 22127 int preparedCount = 0; 22128 for (PackageSetting ps : packages) { 22129 final String packageName = ps.name; 22130 if (ps.pkg == null) { 22131 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22132 // TODO: might be due to legacy ASEC apps; we should circle back 22133 // and reconcile again once they're scanned 22134 continue; 22135 } 22136 // Skip non-core apps if requested 22137 if (onlyCoreApps && !ps.pkg.coreApp) { 22138 result.add(packageName); 22139 continue; 22140 } 22141 22142 if (ps.getInstalled(userId)) { 22143 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22144 preparedCount++; 22145 } 22146 } 22147 22148 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22149 return result; 22150 } 22151 22152 /** 22153 * Prepare app data for the given app just after it was installed or 22154 * upgraded. This method carefully only touches users that it's installed 22155 * for, and it forces a restorecon to handle any seinfo changes. 22156 * <p> 22157 * Verifies that directories exist and that ownership and labeling is 22158 * correct for all installed apps. If there is an ownership mismatch, it 22159 * will try recovering system apps by wiping data; third-party app data is 22160 * left intact. 22161 * <p> 22162 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22163 */ 22164 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22165 final PackageSetting ps; 22166 synchronized (mPackages) { 22167 ps = mSettings.mPackages.get(pkg.packageName); 22168 mSettings.writeKernelMappingLPr(ps); 22169 } 22170 22171 final UserManager um = mContext.getSystemService(UserManager.class); 22172 UserManagerInternal umInternal = getUserManagerInternal(); 22173 for (UserInfo user : um.getUsers()) { 22174 final int flags; 22175 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22176 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22177 } else if (umInternal.isUserRunning(user.id)) { 22178 flags = StorageManager.FLAG_STORAGE_DE; 22179 } else { 22180 continue; 22181 } 22182 22183 if (ps.getInstalled(user.id)) { 22184 // TODO: when user data is locked, mark that we're still dirty 22185 prepareAppDataLIF(pkg, user.id, flags); 22186 } 22187 } 22188 } 22189 22190 /** 22191 * Prepare app data for the given app. 22192 * <p> 22193 * Verifies that directories exist and that ownership and labeling is 22194 * correct for all installed apps. If there is an ownership mismatch, this 22195 * will try recovering system apps by wiping data; third-party app data is 22196 * left intact. 22197 */ 22198 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22199 if (pkg == null) { 22200 Slog.wtf(TAG, "Package was null!", new Throwable()); 22201 return; 22202 } 22203 prepareAppDataLeafLIF(pkg, userId, flags); 22204 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22205 for (int i = 0; i < childCount; i++) { 22206 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22207 } 22208 } 22209 22210 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22211 boolean maybeMigrateAppData) { 22212 prepareAppDataLIF(pkg, userId, flags); 22213 22214 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22215 // We may have just shuffled around app data directories, so 22216 // prepare them one more time 22217 prepareAppDataLIF(pkg, userId, flags); 22218 } 22219 } 22220 22221 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22222 if (DEBUG_APP_DATA) { 22223 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22224 + Integer.toHexString(flags)); 22225 } 22226 22227 final String volumeUuid = pkg.volumeUuid; 22228 final String packageName = pkg.packageName; 22229 final ApplicationInfo app = pkg.applicationInfo; 22230 final int appId = UserHandle.getAppId(app.uid); 22231 22232 Preconditions.checkNotNull(app.seInfo); 22233 22234 long ceDataInode = -1; 22235 try { 22236 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22237 appId, app.seInfo, app.targetSdkVersion); 22238 } catch (InstallerException e) { 22239 if (app.isSystemApp()) { 22240 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22241 + ", but trying to recover: " + e); 22242 destroyAppDataLeafLIF(pkg, userId, flags); 22243 try { 22244 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22245 appId, app.seInfo, app.targetSdkVersion); 22246 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22247 } catch (InstallerException e2) { 22248 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22249 } 22250 } else { 22251 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22252 } 22253 } 22254 // Prepare the application profiles only for upgrades and first boot (so that we don't 22255 // repeat the same operation at each boot). 22256 // We only have to cover the upgrade and first boot here because for app installs we 22257 // prepare the profiles before invoking dexopt (in installPackageLI). 22258 // 22259 // We also have to cover non system users because we do not call the usual install package 22260 // methods for them. 22261 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22262 mArtManagerService.prepareAppProfiles(pkg, userId); 22263 } 22264 22265 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22266 // TODO: mark this structure as dirty so we persist it! 22267 synchronized (mPackages) { 22268 final PackageSetting ps = mSettings.mPackages.get(packageName); 22269 if (ps != null) { 22270 ps.setCeDataInode(ceDataInode, userId); 22271 } 22272 } 22273 } 22274 22275 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22276 } 22277 22278 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22279 if (pkg == null) { 22280 Slog.wtf(TAG, "Package was null!", new Throwable()); 22281 return; 22282 } 22283 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22284 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22285 for (int i = 0; i < childCount; i++) { 22286 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22287 } 22288 } 22289 22290 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22291 final String volumeUuid = pkg.volumeUuid; 22292 final String packageName = pkg.packageName; 22293 final ApplicationInfo app = pkg.applicationInfo; 22294 22295 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22296 // Create a native library symlink only if we have native libraries 22297 // and if the native libraries are 32 bit libraries. We do not provide 22298 // this symlink for 64 bit libraries. 22299 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22300 final String nativeLibPath = app.nativeLibraryDir; 22301 try { 22302 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22303 nativeLibPath, userId); 22304 } catch (InstallerException e) { 22305 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22306 } 22307 } 22308 } 22309 } 22310 22311 /** 22312 * For system apps on non-FBE devices, this method migrates any existing 22313 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22314 * requested by the app. 22315 */ 22316 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22317 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22318 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22319 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22320 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22321 try { 22322 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22323 storageTarget); 22324 } catch (InstallerException e) { 22325 logCriticalInfo(Log.WARN, 22326 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22327 } 22328 return true; 22329 } else { 22330 return false; 22331 } 22332 } 22333 22334 public PackageFreezer freezePackage(String packageName, String killReason) { 22335 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22336 } 22337 22338 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22339 return new PackageFreezer(packageName, userId, killReason); 22340 } 22341 22342 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22343 String killReason) { 22344 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22345 } 22346 22347 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22348 String killReason) { 22349 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22350 return new PackageFreezer(); 22351 } else { 22352 return freezePackage(packageName, userId, killReason); 22353 } 22354 } 22355 22356 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22357 String killReason) { 22358 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22359 } 22360 22361 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22362 String killReason) { 22363 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22364 return new PackageFreezer(); 22365 } else { 22366 return freezePackage(packageName, userId, killReason); 22367 } 22368 } 22369 22370 /** 22371 * Class that freezes and kills the given package upon creation, and 22372 * unfreezes it upon closing. This is typically used when doing surgery on 22373 * app code/data to prevent the app from running while you're working. 22374 */ 22375 private class PackageFreezer implements AutoCloseable { 22376 private final String mPackageName; 22377 private final PackageFreezer[] mChildren; 22378 22379 private final boolean mWeFroze; 22380 22381 private final AtomicBoolean mClosed = new AtomicBoolean(); 22382 private final CloseGuard mCloseGuard = CloseGuard.get(); 22383 22384 /** 22385 * Create and return a stub freezer that doesn't actually do anything, 22386 * typically used when someone requested 22387 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22388 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22389 */ 22390 public PackageFreezer() { 22391 mPackageName = null; 22392 mChildren = null; 22393 mWeFroze = false; 22394 mCloseGuard.open("close"); 22395 } 22396 22397 public PackageFreezer(String packageName, int userId, String killReason) { 22398 synchronized (mPackages) { 22399 mPackageName = packageName; 22400 mWeFroze = mFrozenPackages.add(mPackageName); 22401 22402 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22403 if (ps != null) { 22404 killApplication(ps.name, ps.appId, userId, killReason); 22405 } 22406 22407 final PackageParser.Package p = mPackages.get(packageName); 22408 if (p != null && p.childPackages != null) { 22409 final int N = p.childPackages.size(); 22410 mChildren = new PackageFreezer[N]; 22411 for (int i = 0; i < N; i++) { 22412 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22413 userId, killReason); 22414 } 22415 } else { 22416 mChildren = null; 22417 } 22418 } 22419 mCloseGuard.open("close"); 22420 } 22421 22422 @Override 22423 protected void finalize() throws Throwable { 22424 try { 22425 if (mCloseGuard != null) { 22426 mCloseGuard.warnIfOpen(); 22427 } 22428 22429 close(); 22430 } finally { 22431 super.finalize(); 22432 } 22433 } 22434 22435 @Override 22436 public void close() { 22437 mCloseGuard.close(); 22438 if (mClosed.compareAndSet(false, true)) { 22439 synchronized (mPackages) { 22440 if (mWeFroze) { 22441 mFrozenPackages.remove(mPackageName); 22442 } 22443 22444 if (mChildren != null) { 22445 for (PackageFreezer freezer : mChildren) { 22446 freezer.close(); 22447 } 22448 } 22449 } 22450 } 22451 } 22452 } 22453 22454 /** 22455 * Verify that given package is currently frozen. 22456 */ 22457 private void checkPackageFrozen(String packageName) { 22458 synchronized (mPackages) { 22459 if (!mFrozenPackages.contains(packageName)) { 22460 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22461 } 22462 } 22463 } 22464 22465 @Override 22466 public int movePackage(final String packageName, final String volumeUuid) { 22467 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22468 22469 final int callingUid = Binder.getCallingUid(); 22470 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22471 final int moveId = mNextMoveId.getAndIncrement(); 22472 mHandler.post(new Runnable() { 22473 @Override 22474 public void run() { 22475 try { 22476 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22477 } catch (PackageManagerException e) { 22478 Slog.w(TAG, "Failed to move " + packageName, e); 22479 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22480 } 22481 } 22482 }); 22483 return moveId; 22484 } 22485 22486 private void movePackageInternal(final String packageName, final String volumeUuid, 22487 final int moveId, final int callingUid, UserHandle user) 22488 throws PackageManagerException { 22489 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22490 final PackageManager pm = mContext.getPackageManager(); 22491 22492 final boolean currentAsec; 22493 final String currentVolumeUuid; 22494 final File codeFile; 22495 final String installerPackageName; 22496 final String packageAbiOverride; 22497 final int appId; 22498 final String seinfo; 22499 final String label; 22500 final int targetSdkVersion; 22501 final PackageFreezer freezer; 22502 final int[] installedUserIds; 22503 22504 // reader 22505 synchronized (mPackages) { 22506 final PackageParser.Package pkg = mPackages.get(packageName); 22507 final PackageSetting ps = mSettings.mPackages.get(packageName); 22508 if (pkg == null 22509 || ps == null 22510 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22511 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22512 } 22513 if (pkg.applicationInfo.isSystemApp()) { 22514 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22515 "Cannot move system application"); 22516 } 22517 22518 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22519 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22520 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22521 if (isInternalStorage && !allow3rdPartyOnInternal) { 22522 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22523 "3rd party apps are not allowed on internal storage"); 22524 } 22525 22526 if (pkg.applicationInfo.isExternalAsec()) { 22527 currentAsec = true; 22528 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22529 } else if (pkg.applicationInfo.isForwardLocked()) { 22530 currentAsec = true; 22531 currentVolumeUuid = "forward_locked"; 22532 } else { 22533 currentAsec = false; 22534 currentVolumeUuid = ps.volumeUuid; 22535 22536 final File probe = new File(pkg.codePath); 22537 final File probeOat = new File(probe, "oat"); 22538 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22539 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22540 "Move only supported for modern cluster style installs"); 22541 } 22542 } 22543 22544 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22545 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22546 "Package already moved to " + volumeUuid); 22547 } 22548 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22549 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22550 "Device admin cannot be moved"); 22551 } 22552 22553 if (mFrozenPackages.contains(packageName)) { 22554 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22555 "Failed to move already frozen package"); 22556 } 22557 22558 codeFile = new File(pkg.codePath); 22559 installerPackageName = ps.installerPackageName; 22560 packageAbiOverride = ps.cpuAbiOverrideString; 22561 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22562 seinfo = pkg.applicationInfo.seInfo; 22563 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22564 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22565 freezer = freezePackage(packageName, "movePackageInternal"); 22566 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22567 } 22568 22569 final Bundle extras = new Bundle(); 22570 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22571 extras.putString(Intent.EXTRA_TITLE, label); 22572 mMoveCallbacks.notifyCreated(moveId, extras); 22573 22574 int installFlags; 22575 final boolean moveCompleteApp; 22576 final File measurePath; 22577 22578 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22579 installFlags = INSTALL_INTERNAL; 22580 moveCompleteApp = !currentAsec; 22581 measurePath = Environment.getDataAppDirectory(volumeUuid); 22582 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22583 installFlags = INSTALL_EXTERNAL; 22584 moveCompleteApp = false; 22585 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22586 } else { 22587 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22588 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22589 || !volume.isMountedWritable()) { 22590 freezer.close(); 22591 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22592 "Move location not mounted private volume"); 22593 } 22594 22595 Preconditions.checkState(!currentAsec); 22596 22597 installFlags = INSTALL_INTERNAL; 22598 moveCompleteApp = true; 22599 measurePath = Environment.getDataAppDirectory(volumeUuid); 22600 } 22601 22602 // If we're moving app data around, we need all the users unlocked 22603 if (moveCompleteApp) { 22604 for (int userId : installedUserIds) { 22605 if (StorageManager.isFileEncryptedNativeOrEmulated() 22606 && !StorageManager.isUserKeyUnlocked(userId)) { 22607 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22608 "User " + userId + " must be unlocked"); 22609 } 22610 } 22611 } 22612 22613 final PackageStats stats = new PackageStats(null, -1); 22614 synchronized (mInstaller) { 22615 for (int userId : installedUserIds) { 22616 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22617 freezer.close(); 22618 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22619 "Failed to measure package size"); 22620 } 22621 } 22622 } 22623 22624 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22625 + stats.dataSize); 22626 22627 final long startFreeBytes = measurePath.getUsableSpace(); 22628 final long sizeBytes; 22629 if (moveCompleteApp) { 22630 sizeBytes = stats.codeSize + stats.dataSize; 22631 } else { 22632 sizeBytes = stats.codeSize; 22633 } 22634 22635 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22636 freezer.close(); 22637 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22638 "Not enough free space to move"); 22639 } 22640 22641 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22642 22643 final CountDownLatch installedLatch = new CountDownLatch(1); 22644 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22645 @Override 22646 public void onUserActionRequired(Intent intent) throws RemoteException { 22647 throw new IllegalStateException(); 22648 } 22649 22650 @Override 22651 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22652 Bundle extras) throws RemoteException { 22653 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22654 + PackageManager.installStatusToString(returnCode, msg)); 22655 22656 installedLatch.countDown(); 22657 freezer.close(); 22658 22659 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22660 switch (status) { 22661 case PackageInstaller.STATUS_SUCCESS: 22662 mMoveCallbacks.notifyStatusChanged(moveId, 22663 PackageManager.MOVE_SUCCEEDED); 22664 break; 22665 case PackageInstaller.STATUS_FAILURE_STORAGE: 22666 mMoveCallbacks.notifyStatusChanged(moveId, 22667 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22668 break; 22669 default: 22670 mMoveCallbacks.notifyStatusChanged(moveId, 22671 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22672 break; 22673 } 22674 } 22675 }; 22676 22677 final MoveInfo move; 22678 if (moveCompleteApp) { 22679 // Kick off a thread to report progress estimates 22680 new Thread() { 22681 @Override 22682 public void run() { 22683 while (true) { 22684 try { 22685 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22686 break; 22687 } 22688 } catch (InterruptedException ignored) { 22689 } 22690 22691 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22692 final int progress = 10 + (int) MathUtils.constrain( 22693 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22694 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22695 } 22696 } 22697 }.start(); 22698 22699 final String dataAppName = codeFile.getName(); 22700 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22701 dataAppName, appId, seinfo, targetSdkVersion); 22702 } else { 22703 move = null; 22704 } 22705 22706 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22707 22708 final Message msg = mHandler.obtainMessage(INIT_COPY); 22709 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22710 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22711 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22712 packageAbiOverride, null /*grantedPermissions*/, 22713 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22714 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22715 msg.obj = params; 22716 22717 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22718 System.identityHashCode(msg.obj)); 22719 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22720 System.identityHashCode(msg.obj)); 22721 22722 mHandler.sendMessage(msg); 22723 } 22724 22725 @Override 22726 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22727 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22728 22729 final int realMoveId = mNextMoveId.getAndIncrement(); 22730 final Bundle extras = new Bundle(); 22731 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22732 mMoveCallbacks.notifyCreated(realMoveId, extras); 22733 22734 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22735 @Override 22736 public void onCreated(int moveId, Bundle extras) { 22737 // Ignored 22738 } 22739 22740 @Override 22741 public void onStatusChanged(int moveId, int status, long estMillis) { 22742 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22743 } 22744 }; 22745 22746 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22747 storage.setPrimaryStorageUuid(volumeUuid, callback); 22748 return realMoveId; 22749 } 22750 22751 @Override 22752 public int getMoveStatus(int moveId) { 22753 mContext.enforceCallingOrSelfPermission( 22754 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22755 return mMoveCallbacks.mLastStatus.get(moveId); 22756 } 22757 22758 @Override 22759 public void registerMoveCallback(IPackageMoveObserver callback) { 22760 mContext.enforceCallingOrSelfPermission( 22761 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22762 mMoveCallbacks.register(callback); 22763 } 22764 22765 @Override 22766 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22767 mContext.enforceCallingOrSelfPermission( 22768 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22769 mMoveCallbacks.unregister(callback); 22770 } 22771 22772 @Override 22773 public boolean setInstallLocation(int loc) { 22774 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22775 null); 22776 if (getInstallLocation() == loc) { 22777 return true; 22778 } 22779 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22780 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22781 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22782 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22783 return true; 22784 } 22785 return false; 22786 } 22787 22788 @Override 22789 public int getInstallLocation() { 22790 // allow instant app access 22791 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22792 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22793 PackageHelper.APP_INSTALL_AUTO); 22794 } 22795 22796 /** Called by UserManagerService */ 22797 void cleanUpUser(UserManagerService userManager, int userHandle) { 22798 synchronized (mPackages) { 22799 mDirtyUsers.remove(userHandle); 22800 mUserNeedsBadging.delete(userHandle); 22801 mSettings.removeUserLPw(userHandle); 22802 mPendingBroadcasts.remove(userHandle); 22803 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22804 removeUnusedPackagesLPw(userManager, userHandle); 22805 } 22806 } 22807 22808 /** 22809 * We're removing userHandle and would like to remove any downloaded packages 22810 * that are no longer in use by any other user. 22811 * @param userHandle the user being removed 22812 */ 22813 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22814 final boolean DEBUG_CLEAN_APKS = false; 22815 int [] users = userManager.getUserIds(); 22816 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22817 while (psit.hasNext()) { 22818 PackageSetting ps = psit.next(); 22819 if (ps.pkg == null) { 22820 continue; 22821 } 22822 final String packageName = ps.pkg.packageName; 22823 // Skip over if system app 22824 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22825 continue; 22826 } 22827 if (DEBUG_CLEAN_APKS) { 22828 Slog.i(TAG, "Checking package " + packageName); 22829 } 22830 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22831 if (keep) { 22832 if (DEBUG_CLEAN_APKS) { 22833 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22834 } 22835 } else { 22836 for (int i = 0; i < users.length; i++) { 22837 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22838 keep = true; 22839 if (DEBUG_CLEAN_APKS) { 22840 Slog.i(TAG, " Keeping package " + packageName + " for user " 22841 + users[i]); 22842 } 22843 break; 22844 } 22845 } 22846 } 22847 if (!keep) { 22848 if (DEBUG_CLEAN_APKS) { 22849 Slog.i(TAG, " Removing package " + packageName); 22850 } 22851 mHandler.post(new Runnable() { 22852 public void run() { 22853 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22854 userHandle, 0); 22855 } //end run 22856 }); 22857 } 22858 } 22859 } 22860 22861 /** Called by UserManagerService */ 22862 void createNewUser(int userId, String[] disallowedPackages) { 22863 synchronized (mInstallLock) { 22864 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22865 } 22866 synchronized (mPackages) { 22867 scheduleWritePackageRestrictionsLocked(userId); 22868 scheduleWritePackageListLocked(userId); 22869 applyFactoryDefaultBrowserLPw(userId); 22870 primeDomainVerificationsLPw(userId); 22871 } 22872 } 22873 22874 void onNewUserCreated(final int userId) { 22875 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22876 synchronized(mPackages) { 22877 // If permission review for legacy apps is required, we represent 22878 // dagerous permissions for such apps as always granted runtime 22879 // permissions to keep per user flag state whether review is needed. 22880 // Hence, if a new user is added we have to propagate dangerous 22881 // permission grants for these legacy apps. 22882 if (mSettings.mPermissions.mPermissionReviewRequired) { 22883// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22884 mPermissionManager.updateAllPermissions( 22885 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22886 mPermissionCallback); 22887 } 22888 } 22889 } 22890 22891 @Override 22892 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22893 mContext.enforceCallingOrSelfPermission( 22894 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22895 "Only package verification agents can read the verifier device identity"); 22896 22897 synchronized (mPackages) { 22898 return mSettings.getVerifierDeviceIdentityLPw(); 22899 } 22900 } 22901 22902 @Override 22903 public void setPermissionEnforced(String permission, boolean enforced) { 22904 // TODO: Now that we no longer change GID for storage, this should to away. 22905 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22906 "setPermissionEnforced"); 22907 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22908 synchronized (mPackages) { 22909 if (mSettings.mReadExternalStorageEnforced == null 22910 || mSettings.mReadExternalStorageEnforced != enforced) { 22911 mSettings.mReadExternalStorageEnforced = 22912 enforced ? Boolean.TRUE : Boolean.FALSE; 22913 mSettings.writeLPr(); 22914 } 22915 } 22916 // kill any non-foreground processes so we restart them and 22917 // grant/revoke the GID. 22918 final IActivityManager am = ActivityManager.getService(); 22919 if (am != null) { 22920 final long token = Binder.clearCallingIdentity(); 22921 try { 22922 am.killProcessesBelowForeground("setPermissionEnforcement"); 22923 } catch (RemoteException e) { 22924 } finally { 22925 Binder.restoreCallingIdentity(token); 22926 } 22927 } 22928 } else { 22929 throw new IllegalArgumentException("No selective enforcement for " + permission); 22930 } 22931 } 22932 22933 @Override 22934 @Deprecated 22935 public boolean isPermissionEnforced(String permission) { 22936 // allow instant applications 22937 return true; 22938 } 22939 22940 @Override 22941 public boolean isStorageLow() { 22942 // allow instant applications 22943 final long token = Binder.clearCallingIdentity(); 22944 try { 22945 final DeviceStorageMonitorInternal 22946 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22947 if (dsm != null) { 22948 return dsm.isMemoryLow(); 22949 } else { 22950 return false; 22951 } 22952 } finally { 22953 Binder.restoreCallingIdentity(token); 22954 } 22955 } 22956 22957 @Override 22958 public IPackageInstaller getPackageInstaller() { 22959 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22960 return null; 22961 } 22962 return mInstallerService; 22963 } 22964 22965 @Override 22966 public IArtManager getArtManager() { 22967 return mArtManagerService; 22968 } 22969 22970 private boolean userNeedsBadging(int userId) { 22971 int index = mUserNeedsBadging.indexOfKey(userId); 22972 if (index < 0) { 22973 final UserInfo userInfo; 22974 final long token = Binder.clearCallingIdentity(); 22975 try { 22976 userInfo = sUserManager.getUserInfo(userId); 22977 } finally { 22978 Binder.restoreCallingIdentity(token); 22979 } 22980 final boolean b; 22981 if (userInfo != null && userInfo.isManagedProfile()) { 22982 b = true; 22983 } else { 22984 b = false; 22985 } 22986 mUserNeedsBadging.put(userId, b); 22987 return b; 22988 } 22989 return mUserNeedsBadging.valueAt(index); 22990 } 22991 22992 @Override 22993 public KeySet getKeySetByAlias(String packageName, String alias) { 22994 if (packageName == null || alias == null) { 22995 return null; 22996 } 22997 synchronized(mPackages) { 22998 final PackageParser.Package pkg = mPackages.get(packageName); 22999 if (pkg == null) { 23000 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23001 throw new IllegalArgumentException("Unknown package: " + packageName); 23002 } 23003 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23004 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23005 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23006 throw new IllegalArgumentException("Unknown package: " + packageName); 23007 } 23008 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23009 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23010 } 23011 } 23012 23013 @Override 23014 public KeySet getSigningKeySet(String packageName) { 23015 if (packageName == null) { 23016 return null; 23017 } 23018 synchronized(mPackages) { 23019 final int callingUid = Binder.getCallingUid(); 23020 final int callingUserId = UserHandle.getUserId(callingUid); 23021 final PackageParser.Package pkg = mPackages.get(packageName); 23022 if (pkg == null) { 23023 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23024 throw new IllegalArgumentException("Unknown package: " + packageName); 23025 } 23026 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23027 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23028 // filter and pretend the package doesn't exist 23029 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23030 + ", uid:" + callingUid); 23031 throw new IllegalArgumentException("Unknown package: " + packageName); 23032 } 23033 if (pkg.applicationInfo.uid != callingUid 23034 && Process.SYSTEM_UID != callingUid) { 23035 throw new SecurityException("May not access signing KeySet of other apps."); 23036 } 23037 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23038 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23039 } 23040 } 23041 23042 @Override 23043 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23044 final int callingUid = Binder.getCallingUid(); 23045 if (getInstantAppPackageName(callingUid) != null) { 23046 return false; 23047 } 23048 if (packageName == null || ks == null) { 23049 return false; 23050 } 23051 synchronized(mPackages) { 23052 final PackageParser.Package pkg = mPackages.get(packageName); 23053 if (pkg == null 23054 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23055 UserHandle.getUserId(callingUid))) { 23056 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23057 throw new IllegalArgumentException("Unknown package: " + packageName); 23058 } 23059 IBinder ksh = ks.getToken(); 23060 if (ksh instanceof KeySetHandle) { 23061 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23062 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23063 } 23064 return false; 23065 } 23066 } 23067 23068 @Override 23069 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23070 final int callingUid = Binder.getCallingUid(); 23071 if (getInstantAppPackageName(callingUid) != null) { 23072 return false; 23073 } 23074 if (packageName == null || ks == null) { 23075 return false; 23076 } 23077 synchronized(mPackages) { 23078 final PackageParser.Package pkg = mPackages.get(packageName); 23079 if (pkg == null 23080 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23081 UserHandle.getUserId(callingUid))) { 23082 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23083 throw new IllegalArgumentException("Unknown package: " + packageName); 23084 } 23085 IBinder ksh = ks.getToken(); 23086 if (ksh instanceof KeySetHandle) { 23087 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23088 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23089 } 23090 return false; 23091 } 23092 } 23093 23094 private void deletePackageIfUnusedLPr(final String packageName) { 23095 PackageSetting ps = mSettings.mPackages.get(packageName); 23096 if (ps == null) { 23097 return; 23098 } 23099 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23100 // TODO Implement atomic delete if package is unused 23101 // It is currently possible that the package will be deleted even if it is installed 23102 // after this method returns. 23103 mHandler.post(new Runnable() { 23104 public void run() { 23105 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23106 0, PackageManager.DELETE_ALL_USERS); 23107 } 23108 }); 23109 } 23110 } 23111 23112 /** 23113 * Check and throw if the given before/after packages would be considered a 23114 * downgrade. 23115 */ 23116 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23117 throws PackageManagerException { 23118 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23119 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23120 "Update version code " + after.versionCode + " is older than current " 23121 + before.getLongVersionCode()); 23122 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23123 if (after.baseRevisionCode < before.baseRevisionCode) { 23124 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23125 "Update base revision code " + after.baseRevisionCode 23126 + " is older than current " + before.baseRevisionCode); 23127 } 23128 23129 if (!ArrayUtils.isEmpty(after.splitNames)) { 23130 for (int i = 0; i < after.splitNames.length; i++) { 23131 final String splitName = after.splitNames[i]; 23132 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23133 if (j != -1) { 23134 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23135 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23136 "Update split " + splitName + " revision code " 23137 + after.splitRevisionCodes[i] + " is older than current " 23138 + before.splitRevisionCodes[j]); 23139 } 23140 } 23141 } 23142 } 23143 } 23144 } 23145 23146 private static class MoveCallbacks extends Handler { 23147 private static final int MSG_CREATED = 1; 23148 private static final int MSG_STATUS_CHANGED = 2; 23149 23150 private final RemoteCallbackList<IPackageMoveObserver> 23151 mCallbacks = new RemoteCallbackList<>(); 23152 23153 private final SparseIntArray mLastStatus = new SparseIntArray(); 23154 23155 public MoveCallbacks(Looper looper) { 23156 super(looper); 23157 } 23158 23159 public void register(IPackageMoveObserver callback) { 23160 mCallbacks.register(callback); 23161 } 23162 23163 public void unregister(IPackageMoveObserver callback) { 23164 mCallbacks.unregister(callback); 23165 } 23166 23167 @Override 23168 public void handleMessage(Message msg) { 23169 final SomeArgs args = (SomeArgs) msg.obj; 23170 final int n = mCallbacks.beginBroadcast(); 23171 for (int i = 0; i < n; i++) { 23172 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23173 try { 23174 invokeCallback(callback, msg.what, args); 23175 } catch (RemoteException ignored) { 23176 } 23177 } 23178 mCallbacks.finishBroadcast(); 23179 args.recycle(); 23180 } 23181 23182 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23183 throws RemoteException { 23184 switch (what) { 23185 case MSG_CREATED: { 23186 callback.onCreated(args.argi1, (Bundle) args.arg2); 23187 break; 23188 } 23189 case MSG_STATUS_CHANGED: { 23190 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23191 break; 23192 } 23193 } 23194 } 23195 23196 private void notifyCreated(int moveId, Bundle extras) { 23197 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23198 23199 final SomeArgs args = SomeArgs.obtain(); 23200 args.argi1 = moveId; 23201 args.arg2 = extras; 23202 obtainMessage(MSG_CREATED, args).sendToTarget(); 23203 } 23204 23205 private void notifyStatusChanged(int moveId, int status) { 23206 notifyStatusChanged(moveId, status, -1); 23207 } 23208 23209 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23210 Slog.v(TAG, "Move " + moveId + " status " + status); 23211 23212 final SomeArgs args = SomeArgs.obtain(); 23213 args.argi1 = moveId; 23214 args.argi2 = status; 23215 args.arg3 = estMillis; 23216 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23217 23218 synchronized (mLastStatus) { 23219 mLastStatus.put(moveId, status); 23220 } 23221 } 23222 } 23223 23224 private final static class OnPermissionChangeListeners extends Handler { 23225 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23226 23227 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23228 new RemoteCallbackList<>(); 23229 23230 public OnPermissionChangeListeners(Looper looper) { 23231 super(looper); 23232 } 23233 23234 @Override 23235 public void handleMessage(Message msg) { 23236 switch (msg.what) { 23237 case MSG_ON_PERMISSIONS_CHANGED: { 23238 final int uid = msg.arg1; 23239 handleOnPermissionsChanged(uid); 23240 } break; 23241 } 23242 } 23243 23244 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23245 mPermissionListeners.register(listener); 23246 23247 } 23248 23249 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23250 mPermissionListeners.unregister(listener); 23251 } 23252 23253 public void onPermissionsChanged(int uid) { 23254 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23255 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23256 } 23257 } 23258 23259 private void handleOnPermissionsChanged(int uid) { 23260 final int count = mPermissionListeners.beginBroadcast(); 23261 try { 23262 for (int i = 0; i < count; i++) { 23263 IOnPermissionsChangeListener callback = mPermissionListeners 23264 .getBroadcastItem(i); 23265 try { 23266 callback.onPermissionsChanged(uid); 23267 } catch (RemoteException e) { 23268 Log.e(TAG, "Permission listener is dead", e); 23269 } 23270 } 23271 } finally { 23272 mPermissionListeners.finishBroadcast(); 23273 } 23274 } 23275 } 23276 23277 private class PackageManagerNative extends IPackageManagerNative.Stub { 23278 @Override 23279 public String[] getNamesForUids(int[] uids) throws RemoteException { 23280 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23281 // massage results so they can be parsed by the native binder 23282 for (int i = results.length - 1; i >= 0; --i) { 23283 if (results[i] == null) { 23284 results[i] = ""; 23285 } 23286 } 23287 return results; 23288 } 23289 23290 // NB: this differentiates between preloads and sideloads 23291 @Override 23292 public String getInstallerForPackage(String packageName) throws RemoteException { 23293 final String installerName = getInstallerPackageName(packageName); 23294 if (!TextUtils.isEmpty(installerName)) { 23295 return installerName; 23296 } 23297 // differentiate between preload and sideload 23298 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23299 ApplicationInfo appInfo = getApplicationInfo(packageName, 23300 /*flags*/ 0, 23301 /*userId*/ callingUser); 23302 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23303 return "preload"; 23304 } 23305 return ""; 23306 } 23307 23308 @Override 23309 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23310 try { 23311 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23312 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23313 if (pInfo != null) { 23314 return pInfo.getLongVersionCode(); 23315 } 23316 } catch (Exception e) { 23317 } 23318 return 0; 23319 } 23320 } 23321 23322 private class PackageManagerInternalImpl extends PackageManagerInternal { 23323 @Override 23324 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23325 int flagValues, int userId) { 23326 PackageManagerService.this.updatePermissionFlags( 23327 permName, packageName, flagMask, flagValues, userId); 23328 } 23329 23330 @Override 23331 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23332 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23333 } 23334 23335 @Override 23336 public boolean isInstantApp(String packageName, int userId) { 23337 return PackageManagerService.this.isInstantApp(packageName, userId); 23338 } 23339 23340 @Override 23341 public String getInstantAppPackageName(int uid) { 23342 return PackageManagerService.this.getInstantAppPackageName(uid); 23343 } 23344 23345 @Override 23346 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23347 synchronized (mPackages) { 23348 return PackageManagerService.this.filterAppAccessLPr( 23349 (PackageSetting) pkg.mExtras, callingUid, userId); 23350 } 23351 } 23352 23353 @Override 23354 public PackageParser.Package getPackage(String packageName) { 23355 synchronized (mPackages) { 23356 packageName = resolveInternalPackageNameLPr( 23357 packageName, PackageManager.VERSION_CODE_HIGHEST); 23358 return mPackages.get(packageName); 23359 } 23360 } 23361 23362 @Override 23363 public PackageList getPackageList(PackageListObserver observer) { 23364 synchronized (mPackages) { 23365 final int N = mPackages.size(); 23366 final ArrayList<String> list = new ArrayList<>(N); 23367 for (int i = 0; i < N; i++) { 23368 list.add(mPackages.keyAt(i)); 23369 } 23370 final PackageList packageList = new PackageList(list, observer); 23371 if (observer != null) { 23372 mPackageListObservers.add(packageList); 23373 } 23374 return packageList; 23375 } 23376 } 23377 23378 @Override 23379 public void removePackageListObserver(PackageListObserver observer) { 23380 synchronized (mPackages) { 23381 mPackageListObservers.remove(observer); 23382 } 23383 } 23384 23385 @Override 23386 public PackageParser.Package getDisabledPackage(String packageName) { 23387 synchronized (mPackages) { 23388 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23389 return (ps != null) ? ps.pkg : null; 23390 } 23391 } 23392 23393 @Override 23394 public String getKnownPackageName(int knownPackage, int userId) { 23395 switch(knownPackage) { 23396 case PackageManagerInternal.PACKAGE_BROWSER: 23397 return getDefaultBrowserPackageName(userId); 23398 case PackageManagerInternal.PACKAGE_INSTALLER: 23399 return mRequiredInstallerPackage; 23400 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23401 return mSetupWizardPackage; 23402 case PackageManagerInternal.PACKAGE_SYSTEM: 23403 return "android"; 23404 case PackageManagerInternal.PACKAGE_VERIFIER: 23405 return mRequiredVerifierPackage; 23406 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23407 return mSystemTextClassifierPackage; 23408 } 23409 return null; 23410 } 23411 23412 @Override 23413 public boolean isResolveActivityComponent(ComponentInfo component) { 23414 return mResolveActivity.packageName.equals(component.packageName) 23415 && mResolveActivity.name.equals(component.name); 23416 } 23417 23418 @Override 23419 public void setLocationPackagesProvider(PackagesProvider provider) { 23420 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23421 } 23422 23423 @Override 23424 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23425 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23426 } 23427 23428 @Override 23429 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23430 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23431 } 23432 23433 @Override 23434 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23435 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23436 } 23437 23438 @Override 23439 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23440 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23441 } 23442 23443 @Override 23444 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23445 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23446 } 23447 23448 @Override 23449 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23450 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23451 } 23452 23453 @Override 23454 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23455 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23456 } 23457 23458 @Override 23459 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23460 synchronized (mPackages) { 23461 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23462 } 23463 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23464 } 23465 23466 @Override 23467 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23468 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23469 packageName, userId); 23470 } 23471 23472 @Override 23473 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23474 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23475 packageName, userId); 23476 } 23477 23478 @Override 23479 public void setKeepUninstalledPackages(final List<String> packageList) { 23480 Preconditions.checkNotNull(packageList); 23481 List<String> removedFromList = null; 23482 synchronized (mPackages) { 23483 if (mKeepUninstalledPackages != null) { 23484 final int packagesCount = mKeepUninstalledPackages.size(); 23485 for (int i = 0; i < packagesCount; i++) { 23486 String oldPackage = mKeepUninstalledPackages.get(i); 23487 if (packageList != null && packageList.contains(oldPackage)) { 23488 continue; 23489 } 23490 if (removedFromList == null) { 23491 removedFromList = new ArrayList<>(); 23492 } 23493 removedFromList.add(oldPackage); 23494 } 23495 } 23496 mKeepUninstalledPackages = new ArrayList<>(packageList); 23497 if (removedFromList != null) { 23498 final int removedCount = removedFromList.size(); 23499 for (int i = 0; i < removedCount; i++) { 23500 deletePackageIfUnusedLPr(removedFromList.get(i)); 23501 } 23502 } 23503 } 23504 } 23505 23506 @Override 23507 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23508 synchronized (mPackages) { 23509 return mPermissionManager.isPermissionsReviewRequired( 23510 mPackages.get(packageName), userId); 23511 } 23512 } 23513 23514 @Override 23515 public PackageInfo getPackageInfo( 23516 String packageName, int flags, int filterCallingUid, int userId) { 23517 return PackageManagerService.this 23518 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23519 flags, filterCallingUid, userId); 23520 } 23521 23522 @Override 23523 public int getPackageUid(String packageName, int flags, int userId) { 23524 return PackageManagerService.this 23525 .getPackageUid(packageName, flags, userId); 23526 } 23527 23528 @Override 23529 public ApplicationInfo getApplicationInfo( 23530 String packageName, int flags, int filterCallingUid, int userId) { 23531 return PackageManagerService.this 23532 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23533 } 23534 23535 @Override 23536 public ActivityInfo getActivityInfo( 23537 ComponentName component, int flags, int filterCallingUid, int userId) { 23538 return PackageManagerService.this 23539 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23540 } 23541 23542 @Override 23543 public List<ResolveInfo> queryIntentActivities( 23544 Intent intent, int flags, int filterCallingUid, int userId) { 23545 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23546 return PackageManagerService.this 23547 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23548 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23549 } 23550 23551 @Override 23552 public List<ResolveInfo> queryIntentServices( 23553 Intent intent, int flags, int callingUid, int userId) { 23554 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23555 return PackageManagerService.this 23556 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23557 false); 23558 } 23559 23560 @Override 23561 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23562 int userId) { 23563 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23564 } 23565 23566 @Override 23567 public ComponentName getDefaultHomeActivity(int userId) { 23568 return PackageManagerService.this.getDefaultHomeActivity(userId); 23569 } 23570 23571 @Override 23572 public void setDeviceAndProfileOwnerPackages( 23573 int deviceOwnerUserId, String deviceOwnerPackage, 23574 SparseArray<String> profileOwnerPackages) { 23575 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23576 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23577 } 23578 23579 @Override 23580 public boolean isPackageDataProtected(int userId, String packageName) { 23581 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23582 } 23583 23584 @Override 23585 public boolean isPackageEphemeral(int userId, String packageName) { 23586 synchronized (mPackages) { 23587 final PackageSetting ps = mSettings.mPackages.get(packageName); 23588 return ps != null ? ps.getInstantApp(userId) : false; 23589 } 23590 } 23591 23592 @Override 23593 public boolean wasPackageEverLaunched(String packageName, int userId) { 23594 synchronized (mPackages) { 23595 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23596 } 23597 } 23598 23599 @Override 23600 public void grantRuntimePermission(String packageName, String permName, int userId, 23601 boolean overridePolicy) { 23602 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23603 permName, packageName, overridePolicy, getCallingUid(), userId, 23604 mPermissionCallback); 23605 } 23606 23607 @Override 23608 public void revokeRuntimePermission(String packageName, String permName, int userId, 23609 boolean overridePolicy) { 23610 mPermissionManager.revokeRuntimePermission( 23611 permName, packageName, overridePolicy, getCallingUid(), userId, 23612 mPermissionCallback); 23613 } 23614 23615 @Override 23616 public String getNameForUid(int uid) { 23617 return PackageManagerService.this.getNameForUid(uid); 23618 } 23619 23620 @Override 23621 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23622 Intent origIntent, String resolvedType, String callingPackage, 23623 Bundle verificationBundle, int userId) { 23624 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23625 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23626 userId); 23627 } 23628 23629 @Override 23630 public void grantEphemeralAccess(int userId, Intent intent, 23631 int targetAppId, int ephemeralAppId) { 23632 synchronized (mPackages) { 23633 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23634 targetAppId, ephemeralAppId); 23635 } 23636 } 23637 23638 @Override 23639 public boolean isInstantAppInstallerComponent(ComponentName component) { 23640 synchronized (mPackages) { 23641 return mInstantAppInstallerActivity != null 23642 && mInstantAppInstallerActivity.getComponentName().equals(component); 23643 } 23644 } 23645 23646 @Override 23647 public void pruneInstantApps() { 23648 mInstantAppRegistry.pruneInstantApps(); 23649 } 23650 23651 @Override 23652 public String getSetupWizardPackageName() { 23653 return mSetupWizardPackage; 23654 } 23655 23656 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23657 if (policy != null) { 23658 mExternalSourcesPolicy = policy; 23659 } 23660 } 23661 23662 @Override 23663 public boolean isPackagePersistent(String packageName) { 23664 synchronized (mPackages) { 23665 PackageParser.Package pkg = mPackages.get(packageName); 23666 return pkg != null 23667 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23668 | ApplicationInfo.FLAG_PERSISTENT)) == 23669 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23670 : false; 23671 } 23672 } 23673 23674 @Override 23675 public boolean isLegacySystemApp(Package pkg) { 23676 synchronized (mPackages) { 23677 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23678 return mPromoteSystemApps 23679 && ps.isSystem() 23680 && mExistingSystemPackages.contains(ps.name); 23681 } 23682 } 23683 23684 @Override 23685 public List<PackageInfo> getOverlayPackages(int userId) { 23686 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23687 synchronized (mPackages) { 23688 for (PackageParser.Package p : mPackages.values()) { 23689 if (p.mOverlayTarget != null) { 23690 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23691 if (pkg != null) { 23692 overlayPackages.add(pkg); 23693 } 23694 } 23695 } 23696 } 23697 return overlayPackages; 23698 } 23699 23700 @Override 23701 public List<String> getTargetPackageNames(int userId) { 23702 List<String> targetPackages = new ArrayList<>(); 23703 synchronized (mPackages) { 23704 for (PackageParser.Package p : mPackages.values()) { 23705 if (p.mOverlayTarget == null) { 23706 targetPackages.add(p.packageName); 23707 } 23708 } 23709 } 23710 return targetPackages; 23711 } 23712 23713 @Override 23714 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23715 @Nullable List<String> overlayPackageNames) { 23716 synchronized (mPackages) { 23717 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23718 Slog.e(TAG, "failed to find package " + targetPackageName); 23719 return false; 23720 } 23721 ArrayList<String> overlayPaths = null; 23722 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23723 final int N = overlayPackageNames.size(); 23724 overlayPaths = new ArrayList<>(N); 23725 for (int i = 0; i < N; i++) { 23726 final String packageName = overlayPackageNames.get(i); 23727 final PackageParser.Package pkg = mPackages.get(packageName); 23728 if (pkg == null) { 23729 Slog.e(TAG, "failed to find package " + packageName); 23730 return false; 23731 } 23732 overlayPaths.add(pkg.baseCodePath); 23733 } 23734 } 23735 23736 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23737 ps.setOverlayPaths(overlayPaths, userId); 23738 return true; 23739 } 23740 } 23741 23742 @Override 23743 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23744 int flags, int userId, boolean resolveForStart) { 23745 return resolveIntentInternal( 23746 intent, resolvedType, flags, userId, resolveForStart); 23747 } 23748 23749 @Override 23750 public ResolveInfo resolveService(Intent intent, String resolvedType, 23751 int flags, int userId, int callingUid) { 23752 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23753 } 23754 23755 @Override 23756 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23757 return PackageManagerService.this.resolveContentProviderInternal( 23758 name, flags, userId); 23759 } 23760 23761 @Override 23762 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23763 synchronized (mPackages) { 23764 mIsolatedOwners.put(isolatedUid, ownerUid); 23765 } 23766 } 23767 23768 @Override 23769 public void removeIsolatedUid(int isolatedUid) { 23770 synchronized (mPackages) { 23771 mIsolatedOwners.delete(isolatedUid); 23772 } 23773 } 23774 23775 @Override 23776 public int getUidTargetSdkVersion(int uid) { 23777 synchronized (mPackages) { 23778 return getUidTargetSdkVersionLockedLPr(uid); 23779 } 23780 } 23781 23782 @Override 23783 public int getPackageTargetSdkVersion(String packageName) { 23784 synchronized (mPackages) { 23785 return getPackageTargetSdkVersionLockedLPr(packageName); 23786 } 23787 } 23788 23789 @Override 23790 public boolean canAccessInstantApps(int callingUid, int userId) { 23791 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23792 } 23793 23794 @Override 23795 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23796 synchronized (mPackages) { 23797 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23798 } 23799 } 23800 23801 @Override 23802 public void notifyPackageUse(String packageName, int reason) { 23803 synchronized (mPackages) { 23804 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23805 } 23806 } 23807 } 23808 23809 @Override 23810 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23811 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23812 synchronized (mPackages) { 23813 final long identity = Binder.clearCallingIdentity(); 23814 try { 23815 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23816 packageNames, userId); 23817 } finally { 23818 Binder.restoreCallingIdentity(identity); 23819 } 23820 } 23821 } 23822 23823 @Override 23824 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23825 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23826 synchronized (mPackages) { 23827 final long identity = Binder.clearCallingIdentity(); 23828 try { 23829 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23830 packageNames, userId); 23831 } finally { 23832 Binder.restoreCallingIdentity(identity); 23833 } 23834 } 23835 } 23836 23837 private static void enforceSystemOrPhoneCaller(String tag) { 23838 int callingUid = Binder.getCallingUid(); 23839 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23840 throw new SecurityException( 23841 "Cannot call " + tag + " from UID " + callingUid); 23842 } 23843 } 23844 23845 boolean isHistoricalPackageUsageAvailable() { 23846 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23847 } 23848 23849 /** 23850 * Return a <b>copy</b> of the collection of packages known to the package manager. 23851 * @return A copy of the values of mPackages. 23852 */ 23853 Collection<PackageParser.Package> getPackages() { 23854 synchronized (mPackages) { 23855 return new ArrayList<>(mPackages.values()); 23856 } 23857 } 23858 23859 /** 23860 * Logs process start information (including base APK hash) to the security log. 23861 * @hide 23862 */ 23863 @Override 23864 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23865 String apkFile, int pid) { 23866 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23867 return; 23868 } 23869 if (!SecurityLog.isLoggingEnabled()) { 23870 return; 23871 } 23872 Bundle data = new Bundle(); 23873 data.putLong("startTimestamp", System.currentTimeMillis()); 23874 data.putString("processName", processName); 23875 data.putInt("uid", uid); 23876 data.putString("seinfo", seinfo); 23877 data.putString("apkFile", apkFile); 23878 data.putInt("pid", pid); 23879 Message msg = mProcessLoggingHandler.obtainMessage( 23880 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23881 msg.setData(data); 23882 mProcessLoggingHandler.sendMessage(msg); 23883 } 23884 23885 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23886 return mCompilerStats.getPackageStats(pkgName); 23887 } 23888 23889 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23890 return getOrCreateCompilerPackageStats(pkg.packageName); 23891 } 23892 23893 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23894 return mCompilerStats.getOrCreatePackageStats(pkgName); 23895 } 23896 23897 public void deleteCompilerPackageStats(String pkgName) { 23898 mCompilerStats.deletePackageStats(pkgName); 23899 } 23900 23901 @Override 23902 public int getInstallReason(String packageName, int userId) { 23903 final int callingUid = Binder.getCallingUid(); 23904 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23905 true /* requireFullPermission */, false /* checkShell */, 23906 "get install reason"); 23907 synchronized (mPackages) { 23908 final PackageSetting ps = mSettings.mPackages.get(packageName); 23909 if (filterAppAccessLPr(ps, callingUid, userId)) { 23910 return PackageManager.INSTALL_REASON_UNKNOWN; 23911 } 23912 if (ps != null) { 23913 return ps.getInstallReason(userId); 23914 } 23915 } 23916 return PackageManager.INSTALL_REASON_UNKNOWN; 23917 } 23918 23919 @Override 23920 public boolean canRequestPackageInstalls(String packageName, int userId) { 23921 return canRequestPackageInstallsInternal(packageName, 0, userId, 23922 true /* throwIfPermNotDeclared*/); 23923 } 23924 23925 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23926 boolean throwIfPermNotDeclared) { 23927 int callingUid = Binder.getCallingUid(); 23928 int uid = getPackageUid(packageName, 0, userId); 23929 if (callingUid != uid && callingUid != Process.ROOT_UID 23930 && callingUid != Process.SYSTEM_UID) { 23931 throw new SecurityException( 23932 "Caller uid " + callingUid + " does not own package " + packageName); 23933 } 23934 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23935 if (info == null) { 23936 return false; 23937 } 23938 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23939 return false; 23940 } 23941 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23942 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23943 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23944 if (throwIfPermNotDeclared) { 23945 throw new SecurityException("Need to declare " + appOpPermission 23946 + " to call this api"); 23947 } else { 23948 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23949 return false; 23950 } 23951 } 23952 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23953 return false; 23954 } 23955 if (mExternalSourcesPolicy != null) { 23956 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23957 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23958 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23959 } 23960 } 23961 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23962 } 23963 23964 @Override 23965 public ComponentName getInstantAppResolverSettingsComponent() { 23966 return mInstantAppResolverSettingsComponent; 23967 } 23968 23969 @Override 23970 public ComponentName getInstantAppInstallerComponent() { 23971 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23972 return null; 23973 } 23974 return mInstantAppInstallerActivity == null 23975 ? null : mInstantAppInstallerActivity.getComponentName(); 23976 } 23977 23978 @Override 23979 public String getInstantAppAndroidId(String packageName, int userId) { 23980 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23981 "getInstantAppAndroidId"); 23982 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23983 true /* requireFullPermission */, false /* checkShell */, 23984 "getInstantAppAndroidId"); 23985 // Make sure the target is an Instant App. 23986 if (!isInstantApp(packageName, userId)) { 23987 return null; 23988 } 23989 synchronized (mPackages) { 23990 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23991 } 23992 } 23993 23994 boolean canHaveOatDir(String packageName) { 23995 synchronized (mPackages) { 23996 PackageParser.Package p = mPackages.get(packageName); 23997 if (p == null) { 23998 return false; 23999 } 24000 return p.canHaveOatDir(); 24001 } 24002 } 24003 24004 private String getOatDir(PackageParser.Package pkg) { 24005 if (!pkg.canHaveOatDir()) { 24006 return null; 24007 } 24008 File codePath = new File(pkg.codePath); 24009 if (codePath.isDirectory()) { 24010 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24011 } 24012 return null; 24013 } 24014 24015 void deleteOatArtifactsOfPackage(String packageName) { 24016 final String[] instructionSets; 24017 final List<String> codePaths; 24018 final String oatDir; 24019 final PackageParser.Package pkg; 24020 synchronized (mPackages) { 24021 pkg = mPackages.get(packageName); 24022 } 24023 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24024 codePaths = pkg.getAllCodePaths(); 24025 oatDir = getOatDir(pkg); 24026 24027 for (String codePath : codePaths) { 24028 for (String isa : instructionSets) { 24029 try { 24030 mInstaller.deleteOdex(codePath, isa, oatDir); 24031 } catch (InstallerException e) { 24032 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24033 } 24034 } 24035 } 24036 } 24037 24038 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24039 Set<String> unusedPackages = new HashSet<>(); 24040 long currentTimeInMillis = System.currentTimeMillis(); 24041 synchronized (mPackages) { 24042 for (PackageParser.Package pkg : mPackages.values()) { 24043 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24044 if (ps == null) { 24045 continue; 24046 } 24047 PackageDexUsage.PackageUseInfo packageUseInfo = 24048 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24049 if (PackageManagerServiceUtils 24050 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24051 downgradeTimeThresholdMillis, packageUseInfo, 24052 pkg.getLatestPackageUseTimeInMills(), 24053 pkg.getLatestForegroundPackageUseTimeInMills())) { 24054 unusedPackages.add(pkg.packageName); 24055 } 24056 } 24057 } 24058 return unusedPackages; 24059 } 24060 24061 @Override 24062 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24063 int userId) { 24064 final int callingUid = Binder.getCallingUid(); 24065 final int callingAppId = UserHandle.getAppId(callingUid); 24066 24067 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24068 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24069 24070 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24071 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24072 throw new SecurityException("Caller must have the " 24073 + SET_HARMFUL_APP_WARNINGS + " permission."); 24074 } 24075 24076 synchronized(mPackages) { 24077 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24078 scheduleWritePackageRestrictionsLocked(userId); 24079 } 24080 } 24081 24082 @Nullable 24083 @Override 24084 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24085 final int callingUid = Binder.getCallingUid(); 24086 final int callingAppId = UserHandle.getAppId(callingUid); 24087 24088 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24089 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24090 24091 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24092 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24093 throw new SecurityException("Caller must have the " 24094 + SET_HARMFUL_APP_WARNINGS + " permission."); 24095 } 24096 24097 synchronized(mPackages) { 24098 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24099 } 24100 } 24101} 24102 24103interface PackageSender { 24104 /** 24105 * @param userIds User IDs where the action occurred on a full application 24106 * @param instantUserIds User IDs where the action occurred on an instant application 24107 */ 24108 void sendPackageBroadcast(final String action, final String pkg, 24109 final Bundle extras, final int flags, final String targetPkg, 24110 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24111 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24112 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24113 void notifyPackageAdded(String packageName); 24114 void notifyPackageRemoved(String packageName); 24115} 24116