PackageManagerService.java revision 244ef2b030e9f0c8d6780be11f8e18003dba2777
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.signingDetailsHasCertificate; 112import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate; 113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 117 118import android.Manifest; 119import android.annotation.IntDef; 120import android.annotation.NonNull; 121import android.annotation.Nullable; 122import android.app.ActivityManager; 123import android.app.ActivityManagerInternal; 124import android.app.AppOpsManager; 125import android.app.IActivityManager; 126import android.app.ResourcesManager; 127import android.app.admin.IDevicePolicyManager; 128import android.app.admin.SecurityLog; 129import android.app.backup.IBackupManager; 130import android.content.BroadcastReceiver; 131import android.content.ComponentName; 132import android.content.ContentResolver; 133import android.content.Context; 134import android.content.IIntentReceiver; 135import android.content.Intent; 136import android.content.IntentFilter; 137import android.content.IntentSender; 138import android.content.IntentSender.SendIntentException; 139import android.content.ServiceConnection; 140import android.content.pm.ActivityInfo; 141import android.content.pm.ApplicationInfo; 142import android.content.pm.AppsQueryHelper; 143import android.content.pm.AuxiliaryResolveInfo; 144import android.content.pm.ChangedPackages; 145import android.content.pm.ComponentInfo; 146import android.content.pm.FallbackCategoryProvider; 147import android.content.pm.FeatureInfo; 148import android.content.pm.IDexModuleRegisterCallback; 149import android.content.pm.IOnPermissionsChangeListener; 150import android.content.pm.IPackageDataObserver; 151import android.content.pm.IPackageDeleteObserver; 152import android.content.pm.IPackageDeleteObserver2; 153import android.content.pm.IPackageInstallObserver2; 154import android.content.pm.IPackageInstaller; 155import android.content.pm.IPackageManager; 156import android.content.pm.IPackageManagerNative; 157import android.content.pm.IPackageMoveObserver; 158import android.content.pm.IPackageStatsObserver; 159import android.content.pm.InstantAppInfo; 160import android.content.pm.InstantAppRequest; 161import android.content.pm.InstantAppResolveInfo; 162import android.content.pm.InstrumentationInfo; 163import android.content.pm.IntentFilterVerificationInfo; 164import android.content.pm.KeySet; 165import android.content.pm.PackageCleanItem; 166import android.content.pm.PackageInfo; 167import android.content.pm.PackageInfoLite; 168import android.content.pm.PackageInstaller; 169import android.content.pm.PackageList; 170import android.content.pm.PackageManager; 171import android.content.pm.PackageManagerInternal; 172import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 173import android.content.pm.PackageManagerInternal.PackageListObserver; 174import android.content.pm.PackageParser; 175import android.content.pm.PackageParser.ActivityIntentInfo; 176import android.content.pm.PackageParser.Package; 177import android.content.pm.PackageParser.PackageLite; 178import android.content.pm.PackageParser.PackageParserException; 179import android.content.pm.PackageParser.ParseFlags; 180import android.content.pm.PackageParser.ServiceIntentInfo; 181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 182import android.content.pm.PackageStats; 183import android.content.pm.PackageUserState; 184import android.content.pm.ParceledListSlice; 185import android.content.pm.PermissionGroupInfo; 186import android.content.pm.PermissionInfo; 187import android.content.pm.ProviderInfo; 188import android.content.pm.ResolveInfo; 189import android.content.pm.ServiceInfo; 190import android.content.pm.SharedLibraryInfo; 191import android.content.pm.Signature; 192import android.content.pm.UserInfo; 193import android.content.pm.VerifierDeviceIdentity; 194import android.content.pm.VerifierInfo; 195import android.content.pm.VersionedPackage; 196import android.content.pm.dex.ArtManager; 197import android.content.pm.dex.DexMetadataHelper; 198import android.content.pm.dex.IArtManager; 199import android.content.res.Resources; 200import android.database.ContentObserver; 201import android.graphics.Bitmap; 202import android.hardware.display.DisplayManager; 203import android.net.Uri; 204import android.os.Binder; 205import android.os.Build; 206import android.os.Bundle; 207import android.os.Debug; 208import android.os.Environment; 209import android.os.Environment.UserEnvironment; 210import android.os.FileUtils; 211import android.os.Handler; 212import android.os.IBinder; 213import android.os.Looper; 214import android.os.Message; 215import android.os.Parcel; 216import android.os.ParcelFileDescriptor; 217import android.os.PatternMatcher; 218import android.os.Process; 219import android.os.RemoteCallbackList; 220import android.os.RemoteException; 221import android.os.ResultReceiver; 222import android.os.SELinux; 223import android.os.ServiceManager; 224import android.os.ShellCallback; 225import android.os.SystemClock; 226import android.os.SystemProperties; 227import android.os.Trace; 228import android.os.UserHandle; 229import android.os.UserManager; 230import android.os.UserManagerInternal; 231import android.os.storage.IStorageManager; 232import android.os.storage.StorageEventListener; 233import android.os.storage.StorageManager; 234import android.os.storage.StorageManagerInternal; 235import android.os.storage.VolumeInfo; 236import android.os.storage.VolumeRecord; 237import android.provider.Settings.Global; 238import android.provider.Settings.Secure; 239import android.security.KeyStore; 240import android.security.SystemKeyStore; 241import android.service.pm.PackageServiceDumpProto; 242import android.system.ErrnoException; 243import android.system.Os; 244import android.text.TextUtils; 245import android.text.format.DateUtils; 246import android.util.ArrayMap; 247import android.util.ArraySet; 248import android.util.Base64; 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_EPHEMERAL = 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 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 558 559 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 } 587 588 /** 589 * The set of all protected actions [i.e. those actions for which a high priority 590 * intent filter is disallowed]. 591 */ 592 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 593 static { 594 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 595 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 596 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 597 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 598 } 599 600 // Compilation reasons. 601 public static final int REASON_FIRST_BOOT = 0; 602 public static final int REASON_BOOT = 1; 603 public static final int REASON_INSTALL = 2; 604 public static final int REASON_BACKGROUND_DEXOPT = 3; 605 public static final int REASON_AB_OTA = 4; 606 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 607 public static final int REASON_SHARED = 6; 608 609 public static final int REASON_LAST = REASON_SHARED; 610 611 /** 612 * Version number for the package parser cache. Increment this whenever the format or 613 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 614 */ 615 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 616 617 /** 618 * Whether the package parser cache is enabled. 619 */ 620 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 621 622 /** 623 * Permissions required in order to receive instant application lifecycle broadcasts. 624 */ 625 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 626 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 627 628 final ServiceThread mHandlerThread; 629 630 final PackageHandler mHandler; 631 632 private final ProcessLoggingHandler mProcessLoggingHandler; 633 634 /** 635 * Messages for {@link #mHandler} that need to wait for system ready before 636 * being dispatched. 637 */ 638 private ArrayList<Message> mPostSystemReadyMessages; 639 640 final int mSdkVersion = Build.VERSION.SDK_INT; 641 642 final Context mContext; 643 final boolean mFactoryTest; 644 final boolean mOnlyCore; 645 final DisplayMetrics mMetrics; 646 final int mDefParseFlags; 647 final String[] mSeparateProcesses; 648 final boolean mIsUpgrade; 649 final boolean mIsPreNUpgrade; 650 final boolean mIsPreNMR1Upgrade; 651 652 // Have we told the Activity Manager to whitelist the default container service by uid yet? 653 @GuardedBy("mPackages") 654 boolean mDefaultContainerWhitelisted = false; 655 656 @GuardedBy("mPackages") 657 private boolean mDexOptDialogShown; 658 659 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 660 // LOCK HELD. Can be called with mInstallLock held. 661 @GuardedBy("mInstallLock") 662 final Installer mInstaller; 663 664 /** Directory where installed applications are stored */ 665 private static final File sAppInstallDir = 666 new File(Environment.getDataDirectory(), "app"); 667 /** Directory where installed application's 32-bit native libraries are copied. */ 668 private static final File sAppLib32InstallDir = 669 new File(Environment.getDataDirectory(), "app-lib"); 670 /** Directory where code and non-resource assets of forward-locked applications are stored */ 671 private static final File sDrmAppPrivateInstallDir = 672 new File(Environment.getDataDirectory(), "app-private"); 673 674 // ---------------------------------------------------------------- 675 676 // Lock for state used when installing and doing other long running 677 // operations. Methods that must be called with this lock held have 678 // the suffix "LI". 679 final Object mInstallLock = new Object(); 680 681 // ---------------------------------------------------------------- 682 683 // Keys are String (package name), values are Package. This also serves 684 // as the lock for the global state. Methods that must be called with 685 // this lock held have the prefix "LP". 686 @GuardedBy("mPackages") 687 final ArrayMap<String, PackageParser.Package> mPackages = 688 new ArrayMap<String, PackageParser.Package>(); 689 690 final ArrayMap<String, Set<String>> mKnownCodebase = 691 new ArrayMap<String, Set<String>>(); 692 693 // Keys are isolated uids and values are the uid of the application 694 // that created the isolated proccess. 695 @GuardedBy("mPackages") 696 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 697 698 /** 699 * Tracks new system packages [received in an OTA] that we expect to 700 * find updated user-installed versions. Keys are package name, values 701 * are package location. 702 */ 703 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 704 /** 705 * Tracks high priority intent filters for protected actions. During boot, certain 706 * filter actions are protected and should never be allowed to have a high priority 707 * intent filter for them. However, there is one, and only one exception -- the 708 * setup wizard. It must be able to define a high priority intent filter for these 709 * actions to ensure there are no escapes from the wizard. We need to delay processing 710 * of these during boot as we need to look at all of the system packages in order 711 * to know which component is the setup wizard. 712 */ 713 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 714 /** 715 * Whether or not processing protected filters should be deferred. 716 */ 717 private boolean mDeferProtectedFilters = true; 718 719 /** 720 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 721 */ 722 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 723 /** 724 * Whether or not system app permissions should be promoted from install to runtime. 725 */ 726 boolean mPromoteSystemApps; 727 728 @GuardedBy("mPackages") 729 final Settings mSettings; 730 731 /** 732 * Set of package names that are currently "frozen", which means active 733 * surgery is being done on the code/data for that package. The platform 734 * will refuse to launch frozen packages to avoid race conditions. 735 * 736 * @see PackageFreezer 737 */ 738 @GuardedBy("mPackages") 739 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 740 741 final ProtectedPackages mProtectedPackages; 742 743 @GuardedBy("mLoadedVolumes") 744 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 745 746 boolean mFirstBoot; 747 748 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 749 750 @GuardedBy("mAvailableFeatures") 751 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 752 753 private final InstantAppRegistry mInstantAppRegistry; 754 755 @GuardedBy("mPackages") 756 int mChangedPackagesSequenceNumber; 757 /** 758 * List of changed [installed, removed or updated] packages. 759 * mapping from user id -> sequence number -> package name 760 */ 761 @GuardedBy("mPackages") 762 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 763 /** 764 * The sequence number of the last change to a package. 765 * mapping from user id -> package name -> sequence number 766 */ 767 @GuardedBy("mPackages") 768 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 769 770 @GuardedBy("mPackages") 771 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 772 773 class PackageParserCallback implements PackageParser.Callback { 774 @Override public final boolean hasFeature(String feature) { 775 return PackageManagerService.this.hasSystemFeature(feature, 0); 776 } 777 778 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 779 Collection<PackageParser.Package> allPackages, String targetPackageName) { 780 List<PackageParser.Package> overlayPackages = null; 781 for (PackageParser.Package p : allPackages) { 782 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 783 if (overlayPackages == null) { 784 overlayPackages = new ArrayList<PackageParser.Package>(); 785 } 786 overlayPackages.add(p); 787 } 788 } 789 if (overlayPackages != null) { 790 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 791 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 792 return p1.mOverlayPriority - p2.mOverlayPriority; 793 } 794 }; 795 Collections.sort(overlayPackages, cmp); 796 } 797 return overlayPackages; 798 } 799 800 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 801 String targetPackageName, String targetPath) { 802 if ("android".equals(targetPackageName)) { 803 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 804 // native AssetManager. 805 return null; 806 } 807 List<PackageParser.Package> overlayPackages = 808 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 809 if (overlayPackages == null || overlayPackages.isEmpty()) { 810 return null; 811 } 812 List<String> overlayPathList = null; 813 for (PackageParser.Package overlayPackage : overlayPackages) { 814 if (targetPath == null) { 815 if (overlayPathList == null) { 816 overlayPathList = new ArrayList<String>(); 817 } 818 overlayPathList.add(overlayPackage.baseCodePath); 819 continue; 820 } 821 822 try { 823 // Creates idmaps for system to parse correctly the Android manifest of the 824 // target package. 825 // 826 // OverlayManagerService will update each of them with a correct gid from its 827 // target package app id. 828 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 829 UserHandle.getSharedAppGid( 830 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 831 if (overlayPathList == null) { 832 overlayPathList = new ArrayList<String>(); 833 } 834 overlayPathList.add(overlayPackage.baseCodePath); 835 } catch (InstallerException e) { 836 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 837 overlayPackage.baseCodePath); 838 } 839 } 840 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 841 } 842 843 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 844 synchronized (mPackages) { 845 return getStaticOverlayPathsLocked( 846 mPackages.values(), targetPackageName, targetPath); 847 } 848 } 849 850 @Override public final String[] getOverlayApks(String targetPackageName) { 851 return getStaticOverlayPaths(targetPackageName, null); 852 } 853 854 @Override public final String[] getOverlayPaths(String targetPackageName, 855 String targetPath) { 856 return getStaticOverlayPaths(targetPackageName, targetPath); 857 } 858 } 859 860 class ParallelPackageParserCallback extends PackageParserCallback { 861 List<PackageParser.Package> mOverlayPackages = null; 862 863 void findStaticOverlayPackages() { 864 synchronized (mPackages) { 865 for (PackageParser.Package p : mPackages.values()) { 866 if (p.mOverlayIsStatic) { 867 if (mOverlayPackages == null) { 868 mOverlayPackages = new ArrayList<PackageParser.Package>(); 869 } 870 mOverlayPackages.add(p); 871 } 872 } 873 } 874 } 875 876 @Override 877 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 878 // We can trust mOverlayPackages without holding mPackages because package uninstall 879 // can't happen while running parallel parsing. 880 // Moreover holding mPackages on each parsing thread causes dead-lock. 881 return mOverlayPackages == null ? null : 882 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 883 } 884 } 885 886 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 887 final ParallelPackageParserCallback mParallelPackageParserCallback = 888 new ParallelPackageParserCallback(); 889 890 public static final class SharedLibraryEntry { 891 public final @Nullable String path; 892 public final @Nullable String apk; 893 public final @NonNull SharedLibraryInfo info; 894 895 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 896 String declaringPackageName, long declaringPackageVersionCode) { 897 path = _path; 898 apk = _apk; 899 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 900 declaringPackageName, declaringPackageVersionCode), null); 901 } 902 } 903 904 // Currently known shared libraries. 905 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 906 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 907 new ArrayMap<>(); 908 909 // All available activities, for your resolving pleasure. 910 final ActivityIntentResolver mActivities = 911 new ActivityIntentResolver(); 912 913 // All available receivers, for your resolving pleasure. 914 final ActivityIntentResolver mReceivers = 915 new ActivityIntentResolver(); 916 917 // All available services, for your resolving pleasure. 918 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 919 920 // All available providers, for your resolving pleasure. 921 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 922 923 // Mapping from provider base names (first directory in content URI codePath) 924 // to the provider information. 925 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 926 new ArrayMap<String, PackageParser.Provider>(); 927 928 // Mapping from instrumentation class names to info about them. 929 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 930 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 931 932 // Packages whose data we have transfered into another package, thus 933 // should no longer exist. 934 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 935 936 // Broadcast actions that are only available to the system. 937 @GuardedBy("mProtectedBroadcasts") 938 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 939 940 /** List of packages waiting for verification. */ 941 final SparseArray<PackageVerificationState> mPendingVerification 942 = new SparseArray<PackageVerificationState>(); 943 944 final PackageInstallerService mInstallerService; 945 946 final ArtManagerService mArtManagerService; 947 948 private final PackageDexOptimizer mPackageDexOptimizer; 949 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 950 // is used by other apps). 951 private final DexManager mDexManager; 952 953 private AtomicInteger mNextMoveId = new AtomicInteger(); 954 private final MoveCallbacks mMoveCallbacks; 955 956 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 957 958 // Cache of users who need badging. 959 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 960 961 /** Token for keys in mPendingVerification. */ 962 private int mPendingVerificationToken = 0; 963 964 volatile boolean mSystemReady; 965 volatile boolean mSafeMode; 966 volatile boolean mHasSystemUidErrors; 967 private volatile boolean mEphemeralAppsDisabled; 968 969 ApplicationInfo mAndroidApplication; 970 final ActivityInfo mResolveActivity = new ActivityInfo(); 971 final ResolveInfo mResolveInfo = new ResolveInfo(); 972 ComponentName mResolveComponentName; 973 PackageParser.Package mPlatformPackage; 974 ComponentName mCustomResolverComponentName; 975 976 boolean mResolverReplaced = false; 977 978 private final @Nullable ComponentName mIntentFilterVerifierComponent; 979 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 980 981 private int mIntentFilterVerificationToken = 0; 982 983 /** The service connection to the ephemeral resolver */ 984 final EphemeralResolverConnection mInstantAppResolverConnection; 985 /** Component used to show resolver settings for Instant Apps */ 986 final ComponentName mInstantAppResolverSettingsComponent; 987 988 /** Activity used to install instant applications */ 989 ActivityInfo mInstantAppInstallerActivity; 990 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 991 992 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 993 = new SparseArray<IntentFilterVerificationState>(); 994 995 // TODO remove this and go through mPermissonManager directly 996 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 997 private final PermissionManagerInternal mPermissionManager; 998 999 // List of packages names to keep cached, even if they are uninstalled for all users 1000 private List<String> mKeepUninstalledPackages; 1001 1002 private UserManagerInternal mUserManagerInternal; 1003 private ActivityManagerInternal mActivityManagerInternal; 1004 1005 private DeviceIdleController.LocalService mDeviceIdleController; 1006 1007 private File mCacheDir; 1008 1009 private Future<?> mPrepareAppDataFuture; 1010 1011 private static class IFVerificationParams { 1012 PackageParser.Package pkg; 1013 boolean replacing; 1014 int userId; 1015 int verifierUid; 1016 1017 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1018 int _userId, int _verifierUid) { 1019 pkg = _pkg; 1020 replacing = _replacing; 1021 userId = _userId; 1022 replacing = _replacing; 1023 verifierUid = _verifierUid; 1024 } 1025 } 1026 1027 private interface IntentFilterVerifier<T extends IntentFilter> { 1028 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1029 T filter, String packageName); 1030 void startVerifications(int userId); 1031 void receiveVerificationResponse(int verificationId); 1032 } 1033 1034 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1035 private Context mContext; 1036 private ComponentName mIntentFilterVerifierComponent; 1037 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1038 1039 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1040 mContext = context; 1041 mIntentFilterVerifierComponent = verifierComponent; 1042 } 1043 1044 private String getDefaultScheme() { 1045 return IntentFilter.SCHEME_HTTPS; 1046 } 1047 1048 @Override 1049 public void startVerifications(int userId) { 1050 // Launch verifications requests 1051 int count = mCurrentIntentFilterVerifications.size(); 1052 for (int n=0; n<count; n++) { 1053 int verificationId = mCurrentIntentFilterVerifications.get(n); 1054 final IntentFilterVerificationState ivs = 1055 mIntentFilterVerificationStates.get(verificationId); 1056 1057 String packageName = ivs.getPackageName(); 1058 1059 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1060 final int filterCount = filters.size(); 1061 ArraySet<String> domainsSet = new ArraySet<>(); 1062 for (int m=0; m<filterCount; m++) { 1063 PackageParser.ActivityIntentInfo filter = filters.get(m); 1064 domainsSet.addAll(filter.getHostsList()); 1065 } 1066 synchronized (mPackages) { 1067 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1068 packageName, domainsSet) != null) { 1069 scheduleWriteSettingsLocked(); 1070 } 1071 } 1072 sendVerificationRequest(verificationId, ivs); 1073 } 1074 mCurrentIntentFilterVerifications.clear(); 1075 } 1076 1077 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1078 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1081 verificationId); 1082 verificationIntent.putExtra( 1083 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1084 getDefaultScheme()); 1085 verificationIntent.putExtra( 1086 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1087 ivs.getHostsString()); 1088 verificationIntent.putExtra( 1089 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1090 ivs.getPackageName()); 1091 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1092 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1093 1094 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1095 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1096 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1097 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1098 1099 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1100 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1101 "Sending IntentFilter verification broadcast"); 1102 } 1103 1104 public void receiveVerificationResponse(int verificationId) { 1105 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1106 1107 final boolean verified = ivs.isVerified(); 1108 1109 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1110 final int count = filters.size(); 1111 if (DEBUG_DOMAIN_VERIFICATION) { 1112 Slog.i(TAG, "Received verification response " + verificationId 1113 + " for " + count + " filters, verified=" + verified); 1114 } 1115 for (int n=0; n<count; n++) { 1116 PackageParser.ActivityIntentInfo filter = filters.get(n); 1117 filter.setVerified(verified); 1118 1119 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1120 + " verified with result:" + verified + " and hosts:" 1121 + ivs.getHostsString()); 1122 } 1123 1124 mIntentFilterVerificationStates.remove(verificationId); 1125 1126 final String packageName = ivs.getPackageName(); 1127 IntentFilterVerificationInfo ivi = null; 1128 1129 synchronized (mPackages) { 1130 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1131 } 1132 if (ivi == null) { 1133 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1134 + verificationId + " packageName:" + packageName); 1135 return; 1136 } 1137 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1138 "Updating IntentFilterVerificationInfo for package " + packageName 1139 +" verificationId:" + verificationId); 1140 1141 synchronized (mPackages) { 1142 if (verified) { 1143 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1144 } else { 1145 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1146 } 1147 scheduleWriteSettingsLocked(); 1148 1149 final int userId = ivs.getUserId(); 1150 if (userId != UserHandle.USER_ALL) { 1151 final int userStatus = 1152 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1153 1154 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1155 boolean needUpdate = false; 1156 1157 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1158 // already been set by the User thru the Disambiguation dialog 1159 switch (userStatus) { 1160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1161 if (verified) { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1163 } else { 1164 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1165 } 1166 needUpdate = true; 1167 break; 1168 1169 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1170 if (verified) { 1171 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1172 needUpdate = true; 1173 } 1174 break; 1175 1176 default: 1177 // Nothing to do 1178 } 1179 1180 if (needUpdate) { 1181 mSettings.updateIntentFilterVerificationStatusLPw( 1182 packageName, updatedStatus, userId); 1183 scheduleWritePackageRestrictionsLocked(userId); 1184 } 1185 } 1186 } 1187 } 1188 1189 @Override 1190 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1191 ActivityIntentInfo filter, String packageName) { 1192 if (!hasValidDomains(filter)) { 1193 return false; 1194 } 1195 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1196 if (ivs == null) { 1197 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1198 packageName); 1199 } 1200 if (DEBUG_DOMAIN_VERIFICATION) { 1201 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1202 } 1203 ivs.addFilter(filter); 1204 return true; 1205 } 1206 1207 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1208 int userId, int verificationId, String packageName) { 1209 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1210 verifierUid, userId, packageName); 1211 ivs.setPendingState(); 1212 synchronized (mPackages) { 1213 mIntentFilterVerificationStates.append(verificationId, ivs); 1214 mCurrentIntentFilterVerifications.add(verificationId); 1215 } 1216 return ivs; 1217 } 1218 } 1219 1220 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1221 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1222 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1223 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1224 } 1225 1226 // Set of pending broadcasts for aggregating enable/disable of components. 1227 static class PendingPackageBroadcasts { 1228 // for each user id, a map of <package name -> components within that package> 1229 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1230 1231 public PendingPackageBroadcasts() { 1232 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1233 } 1234 1235 public ArrayList<String> get(int userId, String packageName) { 1236 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1237 return packages.get(packageName); 1238 } 1239 1240 public void put(int userId, String packageName, ArrayList<String> components) { 1241 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1242 packages.put(packageName, components); 1243 } 1244 1245 public void remove(int userId, String packageName) { 1246 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1247 if (packages != null) { 1248 packages.remove(packageName); 1249 } 1250 } 1251 1252 public void remove(int userId) { 1253 mUidMap.remove(userId); 1254 } 1255 1256 public int userIdCount() { 1257 return mUidMap.size(); 1258 } 1259 1260 public int userIdAt(int n) { 1261 return mUidMap.keyAt(n); 1262 } 1263 1264 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1265 return mUidMap.get(userId); 1266 } 1267 1268 public int size() { 1269 // total number of pending broadcast entries across all userIds 1270 int num = 0; 1271 for (int i = 0; i< mUidMap.size(); i++) { 1272 num += mUidMap.valueAt(i).size(); 1273 } 1274 return num; 1275 } 1276 1277 public void clear() { 1278 mUidMap.clear(); 1279 } 1280 1281 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1282 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1283 if (map == null) { 1284 map = new ArrayMap<String, ArrayList<String>>(); 1285 mUidMap.put(userId, map); 1286 } 1287 return map; 1288 } 1289 } 1290 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1291 1292 // Service Connection to remote media container service to copy 1293 // package uri's from external media onto secure containers 1294 // or internal storage. 1295 private IMediaContainerService mContainerService = null; 1296 1297 static final int SEND_PENDING_BROADCAST = 1; 1298 static final int MCS_BOUND = 3; 1299 static final int END_COPY = 4; 1300 static final int INIT_COPY = 5; 1301 static final int MCS_UNBIND = 6; 1302 static final int START_CLEANING_PACKAGE = 7; 1303 static final int FIND_INSTALL_LOC = 8; 1304 static final int POST_INSTALL = 9; 1305 static final int MCS_RECONNECT = 10; 1306 static final int MCS_GIVE_UP = 11; 1307 static final int WRITE_SETTINGS = 13; 1308 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1309 static final int PACKAGE_VERIFIED = 15; 1310 static final int CHECK_PENDING_VERIFICATION = 16; 1311 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1312 static final int INTENT_FILTER_VERIFIED = 18; 1313 static final int WRITE_PACKAGE_LIST = 19; 1314 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1315 1316 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1317 1318 // Delay time in millisecs 1319 static final int BROADCAST_DELAY = 10 * 1000; 1320 1321 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1322 2 * 60 * 60 * 1000L; /* two hours */ 1323 1324 static UserManagerService sUserManager; 1325 1326 // Stores a list of users whose package restrictions file needs to be updated 1327 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1328 1329 final private DefaultContainerConnection mDefContainerConn = 1330 new DefaultContainerConnection(); 1331 class DefaultContainerConnection implements ServiceConnection { 1332 public void onServiceConnected(ComponentName name, IBinder service) { 1333 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1334 final IMediaContainerService imcs = IMediaContainerService.Stub 1335 .asInterface(Binder.allowBlocking(service)); 1336 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1337 } 1338 1339 public void onServiceDisconnected(ComponentName name) { 1340 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1341 } 1342 } 1343 1344 // Recordkeeping of restore-after-install operations that are currently in flight 1345 // between the Package Manager and the Backup Manager 1346 static class PostInstallData { 1347 public InstallArgs args; 1348 public PackageInstalledInfo res; 1349 1350 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1351 args = _a; 1352 res = _r; 1353 } 1354 } 1355 1356 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1357 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1358 1359 // XML tags for backup/restore of various bits of state 1360 private static final String TAG_PREFERRED_BACKUP = "pa"; 1361 private static final String TAG_DEFAULT_APPS = "da"; 1362 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1363 1364 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1365 private static final String TAG_ALL_GRANTS = "rt-grants"; 1366 private static final String TAG_GRANT = "grant"; 1367 private static final String ATTR_PACKAGE_NAME = "pkg"; 1368 1369 private static final String TAG_PERMISSION = "perm"; 1370 private static final String ATTR_PERMISSION_NAME = "name"; 1371 private static final String ATTR_IS_GRANTED = "g"; 1372 private static final String ATTR_USER_SET = "set"; 1373 private static final String ATTR_USER_FIXED = "fixed"; 1374 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1375 1376 // System/policy permission grants are not backed up 1377 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1378 FLAG_PERMISSION_POLICY_FIXED 1379 | FLAG_PERMISSION_SYSTEM_FIXED 1380 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1381 1382 // And we back up these user-adjusted states 1383 private static final int USER_RUNTIME_GRANT_MASK = 1384 FLAG_PERMISSION_USER_SET 1385 | FLAG_PERMISSION_USER_FIXED 1386 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1387 1388 final @Nullable String mRequiredVerifierPackage; 1389 final @NonNull String mRequiredInstallerPackage; 1390 final @NonNull String mRequiredUninstallerPackage; 1391 final @Nullable String mSetupWizardPackage; 1392 final @Nullable String mStorageManagerPackage; 1393 final @NonNull String mServicesSystemSharedLibraryPackageName; 1394 final @NonNull String mSharedSystemSharedLibraryPackageName; 1395 1396 private final PackageUsage mPackageUsage = new PackageUsage(); 1397 private final CompilerStats mCompilerStats = new CompilerStats(); 1398 1399 class PackageHandler extends Handler { 1400 private boolean mBound = false; 1401 final ArrayList<HandlerParams> mPendingInstalls = 1402 new ArrayList<HandlerParams>(); 1403 1404 private boolean connectToService() { 1405 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1406 " DefaultContainerService"); 1407 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1409 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1410 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 mBound = true; 1413 return true; 1414 } 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 return false; 1417 } 1418 1419 private void disconnectService() { 1420 mContainerService = null; 1421 mBound = false; 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1423 mContext.unbindService(mDefContainerConn); 1424 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1425 } 1426 1427 PackageHandler(Looper looper) { 1428 super(looper); 1429 } 1430 1431 public void handleMessage(Message msg) { 1432 try { 1433 doHandleMessage(msg); 1434 } finally { 1435 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1436 } 1437 } 1438 1439 void doHandleMessage(Message msg) { 1440 switch (msg.what) { 1441 case INIT_COPY: { 1442 HandlerParams params = (HandlerParams) msg.obj; 1443 int idx = mPendingInstalls.size(); 1444 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1445 // If a bind was already initiated we dont really 1446 // need to do anything. The pending install 1447 // will be processed later on. 1448 if (!mBound) { 1449 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1450 System.identityHashCode(mHandler)); 1451 // If this is the only one pending we might 1452 // have to bind to the service again. 1453 if (!connectToService()) { 1454 Slog.e(TAG, "Failed to bind to media container service"); 1455 params.serviceError(); 1456 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1457 System.identityHashCode(mHandler)); 1458 if (params.traceMethod != null) { 1459 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1460 params.traceCookie); 1461 } 1462 return; 1463 } else { 1464 // Once we bind to the service, the first 1465 // pending request will be processed. 1466 mPendingInstalls.add(idx, params); 1467 } 1468 } else { 1469 mPendingInstalls.add(idx, params); 1470 // Already bound to the service. Just make 1471 // sure we trigger off processing the first request. 1472 if (idx == 0) { 1473 mHandler.sendEmptyMessage(MCS_BOUND); 1474 } 1475 } 1476 break; 1477 } 1478 case MCS_BOUND: { 1479 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1480 if (msg.obj != null) { 1481 mContainerService = (IMediaContainerService) msg.obj; 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1483 System.identityHashCode(mHandler)); 1484 } 1485 if (mContainerService == null) { 1486 if (!mBound) { 1487 // Something seriously wrong since we are not bound and we are not 1488 // waiting for connection. Bail out. 1489 Slog.e(TAG, "Cannot bind to media container service"); 1490 for (HandlerParams params : mPendingInstalls) { 1491 // Indicate service bind error 1492 params.serviceError(); 1493 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1494 System.identityHashCode(params)); 1495 if (params.traceMethod != null) { 1496 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1497 params.traceMethod, params.traceCookie); 1498 } 1499 return; 1500 } 1501 mPendingInstalls.clear(); 1502 } else { 1503 Slog.w(TAG, "Waiting to connect to media container service"); 1504 } 1505 } else if (mPendingInstalls.size() > 0) { 1506 HandlerParams params = mPendingInstalls.get(0); 1507 if (params != null) { 1508 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1509 System.identityHashCode(params)); 1510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1511 if (params.startCopy()) { 1512 // We are done... look for more work or to 1513 // go idle. 1514 if (DEBUG_SD_INSTALL) Log.i(TAG, 1515 "Checking for more work or unbind..."); 1516 // Delete pending install 1517 if (mPendingInstalls.size() > 0) { 1518 mPendingInstalls.remove(0); 1519 } 1520 if (mPendingInstalls.size() == 0) { 1521 if (mBound) { 1522 if (DEBUG_SD_INSTALL) Log.i(TAG, 1523 "Posting delayed MCS_UNBIND"); 1524 removeMessages(MCS_UNBIND); 1525 Message ubmsg = obtainMessage(MCS_UNBIND); 1526 // Unbind after a little delay, to avoid 1527 // continual thrashing. 1528 sendMessageDelayed(ubmsg, 10000); 1529 } 1530 } else { 1531 // There are more pending requests in queue. 1532 // Just post MCS_BOUND message to trigger processing 1533 // of next pending install. 1534 if (DEBUG_SD_INSTALL) Log.i(TAG, 1535 "Posting MCS_BOUND for next work"); 1536 mHandler.sendEmptyMessage(MCS_BOUND); 1537 } 1538 } 1539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1540 } 1541 } else { 1542 // Should never happen ideally. 1543 Slog.w(TAG, "Empty queue"); 1544 } 1545 break; 1546 } 1547 case MCS_RECONNECT: { 1548 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1549 if (mPendingInstalls.size() > 0) { 1550 if (mBound) { 1551 disconnectService(); 1552 } 1553 if (!connectToService()) { 1554 Slog.e(TAG, "Failed to bind to media container service"); 1555 for (HandlerParams params : mPendingInstalls) { 1556 // Indicate service bind error 1557 params.serviceError(); 1558 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1559 System.identityHashCode(params)); 1560 } 1561 mPendingInstalls.clear(); 1562 } 1563 } 1564 break; 1565 } 1566 case MCS_UNBIND: { 1567 // If there is no actual work left, then time to unbind. 1568 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1569 1570 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1571 if (mBound) { 1572 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1573 1574 disconnectService(); 1575 } 1576 } else if (mPendingInstalls.size() > 0) { 1577 // There are more pending requests in queue. 1578 // Just post MCS_BOUND message to trigger processing 1579 // of next pending install. 1580 mHandler.sendEmptyMessage(MCS_BOUND); 1581 } 1582 1583 break; 1584 } 1585 case MCS_GIVE_UP: { 1586 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1587 HandlerParams params = mPendingInstalls.remove(0); 1588 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1589 System.identityHashCode(params)); 1590 break; 1591 } 1592 case SEND_PENDING_BROADCAST: { 1593 String packages[]; 1594 ArrayList<String> components[]; 1595 int size = 0; 1596 int uids[]; 1597 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1598 synchronized (mPackages) { 1599 if (mPendingBroadcasts == null) { 1600 return; 1601 } 1602 size = mPendingBroadcasts.size(); 1603 if (size <= 0) { 1604 // Nothing to be done. Just return 1605 return; 1606 } 1607 packages = new String[size]; 1608 components = new ArrayList[size]; 1609 uids = new int[size]; 1610 int i = 0; // filling out the above arrays 1611 1612 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1613 int packageUserId = mPendingBroadcasts.userIdAt(n); 1614 Iterator<Map.Entry<String, ArrayList<String>>> it 1615 = mPendingBroadcasts.packagesForUserId(packageUserId) 1616 .entrySet().iterator(); 1617 while (it.hasNext() && i < size) { 1618 Map.Entry<String, ArrayList<String>> ent = it.next(); 1619 packages[i] = ent.getKey(); 1620 components[i] = ent.getValue(); 1621 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1622 uids[i] = (ps != null) 1623 ? UserHandle.getUid(packageUserId, ps.appId) 1624 : -1; 1625 i++; 1626 } 1627 } 1628 size = i; 1629 mPendingBroadcasts.clear(); 1630 } 1631 // Send broadcasts 1632 for (int i = 0; i < size; i++) { 1633 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1634 } 1635 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1636 break; 1637 } 1638 case START_CLEANING_PACKAGE: { 1639 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1640 final String packageName = (String)msg.obj; 1641 final int userId = msg.arg1; 1642 final boolean andCode = msg.arg2 != 0; 1643 synchronized (mPackages) { 1644 if (userId == UserHandle.USER_ALL) { 1645 int[] users = sUserManager.getUserIds(); 1646 for (int user : users) { 1647 mSettings.addPackageToCleanLPw( 1648 new PackageCleanItem(user, packageName, andCode)); 1649 } 1650 } else { 1651 mSettings.addPackageToCleanLPw( 1652 new PackageCleanItem(userId, packageName, andCode)); 1653 } 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 startCleaningPackages(); 1657 } break; 1658 case POST_INSTALL: { 1659 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1660 1661 PostInstallData data = mRunningInstalls.get(msg.arg1); 1662 final boolean didRestore = (msg.arg2 != 0); 1663 mRunningInstalls.delete(msg.arg1); 1664 1665 if (data != null) { 1666 InstallArgs args = data.args; 1667 PackageInstalledInfo parentRes = data.res; 1668 1669 final boolean grantPermissions = (args.installFlags 1670 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1671 final boolean killApp = (args.installFlags 1672 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1673 final boolean virtualPreload = ((args.installFlags 1674 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1675 final String[] grantedPermissions = args.installGrantPermissions; 1676 1677 // Handle the parent package 1678 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1679 virtualPreload, grantedPermissions, didRestore, 1680 args.installerPackageName, args.observer); 1681 1682 // Handle the child packages 1683 final int childCount = (parentRes.addedChildPackages != null) 1684 ? parentRes.addedChildPackages.size() : 0; 1685 for (int i = 0; i < childCount; i++) { 1686 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1687 handlePackagePostInstall(childRes, grantPermissions, killApp, 1688 virtualPreload, grantedPermissions, false /*didRestore*/, 1689 args.installerPackageName, args.observer); 1690 } 1691 1692 // Log tracing if needed 1693 if (args.traceMethod != null) { 1694 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1695 args.traceCookie); 1696 } 1697 } else { 1698 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1699 } 1700 1701 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1702 } break; 1703 case WRITE_SETTINGS: { 1704 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1705 synchronized (mPackages) { 1706 removeMessages(WRITE_SETTINGS); 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 mSettings.writeLPr(); 1709 mDirtyUsers.clear(); 1710 } 1711 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1712 } break; 1713 case WRITE_PACKAGE_RESTRICTIONS: { 1714 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1715 synchronized (mPackages) { 1716 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1717 for (int userId : mDirtyUsers) { 1718 mSettings.writePackageRestrictionsLPr(userId); 1719 } 1720 mDirtyUsers.clear(); 1721 } 1722 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1723 } break; 1724 case WRITE_PACKAGE_LIST: { 1725 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1726 synchronized (mPackages) { 1727 removeMessages(WRITE_PACKAGE_LIST); 1728 mSettings.writePackageListLPr(msg.arg1); 1729 } 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1731 } break; 1732 case CHECK_PENDING_VERIFICATION: { 1733 final int verificationId = msg.arg1; 1734 final PackageVerificationState state = mPendingVerification.get(verificationId); 1735 1736 if ((state != null) && !state.timeoutExtended()) { 1737 final InstallArgs args = state.getInstallArgs(); 1738 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1739 1740 Slog.i(TAG, "Verification timed out for " + originUri); 1741 mPendingVerification.remove(verificationId); 1742 1743 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1744 1745 final UserHandle user = args.getUser(); 1746 if (getDefaultVerificationResponse(user) 1747 == PackageManager.VERIFICATION_ALLOW) { 1748 Slog.i(TAG, "Continuing with installation of " + originUri); 1749 state.setVerifierResponse(Binder.getCallingUid(), 1750 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1751 broadcastPackageVerified(verificationId, originUri, 1752 PackageManager.VERIFICATION_ALLOW, user); 1753 try { 1754 ret = args.copyApk(mContainerService, true); 1755 } catch (RemoteException e) { 1756 Slog.e(TAG, "Could not contact the ContainerService"); 1757 } 1758 } else { 1759 broadcastPackageVerified(verificationId, originUri, 1760 PackageManager.VERIFICATION_REJECT, user); 1761 } 1762 1763 Trace.asyncTraceEnd( 1764 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1765 1766 processPendingInstall(args, ret); 1767 mHandler.sendEmptyMessage(MCS_UNBIND); 1768 } 1769 break; 1770 } 1771 case PACKAGE_VERIFIED: { 1772 final int verificationId = msg.arg1; 1773 1774 final PackageVerificationState state = mPendingVerification.get(verificationId); 1775 if (state == null) { 1776 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1777 break; 1778 } 1779 1780 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1781 1782 state.setVerifierResponse(response.callerUid, response.code); 1783 1784 if (state.isVerificationComplete()) { 1785 mPendingVerification.remove(verificationId); 1786 1787 final InstallArgs args = state.getInstallArgs(); 1788 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1789 1790 int ret; 1791 if (state.isInstallAllowed()) { 1792 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1793 broadcastPackageVerified(verificationId, originUri, 1794 response.code, state.getInstallArgs().getUser()); 1795 try { 1796 ret = args.copyApk(mContainerService, true); 1797 } catch (RemoteException e) { 1798 Slog.e(TAG, "Could not contact the ContainerService"); 1799 } 1800 } else { 1801 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1802 } 1803 1804 Trace.asyncTraceEnd( 1805 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1806 1807 processPendingInstall(args, ret); 1808 mHandler.sendEmptyMessage(MCS_UNBIND); 1809 } 1810 1811 break; 1812 } 1813 case START_INTENT_FILTER_VERIFICATIONS: { 1814 IFVerificationParams params = (IFVerificationParams) msg.obj; 1815 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1816 params.replacing, params.pkg); 1817 break; 1818 } 1819 case INTENT_FILTER_VERIFIED: { 1820 final int verificationId = msg.arg1; 1821 1822 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1823 verificationId); 1824 if (state == null) { 1825 Slog.w(TAG, "Invalid IntentFilter verification token " 1826 + verificationId + " received"); 1827 break; 1828 } 1829 1830 final int userId = state.getUserId(); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "Processing IntentFilter verification with token:" 1834 + verificationId + " and userId:" + userId); 1835 1836 final IntentFilterVerificationResponse response = 1837 (IntentFilterVerificationResponse) msg.obj; 1838 1839 state.setVerifierResponse(response.callerUid, response.code); 1840 1841 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1842 "IntentFilter verification with token:" + verificationId 1843 + " and userId:" + userId 1844 + " is settings verifier response with response code:" 1845 + response.code); 1846 1847 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1849 + response.getFailedDomainsString()); 1850 } 1851 1852 if (state.isVerificationComplete()) { 1853 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1854 } else { 1855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1856 "IntentFilter verification with token:" + verificationId 1857 + " was not said to be complete"); 1858 } 1859 1860 break; 1861 } 1862 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1863 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1864 mInstantAppResolverConnection, 1865 (InstantAppRequest) msg.obj, 1866 mInstantAppInstallerActivity, 1867 mHandler); 1868 } 1869 } 1870 } 1871 } 1872 1873 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1874 @Override 1875 public void onGidsChanged(int appId, int userId) { 1876 mHandler.post(new Runnable() { 1877 @Override 1878 public void run() { 1879 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1880 } 1881 }); 1882 } 1883 @Override 1884 public void onPermissionGranted(int uid, int userId) { 1885 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1886 1887 // Not critical; if this is lost, the application has to request again. 1888 synchronized (mPackages) { 1889 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1890 } 1891 } 1892 @Override 1893 public void onInstallPermissionGranted() { 1894 synchronized (mPackages) { 1895 scheduleWriteSettingsLocked(); 1896 } 1897 } 1898 @Override 1899 public void onPermissionRevoked(int uid, int userId) { 1900 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1901 1902 synchronized (mPackages) { 1903 // Critical; after this call the application should never have the permission 1904 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1905 } 1906 1907 final int appId = UserHandle.getAppId(uid); 1908 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1909 } 1910 @Override 1911 public void onInstallPermissionRevoked() { 1912 synchronized (mPackages) { 1913 scheduleWriteSettingsLocked(); 1914 } 1915 } 1916 @Override 1917 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1918 synchronized (mPackages) { 1919 for (int userId : updatedUserIds) { 1920 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1921 } 1922 } 1923 } 1924 @Override 1925 public void onInstallPermissionUpdated() { 1926 synchronized (mPackages) { 1927 scheduleWriteSettingsLocked(); 1928 } 1929 } 1930 @Override 1931 public void onPermissionRemoved() { 1932 synchronized (mPackages) { 1933 mSettings.writeLPr(); 1934 } 1935 } 1936 }; 1937 1938 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1939 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1940 boolean launchedForRestore, String installerPackage, 1941 IPackageInstallObserver2 installObserver) { 1942 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1943 // Send the removed broadcasts 1944 if (res.removedInfo != null) { 1945 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1946 } 1947 1948 // Now that we successfully installed the package, grant runtime 1949 // permissions if requested before broadcasting the install. Also 1950 // for legacy apps in permission review mode we clear the permission 1951 // review flag which is used to emulate runtime permissions for 1952 // legacy apps. 1953 if (grantPermissions) { 1954 final int callingUid = Binder.getCallingUid(); 1955 mPermissionManager.grantRequestedRuntimePermissions( 1956 res.pkg, res.newUsers, grantedPermissions, callingUid, 1957 mPermissionCallback); 1958 } 1959 1960 final boolean update = res.removedInfo != null 1961 && res.removedInfo.removedPackage != null; 1962 final String installerPackageName = 1963 res.installerPackageName != null 1964 ? res.installerPackageName 1965 : res.removedInfo != null 1966 ? res.removedInfo.installerPackageName 1967 : null; 1968 1969 // If this is the first time we have child packages for a disabled privileged 1970 // app that had no children, we grant requested runtime permissions to the new 1971 // children if the parent on the system image had them already granted. 1972 if (res.pkg.parentPackage != null) { 1973 final int callingUid = Binder.getCallingUid(); 1974 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1975 res.pkg, callingUid, mPermissionCallback); 1976 } 1977 1978 synchronized (mPackages) { 1979 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1980 } 1981 1982 final String packageName = res.pkg.applicationInfo.packageName; 1983 1984 // Determine the set of users who are adding this package for 1985 // the first time vs. those who are seeing an update. 1986 int[] firstUserIds = EMPTY_INT_ARRAY; 1987 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1988 int[] updateUserIds = EMPTY_INT_ARRAY; 1989 int[] instantUserIds = EMPTY_INT_ARRAY; 1990 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1991 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1992 for (int newUser : res.newUsers) { 1993 final boolean isInstantApp = ps.getInstantApp(newUser); 1994 if (allNewUsers) { 1995 if (isInstantApp) { 1996 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1997 } else { 1998 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1999 } 2000 continue; 2001 } 2002 boolean isNew = true; 2003 for (int origUser : res.origUsers) { 2004 if (origUser == newUser) { 2005 isNew = false; 2006 break; 2007 } 2008 } 2009 if (isNew) { 2010 if (isInstantApp) { 2011 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2012 } else { 2013 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2014 } 2015 } else { 2016 if (isInstantApp) { 2017 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2018 } else { 2019 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2020 } 2021 } 2022 } 2023 2024 // Send installed broadcasts if the package is not a static shared lib. 2025 if (res.pkg.staticSharedLibName == null) { 2026 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2027 2028 // Send added for users that see the package for the first time 2029 // sendPackageAddedForNewUsers also deals with system apps 2030 int appId = UserHandle.getAppId(res.uid); 2031 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2032 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2033 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2034 2035 // Send added for users that don't see the package for the first time 2036 Bundle extras = new Bundle(1); 2037 extras.putInt(Intent.EXTRA_UID, res.uid); 2038 if (update) { 2039 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2040 } 2041 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2042 extras, 0 /*flags*/, 2043 null /*targetPackage*/, null /*finishedReceiver*/, 2044 updateUserIds, instantUserIds); 2045 if (installerPackageName != null) { 2046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2047 extras, 0 /*flags*/, 2048 installerPackageName, null /*finishedReceiver*/, 2049 updateUserIds, instantUserIds); 2050 } 2051 2052 // Send replaced for users that don't see the package for the first time 2053 if (update) { 2054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2055 packageName, extras, 0 /*flags*/, 2056 null /*targetPackage*/, null /*finishedReceiver*/, 2057 updateUserIds, instantUserIds); 2058 if (installerPackageName != null) { 2059 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2060 extras, 0 /*flags*/, 2061 installerPackageName, null /*finishedReceiver*/, 2062 updateUserIds, instantUserIds); 2063 } 2064 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2065 null /*package*/, null /*extras*/, 0 /*flags*/, 2066 packageName /*targetPackage*/, 2067 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2068 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2069 // First-install and we did a restore, so we're responsible for the 2070 // first-launch broadcast. 2071 if (DEBUG_BACKUP) { 2072 Slog.i(TAG, "Post-restore of " + packageName 2073 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2074 } 2075 sendFirstLaunchBroadcast(packageName, installerPackage, 2076 firstUserIds, firstInstantUserIds); 2077 } 2078 2079 // Send broadcast package appeared if forward locked/external for all users 2080 // treat asec-hosted packages like removable media on upgrade 2081 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2082 if (DEBUG_INSTALL) { 2083 Slog.i(TAG, "upgrading pkg " + res.pkg 2084 + " is ASEC-hosted -> AVAILABLE"); 2085 } 2086 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2087 ArrayList<String> pkgList = new ArrayList<>(1); 2088 pkgList.add(packageName); 2089 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2090 } 2091 } 2092 2093 // Work that needs to happen on first install within each user 2094 if (firstUserIds != null && firstUserIds.length > 0) { 2095 synchronized (mPackages) { 2096 for (int userId : firstUserIds) { 2097 // If this app is a browser and it's newly-installed for some 2098 // users, clear any default-browser state in those users. The 2099 // app's nature doesn't depend on the user, so we can just check 2100 // its browser nature in any user and generalize. 2101 if (packageIsBrowser(packageName, userId)) { 2102 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2103 } 2104 2105 // We may also need to apply pending (restored) runtime 2106 // permission grants within these users. 2107 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2108 } 2109 } 2110 } 2111 2112 if (allNewUsers && !update) { 2113 notifyPackageAdded(packageName); 2114 } 2115 2116 // Log current value of "unknown sources" setting 2117 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2118 getUnknownSourcesSettings()); 2119 2120 // Remove the replaced package's older resources safely now 2121 // We delete after a gc for applications on sdcard. 2122 if (res.removedInfo != null && res.removedInfo.args != null) { 2123 Runtime.getRuntime().gc(); 2124 synchronized (mInstallLock) { 2125 res.removedInfo.args.doPostDeleteLI(true); 2126 } 2127 } else { 2128 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2129 // and not block here. 2130 VMRuntime.getRuntime().requestConcurrentGC(); 2131 } 2132 2133 // Notify DexManager that the package was installed for new users. 2134 // The updated users should already be indexed and the package code paths 2135 // should not change. 2136 // Don't notify the manager for ephemeral apps as they are not expected to 2137 // survive long enough to benefit of background optimizations. 2138 for (int userId : firstUserIds) { 2139 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2140 // There's a race currently where some install events may interleave with an uninstall. 2141 // This can lead to package info being null (b/36642664). 2142 if (info != null) { 2143 mDexManager.notifyPackageInstalled(info, userId); 2144 } 2145 } 2146 } 2147 2148 // If someone is watching installs - notify them 2149 if (installObserver != null) { 2150 try { 2151 Bundle extras = extrasForInstallResult(res); 2152 installObserver.onPackageInstalled(res.name, res.returnCode, 2153 res.returnMsg, extras); 2154 } catch (RemoteException e) { 2155 Slog.i(TAG, "Observer no longer exists."); 2156 } 2157 } 2158 } 2159 2160 private StorageEventListener mStorageListener = new StorageEventListener() { 2161 @Override 2162 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2163 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2164 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2165 final String volumeUuid = vol.getFsUuid(); 2166 2167 // Clean up any users or apps that were removed or recreated 2168 // while this volume was missing 2169 sUserManager.reconcileUsers(volumeUuid); 2170 reconcileApps(volumeUuid); 2171 2172 // Clean up any install sessions that expired or were 2173 // cancelled while this volume was missing 2174 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2175 2176 loadPrivatePackages(vol); 2177 2178 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2179 unloadPrivatePackages(vol); 2180 } 2181 } 2182 } 2183 2184 @Override 2185 public void onVolumeForgotten(String fsUuid) { 2186 if (TextUtils.isEmpty(fsUuid)) { 2187 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2188 return; 2189 } 2190 2191 // Remove any apps installed on the forgotten volume 2192 synchronized (mPackages) { 2193 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2194 for (PackageSetting ps : packages) { 2195 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2196 deletePackageVersioned(new VersionedPackage(ps.name, 2197 PackageManager.VERSION_CODE_HIGHEST), 2198 new LegacyPackageDeleteObserver(null).getBinder(), 2199 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2200 // Try very hard to release any references to this package 2201 // so we don't risk the system server being killed due to 2202 // open FDs 2203 AttributeCache.instance().removePackage(ps.name); 2204 } 2205 2206 mSettings.onVolumeForgotten(fsUuid); 2207 mSettings.writeLPr(); 2208 } 2209 } 2210 }; 2211 2212 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2213 Bundle extras = null; 2214 switch (res.returnCode) { 2215 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2216 extras = new Bundle(); 2217 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2218 res.origPermission); 2219 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2220 res.origPackage); 2221 break; 2222 } 2223 case PackageManager.INSTALL_SUCCEEDED: { 2224 extras = new Bundle(); 2225 extras.putBoolean(Intent.EXTRA_REPLACING, 2226 res.removedInfo != null && res.removedInfo.removedPackage != null); 2227 break; 2228 } 2229 } 2230 return extras; 2231 } 2232 2233 void scheduleWriteSettingsLocked() { 2234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2236 } 2237 } 2238 2239 void scheduleWritePackageListLocked(int userId) { 2240 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2241 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2242 msg.arg1 = userId; 2243 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2244 } 2245 } 2246 2247 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2248 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2249 scheduleWritePackageRestrictionsLocked(userId); 2250 } 2251 2252 void scheduleWritePackageRestrictionsLocked(int userId) { 2253 final int[] userIds = (userId == UserHandle.USER_ALL) 2254 ? sUserManager.getUserIds() : new int[]{userId}; 2255 for (int nextUserId : userIds) { 2256 if (!sUserManager.exists(nextUserId)) return; 2257 mDirtyUsers.add(nextUserId); 2258 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2259 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2260 } 2261 } 2262 } 2263 2264 public static PackageManagerService main(Context context, Installer installer, 2265 boolean factoryTest, boolean onlyCore) { 2266 // Self-check for initial settings. 2267 PackageManagerServiceCompilerMapping.checkProperties(); 2268 2269 PackageManagerService m = new PackageManagerService(context, installer, 2270 factoryTest, onlyCore); 2271 m.enableSystemUserPackages(); 2272 ServiceManager.addService("package", m); 2273 final PackageManagerNative pmn = m.new PackageManagerNative(); 2274 ServiceManager.addService("package_native", pmn); 2275 return m; 2276 } 2277 2278 private void enableSystemUserPackages() { 2279 if (!UserManager.isSplitSystemUser()) { 2280 return; 2281 } 2282 // For system user, enable apps based on the following conditions: 2283 // - app is whitelisted or belong to one of these groups: 2284 // -- system app which has no launcher icons 2285 // -- system app which has INTERACT_ACROSS_USERS permission 2286 // -- system IME app 2287 // - app is not in the blacklist 2288 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2289 Set<String> enableApps = new ArraySet<>(); 2290 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2291 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2292 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2293 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2294 enableApps.addAll(wlApps); 2295 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2296 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2297 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2298 enableApps.removeAll(blApps); 2299 Log.i(TAG, "Applications installed for system user: " + enableApps); 2300 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2301 UserHandle.SYSTEM); 2302 final int allAppsSize = allAps.size(); 2303 synchronized (mPackages) { 2304 for (int i = 0; i < allAppsSize; i++) { 2305 String pName = allAps.get(i); 2306 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2307 // Should not happen, but we shouldn't be failing if it does 2308 if (pkgSetting == null) { 2309 continue; 2310 } 2311 boolean install = enableApps.contains(pName); 2312 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2313 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2314 + " for system user"); 2315 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2316 } 2317 } 2318 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2319 } 2320 } 2321 2322 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2323 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2324 Context.DISPLAY_SERVICE); 2325 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2326 } 2327 2328 /** 2329 * Requests that files preopted on a secondary system partition be copied to the data partition 2330 * if possible. Note that the actual copying of the files is accomplished by init for security 2331 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2332 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2333 */ 2334 private static void requestCopyPreoptedFiles() { 2335 final int WAIT_TIME_MS = 100; 2336 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2337 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2338 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2339 // We will wait for up to 100 seconds. 2340 final long timeStart = SystemClock.uptimeMillis(); 2341 final long timeEnd = timeStart + 100 * 1000; 2342 long timeNow = timeStart; 2343 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2344 try { 2345 Thread.sleep(WAIT_TIME_MS); 2346 } catch (InterruptedException e) { 2347 // Do nothing 2348 } 2349 timeNow = SystemClock.uptimeMillis(); 2350 if (timeNow > timeEnd) { 2351 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2352 Slog.wtf(TAG, "cppreopt did not finish!"); 2353 break; 2354 } 2355 } 2356 2357 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2358 } 2359 } 2360 2361 public PackageManagerService(Context context, Installer installer, 2362 boolean factoryTest, boolean onlyCore) { 2363 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2364 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2365 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2366 SystemClock.uptimeMillis()); 2367 2368 if (mSdkVersion <= 0) { 2369 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2370 } 2371 2372 mContext = context; 2373 2374 mFactoryTest = factoryTest; 2375 mOnlyCore = onlyCore; 2376 mMetrics = new DisplayMetrics(); 2377 mInstaller = installer; 2378 2379 // Create sub-components that provide services / data. Order here is important. 2380 synchronized (mInstallLock) { 2381 synchronized (mPackages) { 2382 // Expose private service for system components to use. 2383 LocalServices.addService( 2384 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2385 sUserManager = new UserManagerService(context, this, 2386 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2387 mPermissionManager = PermissionManagerService.create(context, 2388 new DefaultPermissionGrantedCallback() { 2389 @Override 2390 public void onDefaultRuntimePermissionsGranted(int userId) { 2391 synchronized(mPackages) { 2392 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2393 } 2394 } 2395 }, mPackages /*externalLock*/); 2396 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2397 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2398 } 2399 } 2400 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2401 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2402 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2403 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2404 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2405 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2406 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2407 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2408 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2409 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2410 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2411 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2412 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2413 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2414 2415 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2416 if (separateProcesses != null && separateProcesses.length() > 0) { 2417 if ("*".equals(separateProcesses)) { 2418 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2419 mSeparateProcesses = null; 2420 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2421 } else { 2422 mDefParseFlags = 0; 2423 mSeparateProcesses = separateProcesses.split(","); 2424 Slog.w(TAG, "Running with debug.separate_processes: " 2425 + separateProcesses); 2426 } 2427 } else { 2428 mDefParseFlags = 0; 2429 mSeparateProcesses = null; 2430 } 2431 2432 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2433 "*dexopt*"); 2434 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2435 installer, mInstallLock); 2436 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2437 dexManagerListener); 2438 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2439 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2440 2441 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2442 FgThread.get().getLooper()); 2443 2444 getDefaultDisplayMetrics(context, mMetrics); 2445 2446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2447 SystemConfig systemConfig = SystemConfig.getInstance(); 2448 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2449 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2450 2451 mProtectedPackages = new ProtectedPackages(mContext); 2452 2453 synchronized (mInstallLock) { 2454 // writer 2455 synchronized (mPackages) { 2456 mHandlerThread = new ServiceThread(TAG, 2457 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2458 mHandlerThread.start(); 2459 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2460 mProcessLoggingHandler = new ProcessLoggingHandler(); 2461 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2462 mInstantAppRegistry = new InstantAppRegistry(this); 2463 2464 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2465 final int builtInLibCount = libConfig.size(); 2466 for (int i = 0; i < builtInLibCount; i++) { 2467 String name = libConfig.keyAt(i); 2468 String path = libConfig.valueAt(i); 2469 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2470 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2471 } 2472 2473 SELinuxMMAC.readInstallPolicy(); 2474 2475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2476 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2478 2479 // Clean up orphaned packages for which the code path doesn't exist 2480 // and they are an update to a system app - caused by bug/32321269 2481 final int packageSettingCount = mSettings.mPackages.size(); 2482 for (int i = packageSettingCount - 1; i >= 0; i--) { 2483 PackageSetting ps = mSettings.mPackages.valueAt(i); 2484 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2485 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2486 mSettings.mPackages.removeAt(i); 2487 mSettings.enableSystemPackageLPw(ps.name); 2488 } 2489 } 2490 2491 if (mFirstBoot) { 2492 requestCopyPreoptedFiles(); 2493 } 2494 2495 String customResolverActivity = Resources.getSystem().getString( 2496 R.string.config_customResolverActivity); 2497 if (TextUtils.isEmpty(customResolverActivity)) { 2498 customResolverActivity = null; 2499 } else { 2500 mCustomResolverComponentName = ComponentName.unflattenFromString( 2501 customResolverActivity); 2502 } 2503 2504 long startTime = SystemClock.uptimeMillis(); 2505 2506 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2507 startTime); 2508 2509 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2510 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2511 2512 if (bootClassPath == null) { 2513 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2514 } 2515 2516 if (systemServerClassPath == null) { 2517 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2518 } 2519 2520 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2521 2522 final VersionInfo ver = mSettings.getInternalVersion(); 2523 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2524 if (mIsUpgrade) { 2525 logCriticalInfo(Log.INFO, 2526 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2527 } 2528 2529 // when upgrading from pre-M, promote system app permissions from install to runtime 2530 mPromoteSystemApps = 2531 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2532 2533 // When upgrading from pre-N, we need to handle package extraction like first boot, 2534 // as there is no profiling data available. 2535 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2536 2537 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2538 2539 // save off the names of pre-existing system packages prior to scanning; we don't 2540 // want to automatically grant runtime permissions for new system apps 2541 if (mPromoteSystemApps) { 2542 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2543 while (pkgSettingIter.hasNext()) { 2544 PackageSetting ps = pkgSettingIter.next(); 2545 if (isSystemApp(ps)) { 2546 mExistingSystemPackages.add(ps.name); 2547 } 2548 } 2549 } 2550 2551 mCacheDir = preparePackageParserCache(mIsUpgrade); 2552 2553 // Set flag to monitor and not change apk file paths when 2554 // scanning install directories. 2555 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2556 2557 if (mIsUpgrade || mFirstBoot) { 2558 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2559 } 2560 2561 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2562 // For security and version matching reason, only consider 2563 // overlay packages if they reside in the right directory. 2564 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2565 mDefParseFlags 2566 | PackageParser.PARSE_IS_SYSTEM_DIR, 2567 scanFlags 2568 | SCAN_AS_SYSTEM 2569 | SCAN_AS_VENDOR, 2570 0); 2571 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2572 mDefParseFlags 2573 | PackageParser.PARSE_IS_SYSTEM_DIR, 2574 scanFlags 2575 | SCAN_AS_SYSTEM 2576 | SCAN_AS_PRODUCT, 2577 0); 2578 2579 mParallelPackageParserCallback.findStaticOverlayPackages(); 2580 2581 // Find base frameworks (resource packages without code). 2582 scanDirTracedLI(frameworkDir, 2583 mDefParseFlags 2584 | PackageParser.PARSE_IS_SYSTEM_DIR, 2585 scanFlags 2586 | SCAN_NO_DEX 2587 | SCAN_AS_SYSTEM 2588 | SCAN_AS_PRIVILEGED, 2589 0); 2590 2591 // Collected privileged system packages. 2592 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2593 scanDirTracedLI(privilegedAppDir, 2594 mDefParseFlags 2595 | PackageParser.PARSE_IS_SYSTEM_DIR, 2596 scanFlags 2597 | SCAN_AS_SYSTEM 2598 | SCAN_AS_PRIVILEGED, 2599 0); 2600 2601 // Collect ordinary system packages. 2602 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2603 scanDirTracedLI(systemAppDir, 2604 mDefParseFlags 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, 2606 scanFlags 2607 | SCAN_AS_SYSTEM, 2608 0); 2609 2610 // Collected privileged vendor packages. 2611 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2612 try { 2613 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2614 } catch (IOException e) { 2615 // failed to look up canonical path, continue with original one 2616 } 2617 scanDirTracedLI(privilegedVendorAppDir, 2618 mDefParseFlags 2619 | PackageParser.PARSE_IS_SYSTEM_DIR, 2620 scanFlags 2621 | SCAN_AS_SYSTEM 2622 | SCAN_AS_VENDOR 2623 | SCAN_AS_PRIVILEGED, 2624 0); 2625 2626 // Collect ordinary vendor packages. 2627 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2628 try { 2629 vendorAppDir = vendorAppDir.getCanonicalFile(); 2630 } catch (IOException e) { 2631 // failed to look up canonical path, continue with original one 2632 } 2633 scanDirTracedLI(vendorAppDir, 2634 mDefParseFlags 2635 | PackageParser.PARSE_IS_SYSTEM_DIR, 2636 scanFlags 2637 | SCAN_AS_SYSTEM 2638 | SCAN_AS_VENDOR, 2639 0); 2640 2641 // Collect all OEM packages. 2642 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2643 scanDirTracedLI(oemAppDir, 2644 mDefParseFlags 2645 | PackageParser.PARSE_IS_SYSTEM_DIR, 2646 scanFlags 2647 | SCAN_AS_SYSTEM 2648 | SCAN_AS_OEM, 2649 0); 2650 2651 // Collected privileged product packages. 2652 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2653 try { 2654 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2655 } catch (IOException e) { 2656 // failed to look up canonical path, continue with original one 2657 } 2658 scanDirTracedLI(privilegedProductAppDir, 2659 mDefParseFlags 2660 | PackageParser.PARSE_IS_SYSTEM_DIR, 2661 scanFlags 2662 | SCAN_AS_SYSTEM 2663 | SCAN_AS_PRODUCT 2664 | SCAN_AS_PRIVILEGED, 2665 0); 2666 2667 // Collect ordinary product packages. 2668 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2669 try { 2670 productAppDir = productAppDir.getCanonicalFile(); 2671 } catch (IOException e) { 2672 // failed to look up canonical path, continue with original one 2673 } 2674 scanDirTracedLI(productAppDir, 2675 mDefParseFlags 2676 | PackageParser.PARSE_IS_SYSTEM_DIR, 2677 scanFlags 2678 | SCAN_AS_SYSTEM 2679 | SCAN_AS_PRODUCT, 2680 0); 2681 2682 // Prune any system packages that no longer exist. 2683 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2684 // Stub packages must either be replaced with full versions in the /data 2685 // partition or be disabled. 2686 final List<String> stubSystemApps = new ArrayList<>(); 2687 if (!mOnlyCore) { 2688 // do this first before mucking with mPackages for the "expecting better" case 2689 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2690 while (pkgIterator.hasNext()) { 2691 final PackageParser.Package pkg = pkgIterator.next(); 2692 if (pkg.isStub) { 2693 stubSystemApps.add(pkg.packageName); 2694 } 2695 } 2696 2697 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2698 while (psit.hasNext()) { 2699 PackageSetting ps = psit.next(); 2700 2701 /* 2702 * If this is not a system app, it can't be a 2703 * disable system app. 2704 */ 2705 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2706 continue; 2707 } 2708 2709 /* 2710 * If the package is scanned, it's not erased. 2711 */ 2712 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2713 if (scannedPkg != null) { 2714 /* 2715 * If the system app is both scanned and in the 2716 * disabled packages list, then it must have been 2717 * added via OTA. Remove it from the currently 2718 * scanned package so the previously user-installed 2719 * application can be scanned. 2720 */ 2721 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2722 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2723 + ps.name + "; removing system app. Last known codePath=" 2724 + ps.codePathString + ", installStatus=" + ps.installStatus 2725 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2726 + scannedPkg.getLongVersionCode()); 2727 removePackageLI(scannedPkg, true); 2728 mExpectingBetter.put(ps.name, ps.codePath); 2729 } 2730 2731 continue; 2732 } 2733 2734 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2735 psit.remove(); 2736 logCriticalInfo(Log.WARN, "System package " + ps.name 2737 + " no longer exists; it's data will be wiped"); 2738 // Actual deletion of code and data will be handled by later 2739 // reconciliation step 2740 } else { 2741 // we still have a disabled system package, but, it still might have 2742 // been removed. check the code path still exists and check there's 2743 // still a package. the latter can happen if an OTA keeps the same 2744 // code path, but, changes the package name. 2745 final PackageSetting disabledPs = 2746 mSettings.getDisabledSystemPkgLPr(ps.name); 2747 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2748 || disabledPs.pkg == null) { 2749if (REFACTOR_DEBUG) { 2750Slog.e("TODD", 2751 "Possibly deleted app: " + ps.dumpState_temp() 2752 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2753 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2754} 2755 possiblyDeletedUpdatedSystemApps.add(ps.name); 2756 } 2757 } 2758 } 2759 } 2760 2761 //look for any incomplete package installations 2762 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2763 for (int i = 0; i < deletePkgsList.size(); i++) { 2764 // Actual deletion of code and data will be handled by later 2765 // reconciliation step 2766 final String packageName = deletePkgsList.get(i).name; 2767 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2768 synchronized (mPackages) { 2769 mSettings.removePackageLPw(packageName); 2770 } 2771 } 2772 2773 //delete tmp files 2774 deleteTempPackageFiles(); 2775 2776 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2777 2778 // Remove any shared userIDs that have no associated packages 2779 mSettings.pruneSharedUsersLPw(); 2780 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2781 final int systemPackagesCount = mPackages.size(); 2782 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2783 + " ms, packageCount: " + systemPackagesCount 2784 + " , timePerPackage: " 2785 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2786 + " , cached: " + cachedSystemApps); 2787 if (mIsUpgrade && systemPackagesCount > 0) { 2788 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2789 ((int) systemScanTime) / systemPackagesCount); 2790 } 2791 if (!mOnlyCore) { 2792 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2793 SystemClock.uptimeMillis()); 2794 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2795 2796 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2797 | PackageParser.PARSE_FORWARD_LOCK, 2798 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2799 2800 // Remove disable package settings for updated system apps that were 2801 // removed via an OTA. If the update is no longer present, remove the 2802 // app completely. Otherwise, revoke their system privileges. 2803 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2804 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2805 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2806if (REFACTOR_DEBUG) { 2807Slog.e("TODD", 2808 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2809} 2810 final String msg; 2811 if (deletedPkg == null) { 2812 // should have found an update, but, we didn't; remove everything 2813 msg = "Updated system package " + deletedAppName 2814 + " no longer exists; removing its data"; 2815 // Actual deletion of code and data will be handled by later 2816 // reconciliation step 2817 } else { 2818 // found an update; revoke system privileges 2819 msg = "Updated system package + " + deletedAppName 2820 + " no longer exists; revoking system privileges"; 2821 2822 // Don't do anything if a stub is removed from the system image. If 2823 // we were to remove the uncompressed version from the /data partition, 2824 // this is where it'd be done. 2825 2826 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2827 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2828 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2829 } 2830 logCriticalInfo(Log.WARN, msg); 2831 } 2832 2833 /* 2834 * Make sure all system apps that we expected to appear on 2835 * the userdata partition actually showed up. If they never 2836 * appeared, crawl back and revive the system version. 2837 */ 2838 for (int i = 0; i < mExpectingBetter.size(); i++) { 2839 final String packageName = mExpectingBetter.keyAt(i); 2840 if (!mPackages.containsKey(packageName)) { 2841 final File scanFile = mExpectingBetter.valueAt(i); 2842 2843 logCriticalInfo(Log.WARN, "Expected better " + packageName 2844 + " but never showed up; reverting to system"); 2845 2846 final @ParseFlags int reparseFlags; 2847 final @ScanFlags int rescanFlags; 2848 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2849 reparseFlags = 2850 mDefParseFlags | 2851 PackageParser.PARSE_IS_SYSTEM_DIR; 2852 rescanFlags = 2853 scanFlags 2854 | SCAN_AS_SYSTEM 2855 | SCAN_AS_PRIVILEGED; 2856 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2857 reparseFlags = 2858 mDefParseFlags | 2859 PackageParser.PARSE_IS_SYSTEM_DIR; 2860 rescanFlags = 2861 scanFlags 2862 | SCAN_AS_SYSTEM; 2863 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2864 reparseFlags = 2865 mDefParseFlags | 2866 PackageParser.PARSE_IS_SYSTEM_DIR; 2867 rescanFlags = 2868 scanFlags 2869 | SCAN_AS_SYSTEM 2870 | SCAN_AS_VENDOR 2871 | SCAN_AS_PRIVILEGED; 2872 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2873 reparseFlags = 2874 mDefParseFlags | 2875 PackageParser.PARSE_IS_SYSTEM_DIR; 2876 rescanFlags = 2877 scanFlags 2878 | SCAN_AS_SYSTEM 2879 | SCAN_AS_VENDOR; 2880 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2881 reparseFlags = 2882 mDefParseFlags | 2883 PackageParser.PARSE_IS_SYSTEM_DIR; 2884 rescanFlags = 2885 scanFlags 2886 | SCAN_AS_SYSTEM 2887 | SCAN_AS_OEM; 2888 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2889 reparseFlags = 2890 mDefParseFlags | 2891 PackageParser.PARSE_IS_SYSTEM_DIR; 2892 rescanFlags = 2893 scanFlags 2894 | SCAN_AS_SYSTEM 2895 | SCAN_AS_PRODUCT 2896 | SCAN_AS_PRIVILEGED; 2897 } else if (FileUtils.contains(productAppDir, scanFile)) { 2898 reparseFlags = 2899 mDefParseFlags | 2900 PackageParser.PARSE_IS_SYSTEM_DIR; 2901 rescanFlags = 2902 scanFlags 2903 | SCAN_AS_SYSTEM 2904 | SCAN_AS_PRODUCT; 2905 } else { 2906 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2907 continue; 2908 } 2909 2910 mSettings.enableSystemPackageLPw(packageName); 2911 2912 try { 2913 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2914 } catch (PackageManagerException e) { 2915 Slog.e(TAG, "Failed to parse original system package: " 2916 + e.getMessage()); 2917 } 2918 } 2919 } 2920 2921 // Uncompress and install any stubbed system applications. 2922 // This must be done last to ensure all stubs are replaced or disabled. 2923 decompressSystemApplications(stubSystemApps, scanFlags); 2924 2925 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2926 - cachedSystemApps; 2927 2928 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2929 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2930 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2931 + " ms, packageCount: " + dataPackagesCount 2932 + " , timePerPackage: " 2933 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2934 + " , cached: " + cachedNonSystemApps); 2935 if (mIsUpgrade && dataPackagesCount > 0) { 2936 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2937 ((int) dataScanTime) / dataPackagesCount); 2938 } 2939 } 2940 mExpectingBetter.clear(); 2941 2942 // Resolve the storage manager. 2943 mStorageManagerPackage = getStorageManagerPackageName(); 2944 2945 // Resolve protected action filters. Only the setup wizard is allowed to 2946 // have a high priority filter for these actions. 2947 mSetupWizardPackage = getSetupWizardPackageName(); 2948 if (mProtectedFilters.size() > 0) { 2949 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2950 Slog.i(TAG, "No setup wizard;" 2951 + " All protected intents capped to priority 0"); 2952 } 2953 for (ActivityIntentInfo filter : mProtectedFilters) { 2954 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2955 if (DEBUG_FILTERS) { 2956 Slog.i(TAG, "Found setup wizard;" 2957 + " allow priority " + filter.getPriority() + ";" 2958 + " package: " + filter.activity.info.packageName 2959 + " activity: " + filter.activity.className 2960 + " priority: " + filter.getPriority()); 2961 } 2962 // skip setup wizard; allow it to keep the high priority filter 2963 continue; 2964 } 2965 if (DEBUG_FILTERS) { 2966 Slog.i(TAG, "Protected action; cap priority to 0;" 2967 + " package: " + filter.activity.info.packageName 2968 + " activity: " + filter.activity.className 2969 + " origPrio: " + filter.getPriority()); 2970 } 2971 filter.setPriority(0); 2972 } 2973 } 2974 mDeferProtectedFilters = false; 2975 mProtectedFilters.clear(); 2976 2977 // Now that we know all of the shared libraries, update all clients to have 2978 // the correct library paths. 2979 updateAllSharedLibrariesLPw(null); 2980 2981 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2982 // NOTE: We ignore potential failures here during a system scan (like 2983 // the rest of the commands above) because there's precious little we 2984 // can do about it. A settings error is reported, though. 2985 final List<String> changedAbiCodePath = 2986 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2987 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2988 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2989 final String codePathString = changedAbiCodePath.get(i); 2990 try { 2991 mInstaller.rmdex(codePathString, 2992 getDexCodeInstructionSet(getPreferredInstructionSet())); 2993 } catch (InstallerException ignored) { 2994 } 2995 } 2996 } 2997 } 2998 2999 // Now that we know all the packages we are keeping, 3000 // read and update their last usage times. 3001 mPackageUsage.read(mPackages); 3002 mCompilerStats.read(); 3003 3004 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3005 SystemClock.uptimeMillis()); 3006 Slog.i(TAG, "Time to scan packages: " 3007 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3008 + " seconds"); 3009 3010 // If the platform SDK has changed since the last time we booted, 3011 // we need to re-grant app permission to catch any new ones that 3012 // appear. This is really a hack, and means that apps can in some 3013 // cases get permissions that the user didn't initially explicitly 3014 // allow... it would be nice to have some better way to handle 3015 // this situation. 3016 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3017 if (sdkUpdated) { 3018 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3019 + mSdkVersion + "; regranting permissions for internal storage"); 3020 } 3021 mPermissionManager.updateAllPermissions( 3022 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3023 mPermissionCallback); 3024 ver.sdkVersion = mSdkVersion; 3025 3026 // If this is the first boot or an update from pre-M, and it is a normal 3027 // boot, then we need to initialize the default preferred apps across 3028 // all defined users. 3029 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3030 for (UserInfo user : sUserManager.getUsers(true)) { 3031 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3032 applyFactoryDefaultBrowserLPw(user.id); 3033 primeDomainVerificationsLPw(user.id); 3034 } 3035 } 3036 3037 // Prepare storage for system user really early during boot, 3038 // since core system apps like SettingsProvider and SystemUI 3039 // can't wait for user to start 3040 final int storageFlags; 3041 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3042 storageFlags = StorageManager.FLAG_STORAGE_DE; 3043 } else { 3044 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3045 } 3046 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3047 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3048 true /* onlyCoreApps */); 3049 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3050 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3051 Trace.TRACE_TAG_PACKAGE_MANAGER); 3052 traceLog.traceBegin("AppDataFixup"); 3053 try { 3054 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3056 } catch (InstallerException e) { 3057 Slog.w(TAG, "Trouble fixing GIDs", e); 3058 } 3059 traceLog.traceEnd(); 3060 3061 traceLog.traceBegin("AppDataPrepare"); 3062 if (deferPackages == null || deferPackages.isEmpty()) { 3063 return; 3064 } 3065 int count = 0; 3066 for (String pkgName : deferPackages) { 3067 PackageParser.Package pkg = null; 3068 synchronized (mPackages) { 3069 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3070 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3071 pkg = ps.pkg; 3072 } 3073 } 3074 if (pkg != null) { 3075 synchronized (mInstallLock) { 3076 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3077 true /* maybeMigrateAppData */); 3078 } 3079 count++; 3080 } 3081 } 3082 traceLog.traceEnd(); 3083 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3084 }, "prepareAppData"); 3085 3086 // If this is first boot after an OTA, and a normal boot, then 3087 // we need to clear code cache directories. 3088 // Note that we do *not* clear the application profiles. These remain valid 3089 // across OTAs and are used to drive profile verification (post OTA) and 3090 // profile compilation (without waiting to collect a fresh set of profiles). 3091 if (mIsUpgrade && !onlyCore) { 3092 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3093 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3094 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3095 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3096 // No apps are running this early, so no need to freeze 3097 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3098 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3099 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3100 } 3101 } 3102 ver.fingerprint = Build.FINGERPRINT; 3103 } 3104 3105 checkDefaultBrowser(); 3106 3107 // clear only after permissions and other defaults have been updated 3108 mExistingSystemPackages.clear(); 3109 mPromoteSystemApps = false; 3110 3111 // All the changes are done during package scanning. 3112 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3113 3114 // can downgrade to reader 3115 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3116 mSettings.writeLPr(); 3117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3118 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3119 SystemClock.uptimeMillis()); 3120 3121 if (!mOnlyCore) { 3122 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3123 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3124 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3125 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3126 if (mIntentFilterVerifierComponent != null) { 3127 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3128 mIntentFilterVerifierComponent); 3129 } else { 3130 mIntentFilterVerifier = null; 3131 } 3132 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3133 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3134 SharedLibraryInfo.VERSION_UNDEFINED); 3135 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3136 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3137 SharedLibraryInfo.VERSION_UNDEFINED); 3138 } else { 3139 mRequiredVerifierPackage = null; 3140 mRequiredInstallerPackage = null; 3141 mRequiredUninstallerPackage = null; 3142 mIntentFilterVerifierComponent = null; 3143 mIntentFilterVerifier = null; 3144 mServicesSystemSharedLibraryPackageName = null; 3145 mSharedSystemSharedLibraryPackageName = null; 3146 } 3147 3148 mInstallerService = new PackageInstallerService(context, this); 3149 final Pair<ComponentName, String> instantAppResolverComponent = 3150 getInstantAppResolverLPr(); 3151 if (instantAppResolverComponent != null) { 3152 if (DEBUG_EPHEMERAL) { 3153 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3154 } 3155 mInstantAppResolverConnection = new EphemeralResolverConnection( 3156 mContext, instantAppResolverComponent.first, 3157 instantAppResolverComponent.second); 3158 mInstantAppResolverSettingsComponent = 3159 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3160 } else { 3161 mInstantAppResolverConnection = null; 3162 mInstantAppResolverSettingsComponent = null; 3163 } 3164 updateInstantAppInstallerLocked(null); 3165 3166 // Read and update the usage of dex files. 3167 // Do this at the end of PM init so that all the packages have their 3168 // data directory reconciled. 3169 // At this point we know the code paths of the packages, so we can validate 3170 // the disk file and build the internal cache. 3171 // The usage file is expected to be small so loading and verifying it 3172 // should take a fairly small time compare to the other activities (e.g. package 3173 // scanning). 3174 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3175 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3176 for (int userId : currentUserIds) { 3177 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3178 } 3179 mDexManager.load(userPackages); 3180 if (mIsUpgrade) { 3181 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3182 (int) (SystemClock.uptimeMillis() - startTime)); 3183 } 3184 } // synchronized (mPackages) 3185 } // synchronized (mInstallLock) 3186 3187 // Now after opening every single application zip, make sure they 3188 // are all flushed. Not really needed, but keeps things nice and 3189 // tidy. 3190 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3191 Runtime.getRuntime().gc(); 3192 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3193 3194 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3195 FallbackCategoryProvider.loadFallbacks(); 3196 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3197 3198 // The initial scanning above does many calls into installd while 3199 // holding the mPackages lock, but we're mostly interested in yelling 3200 // once we have a booted system. 3201 mInstaller.setWarnIfHeld(mPackages); 3202 3203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3204 } 3205 3206 /** 3207 * Uncompress and install stub applications. 3208 * <p>In order to save space on the system partition, some applications are shipped in a 3209 * compressed form. In addition the compressed bits for the full application, the 3210 * system image contains a tiny stub comprised of only the Android manifest. 3211 * <p>During the first boot, attempt to uncompress and install the full application. If 3212 * the application can't be installed for any reason, disable the stub and prevent 3213 * uncompressing the full application during future boots. 3214 * <p>In order to forcefully attempt an installation of a full application, go to app 3215 * settings and enable the application. 3216 */ 3217 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3218 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3219 final String pkgName = stubSystemApps.get(i); 3220 // skip if the system package is already disabled 3221 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3222 stubSystemApps.remove(i); 3223 continue; 3224 } 3225 // skip if the package isn't installed (?!); this should never happen 3226 final PackageParser.Package pkg = mPackages.get(pkgName); 3227 if (pkg == null) { 3228 stubSystemApps.remove(i); 3229 continue; 3230 } 3231 // skip if the package has been disabled by the user 3232 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3233 if (ps != null) { 3234 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3235 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3236 stubSystemApps.remove(i); 3237 continue; 3238 } 3239 } 3240 3241 if (DEBUG_COMPRESSION) { 3242 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3243 } 3244 3245 // uncompress the binary to its eventual destination on /data 3246 final File scanFile = decompressPackage(pkg); 3247 if (scanFile == null) { 3248 continue; 3249 } 3250 3251 // install the package to replace the stub on /system 3252 try { 3253 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3254 removePackageLI(pkg, true /*chatty*/); 3255 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3256 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3257 UserHandle.USER_SYSTEM, "android"); 3258 stubSystemApps.remove(i); 3259 continue; 3260 } catch (PackageManagerException e) { 3261 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3262 } 3263 3264 // any failed attempt to install the package will be cleaned up later 3265 } 3266 3267 // disable any stub still left; these failed to install the full application 3268 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3269 final String pkgName = stubSystemApps.get(i); 3270 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3271 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3272 UserHandle.USER_SYSTEM, "android"); 3273 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3274 } 3275 } 3276 3277 /** 3278 * Decompresses the given package on the system image onto 3279 * the /data partition. 3280 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3281 */ 3282 private File decompressPackage(PackageParser.Package pkg) { 3283 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3284 if (compressedFiles == null || compressedFiles.length == 0) { 3285 if (DEBUG_COMPRESSION) { 3286 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3287 } 3288 return null; 3289 } 3290 final File dstCodePath = 3291 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3292 int ret = PackageManager.INSTALL_SUCCEEDED; 3293 try { 3294 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3295 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3296 for (File srcFile : compressedFiles) { 3297 final String srcFileName = srcFile.getName(); 3298 final String dstFileName = srcFileName.substring( 3299 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3300 final File dstFile = new File(dstCodePath, dstFileName); 3301 ret = decompressFile(srcFile, dstFile); 3302 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3303 logCriticalInfo(Log.ERROR, "Failed to decompress" 3304 + "; pkg: " + pkg.packageName 3305 + ", file: " + dstFileName); 3306 break; 3307 } 3308 } 3309 } catch (ErrnoException e) { 3310 logCriticalInfo(Log.ERROR, "Failed to decompress" 3311 + "; pkg: " + pkg.packageName 3312 + ", err: " + e.errno); 3313 } 3314 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3315 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3316 NativeLibraryHelper.Handle handle = null; 3317 try { 3318 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3319 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3320 null /*abiOverride*/); 3321 } catch (IOException e) { 3322 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3323 + "; pkg: " + pkg.packageName); 3324 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3325 } finally { 3326 IoUtils.closeQuietly(handle); 3327 } 3328 } 3329 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3330 if (dstCodePath == null || !dstCodePath.exists()) { 3331 return null; 3332 } 3333 removeCodePathLI(dstCodePath); 3334 return null; 3335 } 3336 3337 return dstCodePath; 3338 } 3339 3340 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3341 // we're only interested in updating the installer appliction when 1) it's not 3342 // already set or 2) the modified package is the installer 3343 if (mInstantAppInstallerActivity != null 3344 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3345 .equals(modifiedPackage)) { 3346 return; 3347 } 3348 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3349 } 3350 3351 private static File preparePackageParserCache(boolean isUpgrade) { 3352 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3353 return null; 3354 } 3355 3356 // Disable package parsing on eng builds to allow for faster incremental development. 3357 if (Build.IS_ENG) { 3358 return null; 3359 } 3360 3361 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3362 Slog.i(TAG, "Disabling package parser cache due to system property."); 3363 return null; 3364 } 3365 3366 // The base directory for the package parser cache lives under /data/system/. 3367 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3368 "package_cache"); 3369 if (cacheBaseDir == null) { 3370 return null; 3371 } 3372 3373 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3374 // This also serves to "GC" unused entries when the package cache version changes (which 3375 // can only happen during upgrades). 3376 if (isUpgrade) { 3377 FileUtils.deleteContents(cacheBaseDir); 3378 } 3379 3380 3381 // Return the versioned package cache directory. This is something like 3382 // "/data/system/package_cache/1" 3383 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3384 3385 // The following is a workaround to aid development on non-numbered userdebug 3386 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3387 // the system partition is newer. 3388 // 3389 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3390 // that starts with "eng." to signify that this is an engineering build and not 3391 // destined for release. 3392 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3393 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3394 3395 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3396 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3397 // in general and should not be used for production changes. In this specific case, 3398 // we know that they will work. 3399 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3400 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3401 FileUtils.deleteContents(cacheBaseDir); 3402 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3403 } 3404 } 3405 3406 return cacheDir; 3407 } 3408 3409 @Override 3410 public boolean isFirstBoot() { 3411 // allow instant applications 3412 return mFirstBoot; 3413 } 3414 3415 @Override 3416 public boolean isOnlyCoreApps() { 3417 // allow instant applications 3418 return mOnlyCore; 3419 } 3420 3421 @Override 3422 public boolean isUpgrade() { 3423 // allow instant applications 3424 // The system property allows testing ota flow when upgraded to the same image. 3425 return mIsUpgrade || SystemProperties.getBoolean( 3426 "persist.pm.mock-upgrade", false /* default */); 3427 } 3428 3429 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3430 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3431 3432 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3433 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3434 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3435 if (matches.size() == 1) { 3436 return matches.get(0).getComponentInfo().packageName; 3437 } else if (matches.size() == 0) { 3438 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3439 return null; 3440 } 3441 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3442 } 3443 3444 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3445 synchronized (mPackages) { 3446 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3447 if (libraryEntry == null) { 3448 throw new IllegalStateException("Missing required shared library:" + name); 3449 } 3450 return libraryEntry.apk; 3451 } 3452 } 3453 3454 private @NonNull String getRequiredInstallerLPr() { 3455 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3456 intent.addCategory(Intent.CATEGORY_DEFAULT); 3457 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3458 3459 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3460 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3461 UserHandle.USER_SYSTEM); 3462 if (matches.size() == 1) { 3463 ResolveInfo resolveInfo = matches.get(0); 3464 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3465 throw new RuntimeException("The installer must be a privileged app"); 3466 } 3467 return matches.get(0).getComponentInfo().packageName; 3468 } else { 3469 throw new RuntimeException("There must be exactly one installer; found " + matches); 3470 } 3471 } 3472 3473 private @NonNull String getRequiredUninstallerLPr() { 3474 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3475 intent.addCategory(Intent.CATEGORY_DEFAULT); 3476 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3477 3478 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3479 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3480 UserHandle.USER_SYSTEM); 3481 if (resolveInfo == null || 3482 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3483 throw new RuntimeException("There must be exactly one uninstaller; found " 3484 + resolveInfo); 3485 } 3486 return resolveInfo.getComponentInfo().packageName; 3487 } 3488 3489 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3490 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3491 3492 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3493 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3494 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3495 ResolveInfo best = null; 3496 final int N = matches.size(); 3497 for (int i = 0; i < N; i++) { 3498 final ResolveInfo cur = matches.get(i); 3499 final String packageName = cur.getComponentInfo().packageName; 3500 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3501 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3502 continue; 3503 } 3504 3505 if (best == null || cur.priority > best.priority) { 3506 best = cur; 3507 } 3508 } 3509 3510 if (best != null) { 3511 return best.getComponentInfo().getComponentName(); 3512 } 3513 Slog.w(TAG, "Intent filter verifier not found"); 3514 return null; 3515 } 3516 3517 @Override 3518 public @Nullable ComponentName getInstantAppResolverComponent() { 3519 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3520 return null; 3521 } 3522 synchronized (mPackages) { 3523 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3524 if (instantAppResolver == null) { 3525 return null; 3526 } 3527 return instantAppResolver.first; 3528 } 3529 } 3530 3531 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3532 final String[] packageArray = 3533 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3534 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3535 if (DEBUG_EPHEMERAL) { 3536 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3537 } 3538 return null; 3539 } 3540 3541 final int callingUid = Binder.getCallingUid(); 3542 final int resolveFlags = 3543 MATCH_DIRECT_BOOT_AWARE 3544 | MATCH_DIRECT_BOOT_UNAWARE 3545 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3546 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3547 final Intent resolverIntent = new Intent(actionName); 3548 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3549 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3550 // temporarily look for the old action 3551 if (resolvers.size() == 0) { 3552 if (DEBUG_EPHEMERAL) { 3553 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3554 } 3555 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3556 resolverIntent.setAction(actionName); 3557 resolvers = queryIntentServicesInternal(resolverIntent, null, 3558 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3559 } 3560 final int N = resolvers.size(); 3561 if (N == 0) { 3562 if (DEBUG_EPHEMERAL) { 3563 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3564 } 3565 return null; 3566 } 3567 3568 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3569 for (int i = 0; i < N; i++) { 3570 final ResolveInfo info = resolvers.get(i); 3571 3572 if (info.serviceInfo == null) { 3573 continue; 3574 } 3575 3576 final String packageName = info.serviceInfo.packageName; 3577 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3578 if (DEBUG_EPHEMERAL) { 3579 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3580 + " pkg: " + packageName + ", info:" + info); 3581 } 3582 continue; 3583 } 3584 3585 if (DEBUG_EPHEMERAL) { 3586 Slog.v(TAG, "Ephemeral resolver found;" 3587 + " pkg: " + packageName + ", info:" + info); 3588 } 3589 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3590 } 3591 if (DEBUG_EPHEMERAL) { 3592 Slog.v(TAG, "Ephemeral resolver NOT found"); 3593 } 3594 return null; 3595 } 3596 3597 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3598 String[] orderedActions = Build.IS_ENG 3599 ? new String[]{ 3600 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3601 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE, 3602 Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE} 3603 : new String[]{ 3604 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE, 3605 Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE}; 3606 3607 final int resolveFlags = 3608 MATCH_DIRECT_BOOT_AWARE 3609 | MATCH_DIRECT_BOOT_UNAWARE 3610 | Intent.FLAG_IGNORE_EPHEMERAL 3611 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3612 final Intent intent = new Intent(); 3613 intent.addCategory(Intent.CATEGORY_DEFAULT); 3614 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3615 List<ResolveInfo> matches = null; 3616 for (String action : orderedActions) { 3617 intent.setAction(action); 3618 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3619 resolveFlags, UserHandle.USER_SYSTEM); 3620 if (matches.isEmpty()) { 3621 if (DEBUG_EPHEMERAL) { 3622 Slog.d(TAG, "Instant App installer not found with " + action); 3623 } 3624 } else { 3625 break; 3626 } 3627 } 3628 Iterator<ResolveInfo> iter = matches.iterator(); 3629 while (iter.hasNext()) { 3630 final ResolveInfo rInfo = iter.next(); 3631 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3632 if (ps != null) { 3633 final PermissionsState permissionsState = ps.getPermissionsState(); 3634 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3635 || Build.IS_ENG) { 3636 continue; 3637 } 3638 } 3639 iter.remove(); 3640 } 3641 if (matches.size() == 0) { 3642 return null; 3643 } else if (matches.size() == 1) { 3644 return (ActivityInfo) matches.get(0).getComponentInfo(); 3645 } else { 3646 throw new RuntimeException( 3647 "There must be at most one ephemeral installer; found " + matches); 3648 } 3649 } 3650 3651 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3652 @NonNull ComponentName resolver) { 3653 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3654 .addCategory(Intent.CATEGORY_DEFAULT) 3655 .setPackage(resolver.getPackageName()); 3656 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3657 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3658 UserHandle.USER_SYSTEM); 3659 // temporarily look for the old action 3660 if (matches.isEmpty()) { 3661 if (DEBUG_EPHEMERAL) { 3662 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3663 } 3664 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3665 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3666 UserHandle.USER_SYSTEM); 3667 } 3668 if (matches.isEmpty()) { 3669 return null; 3670 } 3671 return matches.get(0).getComponentInfo().getComponentName(); 3672 } 3673 3674 private void primeDomainVerificationsLPw(int userId) { 3675 if (DEBUG_DOMAIN_VERIFICATION) { 3676 Slog.d(TAG, "Priming domain verifications in user " + userId); 3677 } 3678 3679 SystemConfig systemConfig = SystemConfig.getInstance(); 3680 ArraySet<String> packages = systemConfig.getLinkedApps(); 3681 3682 for (String packageName : packages) { 3683 PackageParser.Package pkg = mPackages.get(packageName); 3684 if (pkg != null) { 3685 if (!pkg.isSystem()) { 3686 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3687 continue; 3688 } 3689 3690 ArraySet<String> domains = null; 3691 for (PackageParser.Activity a : pkg.activities) { 3692 for (ActivityIntentInfo filter : a.intents) { 3693 if (hasValidDomains(filter)) { 3694 if (domains == null) { 3695 domains = new ArraySet<String>(); 3696 } 3697 domains.addAll(filter.getHostsList()); 3698 } 3699 } 3700 } 3701 3702 if (domains != null && domains.size() > 0) { 3703 if (DEBUG_DOMAIN_VERIFICATION) { 3704 Slog.v(TAG, " + " + packageName); 3705 } 3706 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3707 // state w.r.t. the formal app-linkage "no verification attempted" state; 3708 // and then 'always' in the per-user state actually used for intent resolution. 3709 final IntentFilterVerificationInfo ivi; 3710 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3711 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3712 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3713 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3714 } else { 3715 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3716 + "' does not handle web links"); 3717 } 3718 } else { 3719 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3720 } 3721 } 3722 3723 scheduleWritePackageRestrictionsLocked(userId); 3724 scheduleWriteSettingsLocked(); 3725 } 3726 3727 private void applyFactoryDefaultBrowserLPw(int userId) { 3728 // The default browser app's package name is stored in a string resource, 3729 // with a product-specific overlay used for vendor customization. 3730 String browserPkg = mContext.getResources().getString( 3731 com.android.internal.R.string.default_browser); 3732 if (!TextUtils.isEmpty(browserPkg)) { 3733 // non-empty string => required to be a known package 3734 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3735 if (ps == null) { 3736 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3737 browserPkg = null; 3738 } else { 3739 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3740 } 3741 } 3742 3743 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3744 // default. If there's more than one, just leave everything alone. 3745 if (browserPkg == null) { 3746 calculateDefaultBrowserLPw(userId); 3747 } 3748 } 3749 3750 private void calculateDefaultBrowserLPw(int userId) { 3751 List<String> allBrowsers = resolveAllBrowserApps(userId); 3752 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3753 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3754 } 3755 3756 private List<String> resolveAllBrowserApps(int userId) { 3757 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3758 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3759 PackageManager.MATCH_ALL, userId); 3760 3761 final int count = list.size(); 3762 List<String> result = new ArrayList<String>(count); 3763 for (int i=0; i<count; i++) { 3764 ResolveInfo info = list.get(i); 3765 if (info.activityInfo == null 3766 || !info.handleAllWebDataURI 3767 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3768 || result.contains(info.activityInfo.packageName)) { 3769 continue; 3770 } 3771 result.add(info.activityInfo.packageName); 3772 } 3773 3774 return result; 3775 } 3776 3777 private boolean packageIsBrowser(String packageName, int userId) { 3778 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3779 PackageManager.MATCH_ALL, userId); 3780 final int N = list.size(); 3781 for (int i = 0; i < N; i++) { 3782 ResolveInfo info = list.get(i); 3783 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3784 return true; 3785 } 3786 } 3787 return false; 3788 } 3789 3790 private void checkDefaultBrowser() { 3791 final int myUserId = UserHandle.myUserId(); 3792 final String packageName = getDefaultBrowserPackageName(myUserId); 3793 if (packageName != null) { 3794 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3795 if (info == null) { 3796 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3797 synchronized (mPackages) { 3798 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3799 } 3800 } 3801 } 3802 } 3803 3804 @Override 3805 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3806 throws RemoteException { 3807 try { 3808 return super.onTransact(code, data, reply, flags); 3809 } catch (RuntimeException e) { 3810 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3811 Slog.wtf(TAG, "Package Manager Crash", e); 3812 } 3813 throw e; 3814 } 3815 } 3816 3817 static int[] appendInts(int[] cur, int[] add) { 3818 if (add == null) return cur; 3819 if (cur == null) return add; 3820 final int N = add.length; 3821 for (int i=0; i<N; i++) { 3822 cur = appendInt(cur, add[i]); 3823 } 3824 return cur; 3825 } 3826 3827 /** 3828 * Returns whether or not a full application can see an instant application. 3829 * <p> 3830 * Currently, there are three cases in which this can occur: 3831 * <ol> 3832 * <li>The calling application is a "special" process. Special processes 3833 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3834 * <li>The calling application has the permission 3835 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3836 * <li>The calling application is the default launcher on the 3837 * system partition.</li> 3838 * </ol> 3839 */ 3840 private boolean canViewInstantApps(int callingUid, int userId) { 3841 if (callingUid < Process.FIRST_APPLICATION_UID) { 3842 return true; 3843 } 3844 if (mContext.checkCallingOrSelfPermission( 3845 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3846 return true; 3847 } 3848 if (mContext.checkCallingOrSelfPermission( 3849 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3850 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3851 if (homeComponent != null 3852 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3853 return true; 3854 } 3855 } 3856 return false; 3857 } 3858 3859 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3860 if (!sUserManager.exists(userId)) return null; 3861 if (ps == null) { 3862 return null; 3863 } 3864 PackageParser.Package p = ps.pkg; 3865 if (p == null) { 3866 return null; 3867 } 3868 final int callingUid = Binder.getCallingUid(); 3869 // Filter out ephemeral app metadata: 3870 // * The system/shell/root can see metadata for any app 3871 // * An installed app can see metadata for 1) other installed apps 3872 // and 2) ephemeral apps that have explicitly interacted with it 3873 // * Ephemeral apps can only see their own data and exposed installed apps 3874 // * Holding a signature permission allows seeing instant apps 3875 if (filterAppAccessLPr(ps, callingUid, userId)) { 3876 return null; 3877 } 3878 3879 final PermissionsState permissionsState = ps.getPermissionsState(); 3880 3881 // Compute GIDs only if requested 3882 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3883 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3884 // Compute granted permissions only if package has requested permissions 3885 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3886 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3887 final PackageUserState state = ps.readUserState(userId); 3888 3889 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3890 && ps.isSystem()) { 3891 flags |= MATCH_ANY_USER; 3892 } 3893 3894 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3895 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3896 3897 if (packageInfo == null) { 3898 return null; 3899 } 3900 3901 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3902 resolveExternalPackageNameLPr(p); 3903 3904 return packageInfo; 3905 } 3906 3907 @Override 3908 public void checkPackageStartable(String packageName, int userId) { 3909 final int callingUid = Binder.getCallingUid(); 3910 if (getInstantAppPackageName(callingUid) != null) { 3911 throw new SecurityException("Instant applications don't have access to this method"); 3912 } 3913 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3914 synchronized (mPackages) { 3915 final PackageSetting ps = mSettings.mPackages.get(packageName); 3916 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3917 throw new SecurityException("Package " + packageName + " was not found!"); 3918 } 3919 3920 if (!ps.getInstalled(userId)) { 3921 throw new SecurityException( 3922 "Package " + packageName + " was not installed for user " + userId + "!"); 3923 } 3924 3925 if (mSafeMode && !ps.isSystem()) { 3926 throw new SecurityException("Package " + packageName + " not a system app!"); 3927 } 3928 3929 if (mFrozenPackages.contains(packageName)) { 3930 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3931 } 3932 3933 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3934 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3935 } 3936 } 3937 } 3938 3939 @Override 3940 public boolean isPackageAvailable(String packageName, int userId) { 3941 if (!sUserManager.exists(userId)) return false; 3942 final int callingUid = Binder.getCallingUid(); 3943 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3944 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3945 synchronized (mPackages) { 3946 PackageParser.Package p = mPackages.get(packageName); 3947 if (p != null) { 3948 final PackageSetting ps = (PackageSetting) p.mExtras; 3949 if (filterAppAccessLPr(ps, callingUid, userId)) { 3950 return false; 3951 } 3952 if (ps != null) { 3953 final PackageUserState state = ps.readUserState(userId); 3954 if (state != null) { 3955 return PackageParser.isAvailable(state); 3956 } 3957 } 3958 } 3959 } 3960 return false; 3961 } 3962 3963 @Override 3964 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3965 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3966 flags, Binder.getCallingUid(), userId); 3967 } 3968 3969 @Override 3970 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3971 int flags, int userId) { 3972 return getPackageInfoInternal(versionedPackage.getPackageName(), 3973 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3974 } 3975 3976 /** 3977 * Important: The provided filterCallingUid is used exclusively to filter out packages 3978 * that can be seen based on user state. It's typically the original caller uid prior 3979 * to clearing. Because it can only be provided by trusted code, it's value can be 3980 * trusted and will be used as-is; unlike userId which will be validated by this method. 3981 */ 3982 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3983 int flags, int filterCallingUid, int userId) { 3984 if (!sUserManager.exists(userId)) return null; 3985 flags = updateFlagsForPackage(flags, userId, packageName); 3986 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3987 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3988 3989 // reader 3990 synchronized (mPackages) { 3991 // Normalize package name to handle renamed packages and static libs 3992 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3993 3994 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3995 if (matchFactoryOnly) { 3996 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3997 if (ps != null) { 3998 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3999 return null; 4000 } 4001 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4002 return null; 4003 } 4004 return generatePackageInfo(ps, flags, userId); 4005 } 4006 } 4007 4008 PackageParser.Package p = mPackages.get(packageName); 4009 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4010 return null; 4011 } 4012 if (DEBUG_PACKAGE_INFO) 4013 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4014 if (p != null) { 4015 final PackageSetting ps = (PackageSetting) p.mExtras; 4016 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4017 return null; 4018 } 4019 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4020 return null; 4021 } 4022 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4023 } 4024 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4025 final PackageSetting ps = mSettings.mPackages.get(packageName); 4026 if (ps == null) return null; 4027 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4028 return null; 4029 } 4030 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4031 return null; 4032 } 4033 return generatePackageInfo(ps, flags, userId); 4034 } 4035 } 4036 return null; 4037 } 4038 4039 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4040 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4041 return true; 4042 } 4043 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4044 return true; 4045 } 4046 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4047 return true; 4048 } 4049 return false; 4050 } 4051 4052 private boolean isComponentVisibleToInstantApp( 4053 @Nullable ComponentName component, @ComponentType int type) { 4054 if (type == TYPE_ACTIVITY) { 4055 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4056 return activity != null 4057 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4058 : false; 4059 } else if (type == TYPE_RECEIVER) { 4060 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4061 return activity != null 4062 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4063 : false; 4064 } else if (type == TYPE_SERVICE) { 4065 final PackageParser.Service service = mServices.mServices.get(component); 4066 return service != null 4067 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4068 : false; 4069 } else if (type == TYPE_PROVIDER) { 4070 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4071 return provider != null 4072 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4073 : false; 4074 } else if (type == TYPE_UNKNOWN) { 4075 return isComponentVisibleToInstantApp(component); 4076 } 4077 return false; 4078 } 4079 4080 /** 4081 * Returns whether or not access to the application should be filtered. 4082 * <p> 4083 * Access may be limited based upon whether the calling or target applications 4084 * are instant applications. 4085 * 4086 * @see #canAccessInstantApps(int) 4087 */ 4088 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4089 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4090 // if we're in an isolated process, get the real calling UID 4091 if (Process.isIsolated(callingUid)) { 4092 callingUid = mIsolatedOwners.get(callingUid); 4093 } 4094 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4095 final boolean callerIsInstantApp = instantAppPkgName != null; 4096 if (ps == null) { 4097 if (callerIsInstantApp) { 4098 // pretend the application exists, but, needs to be filtered 4099 return true; 4100 } 4101 return false; 4102 } 4103 // if the target and caller are the same application, don't filter 4104 if (isCallerSameApp(ps.name, callingUid)) { 4105 return false; 4106 } 4107 if (callerIsInstantApp) { 4108 // request for a specific component; if it hasn't been explicitly exposed, filter 4109 if (component != null) { 4110 return !isComponentVisibleToInstantApp(component, componentType); 4111 } 4112 // request for application; if no components have been explicitly exposed, filter 4113 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4114 } 4115 if (ps.getInstantApp(userId)) { 4116 // caller can see all components of all instant applications, don't filter 4117 if (canViewInstantApps(callingUid, userId)) { 4118 return false; 4119 } 4120 // request for a specific instant application component, filter 4121 if (component != null) { 4122 return true; 4123 } 4124 // request for an instant application; if the caller hasn't been granted access, filter 4125 return !mInstantAppRegistry.isInstantAccessGranted( 4126 userId, UserHandle.getAppId(callingUid), ps.appId); 4127 } 4128 return false; 4129 } 4130 4131 /** 4132 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4133 */ 4134 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4135 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4136 } 4137 4138 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4139 int flags) { 4140 // Callers can access only the libs they depend on, otherwise they need to explicitly 4141 // ask for the shared libraries given the caller is allowed to access all static libs. 4142 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4143 // System/shell/root get to see all static libs 4144 final int appId = UserHandle.getAppId(uid); 4145 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4146 || appId == Process.ROOT_UID) { 4147 return false; 4148 } 4149 } 4150 4151 // No package means no static lib as it is always on internal storage 4152 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4153 return false; 4154 } 4155 4156 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4157 ps.pkg.staticSharedLibVersion); 4158 if (libEntry == null) { 4159 return false; 4160 } 4161 4162 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4163 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4164 if (uidPackageNames == null) { 4165 return true; 4166 } 4167 4168 for (String uidPackageName : uidPackageNames) { 4169 if (ps.name.equals(uidPackageName)) { 4170 return false; 4171 } 4172 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4173 if (uidPs != null) { 4174 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4175 libEntry.info.getName()); 4176 if (index < 0) { 4177 continue; 4178 } 4179 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4180 return false; 4181 } 4182 } 4183 } 4184 return true; 4185 } 4186 4187 @Override 4188 public String[] currentToCanonicalPackageNames(String[] names) { 4189 final int callingUid = Binder.getCallingUid(); 4190 if (getInstantAppPackageName(callingUid) != null) { 4191 return names; 4192 } 4193 final String[] out = new String[names.length]; 4194 // reader 4195 synchronized (mPackages) { 4196 final int callingUserId = UserHandle.getUserId(callingUid); 4197 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4198 for (int i=names.length-1; i>=0; i--) { 4199 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4200 boolean translateName = false; 4201 if (ps != null && ps.realName != null) { 4202 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4203 translateName = !targetIsInstantApp 4204 || canViewInstantApps 4205 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4206 UserHandle.getAppId(callingUid), ps.appId); 4207 } 4208 out[i] = translateName ? ps.realName : names[i]; 4209 } 4210 } 4211 return out; 4212 } 4213 4214 @Override 4215 public String[] canonicalToCurrentPackageNames(String[] names) { 4216 final int callingUid = Binder.getCallingUid(); 4217 if (getInstantAppPackageName(callingUid) != null) { 4218 return names; 4219 } 4220 final String[] out = new String[names.length]; 4221 // reader 4222 synchronized (mPackages) { 4223 final int callingUserId = UserHandle.getUserId(callingUid); 4224 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4225 for (int i=names.length-1; i>=0; i--) { 4226 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4227 boolean translateName = false; 4228 if (cur != null) { 4229 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4230 final boolean targetIsInstantApp = 4231 ps != null && ps.getInstantApp(callingUserId); 4232 translateName = !targetIsInstantApp 4233 || canViewInstantApps 4234 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4235 UserHandle.getAppId(callingUid), ps.appId); 4236 } 4237 out[i] = translateName ? cur : names[i]; 4238 } 4239 } 4240 return out; 4241 } 4242 4243 @Override 4244 public int getPackageUid(String packageName, int flags, int userId) { 4245 if (!sUserManager.exists(userId)) return -1; 4246 final int callingUid = Binder.getCallingUid(); 4247 flags = updateFlagsForPackage(flags, userId, packageName); 4248 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4249 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4250 4251 // reader 4252 synchronized (mPackages) { 4253 final PackageParser.Package p = mPackages.get(packageName); 4254 if (p != null && p.isMatch(flags)) { 4255 PackageSetting ps = (PackageSetting) p.mExtras; 4256 if (filterAppAccessLPr(ps, callingUid, userId)) { 4257 return -1; 4258 } 4259 return UserHandle.getUid(userId, p.applicationInfo.uid); 4260 } 4261 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4262 final PackageSetting ps = mSettings.mPackages.get(packageName); 4263 if (ps != null && ps.isMatch(flags) 4264 && !filterAppAccessLPr(ps, callingUid, userId)) { 4265 return UserHandle.getUid(userId, ps.appId); 4266 } 4267 } 4268 } 4269 4270 return -1; 4271 } 4272 4273 @Override 4274 public int[] getPackageGids(String packageName, int flags, int userId) { 4275 if (!sUserManager.exists(userId)) return null; 4276 final int callingUid = Binder.getCallingUid(); 4277 flags = updateFlagsForPackage(flags, userId, packageName); 4278 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4279 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4280 4281 // reader 4282 synchronized (mPackages) { 4283 final PackageParser.Package p = mPackages.get(packageName); 4284 if (p != null && p.isMatch(flags)) { 4285 PackageSetting ps = (PackageSetting) p.mExtras; 4286 if (filterAppAccessLPr(ps, callingUid, userId)) { 4287 return null; 4288 } 4289 // TODO: Shouldn't this be checking for package installed state for userId and 4290 // return null? 4291 return ps.getPermissionsState().computeGids(userId); 4292 } 4293 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4294 final PackageSetting ps = mSettings.mPackages.get(packageName); 4295 if (ps != null && ps.isMatch(flags) 4296 && !filterAppAccessLPr(ps, callingUid, userId)) { 4297 return ps.getPermissionsState().computeGids(userId); 4298 } 4299 } 4300 } 4301 4302 return null; 4303 } 4304 4305 @Override 4306 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4307 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4308 } 4309 4310 @Override 4311 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4312 int flags) { 4313 final List<PermissionInfo> permissionList = 4314 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4315 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4316 } 4317 4318 @Override 4319 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4320 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4321 } 4322 4323 @Override 4324 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4325 final List<PermissionGroupInfo> permissionList = 4326 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4327 return (permissionList == null) 4328 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4329 } 4330 4331 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4332 int filterCallingUid, int userId) { 4333 if (!sUserManager.exists(userId)) return null; 4334 PackageSetting ps = mSettings.mPackages.get(packageName); 4335 if (ps != null) { 4336 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4337 return null; 4338 } 4339 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4340 return null; 4341 } 4342 if (ps.pkg == null) { 4343 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4344 if (pInfo != null) { 4345 return pInfo.applicationInfo; 4346 } 4347 return null; 4348 } 4349 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4350 ps.readUserState(userId), userId); 4351 if (ai != null) { 4352 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4353 } 4354 return ai; 4355 } 4356 return null; 4357 } 4358 4359 @Override 4360 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4361 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4362 } 4363 4364 /** 4365 * Important: The provided filterCallingUid is used exclusively to filter out applications 4366 * that can be seen based on user state. It's typically the original caller uid prior 4367 * to clearing. Because it can only be provided by trusted code, it's value can be 4368 * trusted and will be used as-is; unlike userId which will be validated by this method. 4369 */ 4370 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4371 int filterCallingUid, int userId) { 4372 if (!sUserManager.exists(userId)) return null; 4373 flags = updateFlagsForApplication(flags, userId, packageName); 4374 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4375 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4376 4377 // writer 4378 synchronized (mPackages) { 4379 // Normalize package name to handle renamed packages and static libs 4380 packageName = resolveInternalPackageNameLPr(packageName, 4381 PackageManager.VERSION_CODE_HIGHEST); 4382 4383 PackageParser.Package p = mPackages.get(packageName); 4384 if (DEBUG_PACKAGE_INFO) Log.v( 4385 TAG, "getApplicationInfo " + packageName 4386 + ": " + p); 4387 if (p != null) { 4388 PackageSetting ps = mSettings.mPackages.get(packageName); 4389 if (ps == null) return null; 4390 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4391 return null; 4392 } 4393 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4394 return null; 4395 } 4396 // Note: isEnabledLP() does not apply here - always return info 4397 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4398 p, flags, ps.readUserState(userId), userId); 4399 if (ai != null) { 4400 ai.packageName = resolveExternalPackageNameLPr(p); 4401 } 4402 return ai; 4403 } 4404 if ("android".equals(packageName)||"system".equals(packageName)) { 4405 return mAndroidApplication; 4406 } 4407 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4408 // Already generates the external package name 4409 return generateApplicationInfoFromSettingsLPw(packageName, 4410 flags, filterCallingUid, userId); 4411 } 4412 } 4413 return null; 4414 } 4415 4416 private String normalizePackageNameLPr(String packageName) { 4417 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4418 return normalizedPackageName != null ? normalizedPackageName : packageName; 4419 } 4420 4421 @Override 4422 public void deletePreloadsFileCache() { 4423 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4424 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4425 } 4426 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4427 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4428 FileUtils.deleteContents(dir); 4429 } 4430 4431 @Override 4432 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4433 final int storageFlags, final IPackageDataObserver observer) { 4434 mContext.enforceCallingOrSelfPermission( 4435 android.Manifest.permission.CLEAR_APP_CACHE, null); 4436 mHandler.post(() -> { 4437 boolean success = false; 4438 try { 4439 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4440 success = true; 4441 } catch (IOException e) { 4442 Slog.w(TAG, e); 4443 } 4444 if (observer != null) { 4445 try { 4446 observer.onRemoveCompleted(null, success); 4447 } catch (RemoteException e) { 4448 Slog.w(TAG, e); 4449 } 4450 } 4451 }); 4452 } 4453 4454 @Override 4455 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4456 final int storageFlags, final IntentSender pi) { 4457 mContext.enforceCallingOrSelfPermission( 4458 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4459 mHandler.post(() -> { 4460 boolean success = false; 4461 try { 4462 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4463 success = true; 4464 } catch (IOException e) { 4465 Slog.w(TAG, e); 4466 } 4467 if (pi != null) { 4468 try { 4469 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4470 } catch (SendIntentException e) { 4471 Slog.w(TAG, e); 4472 } 4473 } 4474 }); 4475 } 4476 4477 /** 4478 * Blocking call to clear various types of cached data across the system 4479 * until the requested bytes are available. 4480 */ 4481 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4482 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4483 final File file = storage.findPathForUuid(volumeUuid); 4484 if (file.getUsableSpace() >= bytes) return; 4485 4486 if (ENABLE_FREE_CACHE_V2) { 4487 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4488 volumeUuid); 4489 final boolean aggressive = (storageFlags 4490 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4491 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4492 4493 // 1. Pre-flight to determine if we have any chance to succeed 4494 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4495 if (internalVolume && (aggressive || SystemProperties 4496 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4497 deletePreloadsFileCache(); 4498 if (file.getUsableSpace() >= bytes) return; 4499 } 4500 4501 // 3. Consider parsed APK data (aggressive only) 4502 if (internalVolume && aggressive) { 4503 FileUtils.deleteContents(mCacheDir); 4504 if (file.getUsableSpace() >= bytes) return; 4505 } 4506 4507 // 4. Consider cached app data (above quotas) 4508 try { 4509 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4510 Installer.FLAG_FREE_CACHE_V2); 4511 } catch (InstallerException ignored) { 4512 } 4513 if (file.getUsableSpace() >= bytes) return; 4514 4515 // 5. Consider shared libraries with refcount=0 and age>min cache period 4516 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4517 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4518 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4519 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4520 return; 4521 } 4522 4523 // 6. Consider dexopt output (aggressive only) 4524 // TODO: Implement 4525 4526 // 7. Consider installed instant apps unused longer than min cache period 4527 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4528 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4529 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4530 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4531 return; 4532 } 4533 4534 // 8. Consider cached app data (below quotas) 4535 try { 4536 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4537 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4538 } catch (InstallerException ignored) { 4539 } 4540 if (file.getUsableSpace() >= bytes) return; 4541 4542 // 9. Consider DropBox entries 4543 // TODO: Implement 4544 4545 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4546 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4547 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4548 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4549 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4550 return; 4551 } 4552 } else { 4553 try { 4554 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4555 } catch (InstallerException ignored) { 4556 } 4557 if (file.getUsableSpace() >= bytes) return; 4558 } 4559 4560 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4561 } 4562 4563 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4564 throws IOException { 4565 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4566 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4567 4568 List<VersionedPackage> packagesToDelete = null; 4569 final long now = System.currentTimeMillis(); 4570 4571 synchronized (mPackages) { 4572 final int[] allUsers = sUserManager.getUserIds(); 4573 final int libCount = mSharedLibraries.size(); 4574 for (int i = 0; i < libCount; i++) { 4575 final LongSparseArray<SharedLibraryEntry> versionedLib 4576 = mSharedLibraries.valueAt(i); 4577 if (versionedLib == null) { 4578 continue; 4579 } 4580 final int versionCount = versionedLib.size(); 4581 for (int j = 0; j < versionCount; j++) { 4582 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4583 // Skip packages that are not static shared libs. 4584 if (!libInfo.isStatic()) { 4585 break; 4586 } 4587 // Important: We skip static shared libs used for some user since 4588 // in such a case we need to keep the APK on the device. The check for 4589 // a lib being used for any user is performed by the uninstall call. 4590 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4591 // Resolve the package name - we use synthetic package names internally 4592 final String internalPackageName = resolveInternalPackageNameLPr( 4593 declaringPackage.getPackageName(), 4594 declaringPackage.getLongVersionCode()); 4595 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4596 // Skip unused static shared libs cached less than the min period 4597 // to prevent pruning a lib needed by a subsequently installed package. 4598 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4599 continue; 4600 } 4601 if (packagesToDelete == null) { 4602 packagesToDelete = new ArrayList<>(); 4603 } 4604 packagesToDelete.add(new VersionedPackage(internalPackageName, 4605 declaringPackage.getLongVersionCode())); 4606 } 4607 } 4608 } 4609 4610 if (packagesToDelete != null) { 4611 final int packageCount = packagesToDelete.size(); 4612 for (int i = 0; i < packageCount; i++) { 4613 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4614 // Delete the package synchronously (will fail of the lib used for any user). 4615 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4616 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4617 == PackageManager.DELETE_SUCCEEDED) { 4618 if (volume.getUsableSpace() >= neededSpace) { 4619 return true; 4620 } 4621 } 4622 } 4623 } 4624 4625 return false; 4626 } 4627 4628 /** 4629 * Update given flags based on encryption status of current user. 4630 */ 4631 private int updateFlags(int flags, int userId) { 4632 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4633 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4634 // Caller expressed an explicit opinion about what encryption 4635 // aware/unaware components they want to see, so fall through and 4636 // give them what they want 4637 } else { 4638 // Caller expressed no opinion, so match based on user state 4639 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4640 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4641 } else { 4642 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4643 } 4644 } 4645 return flags; 4646 } 4647 4648 private UserManagerInternal getUserManagerInternal() { 4649 if (mUserManagerInternal == null) { 4650 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4651 } 4652 return mUserManagerInternal; 4653 } 4654 4655 private ActivityManagerInternal getActivityManagerInternal() { 4656 if (mActivityManagerInternal == null) { 4657 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4658 } 4659 return mActivityManagerInternal; 4660 } 4661 4662 4663 private DeviceIdleController.LocalService getDeviceIdleController() { 4664 if (mDeviceIdleController == null) { 4665 mDeviceIdleController = 4666 LocalServices.getService(DeviceIdleController.LocalService.class); 4667 } 4668 return mDeviceIdleController; 4669 } 4670 4671 /** 4672 * Update given flags when being used to request {@link PackageInfo}. 4673 */ 4674 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4675 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4676 boolean triaged = true; 4677 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4678 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4679 // Caller is asking for component details, so they'd better be 4680 // asking for specific encryption matching behavior, or be triaged 4681 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4682 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4683 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4684 triaged = false; 4685 } 4686 } 4687 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4688 | PackageManager.MATCH_SYSTEM_ONLY 4689 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4690 triaged = false; 4691 } 4692 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4693 mPermissionManager.enforceCrossUserPermission( 4694 Binder.getCallingUid(), userId, false, false, 4695 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4696 + Debug.getCallers(5)); 4697 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4698 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4699 // If the caller wants all packages and has a restricted profile associated with it, 4700 // then match all users. This is to make sure that launchers that need to access work 4701 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4702 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4703 flags |= PackageManager.MATCH_ANY_USER; 4704 } 4705 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4706 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4707 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4708 } 4709 return updateFlags(flags, userId); 4710 } 4711 4712 /** 4713 * Update given flags when being used to request {@link ApplicationInfo}. 4714 */ 4715 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4716 return updateFlagsForPackage(flags, userId, cookie); 4717 } 4718 4719 /** 4720 * Update given flags when being used to request {@link ComponentInfo}. 4721 */ 4722 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4723 if (cookie instanceof Intent) { 4724 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4725 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4726 } 4727 } 4728 4729 boolean triaged = true; 4730 // Caller is asking for component details, so they'd better be 4731 // asking for specific encryption matching behavior, or be triaged 4732 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4733 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4734 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4735 triaged = false; 4736 } 4737 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4738 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4739 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4740 } 4741 4742 return updateFlags(flags, userId); 4743 } 4744 4745 /** 4746 * Update given intent when being used to request {@link ResolveInfo}. 4747 */ 4748 private Intent updateIntentForResolve(Intent intent) { 4749 if (intent.getSelector() != null) { 4750 intent = intent.getSelector(); 4751 } 4752 if (DEBUG_PREFERRED) { 4753 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4754 } 4755 return intent; 4756 } 4757 4758 /** 4759 * Update given flags when being used to request {@link ResolveInfo}. 4760 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4761 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4762 * flag set. However, this flag is only honoured in three circumstances: 4763 * <ul> 4764 * <li>when called from a system process</li> 4765 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4766 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4767 * action and a {@code android.intent.category.BROWSABLE} category</li> 4768 * </ul> 4769 */ 4770 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4771 return updateFlagsForResolve(flags, userId, intent, callingUid, 4772 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4773 } 4774 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4775 boolean wantInstantApps) { 4776 return updateFlagsForResolve(flags, userId, intent, callingUid, 4777 wantInstantApps, false /*onlyExposedExplicitly*/); 4778 } 4779 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4780 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4781 // Safe mode means we shouldn't match any third-party components 4782 if (mSafeMode) { 4783 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4784 } 4785 if (getInstantAppPackageName(callingUid) != null) { 4786 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4787 if (onlyExposedExplicitly) { 4788 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4789 } 4790 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4791 flags |= PackageManager.MATCH_INSTANT; 4792 } else { 4793 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4794 final boolean allowMatchInstant = wantInstantApps 4795 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4796 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4797 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4798 if (!allowMatchInstant) { 4799 flags &= ~PackageManager.MATCH_INSTANT; 4800 } 4801 } 4802 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4803 } 4804 4805 @Override 4806 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4807 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4808 } 4809 4810 /** 4811 * Important: The provided filterCallingUid is used exclusively to filter out activities 4812 * that can be seen based on user state. It's typically the original caller uid prior 4813 * to clearing. Because it can only be provided by trusted code, it's value can be 4814 * trusted and will be used as-is; unlike userId which will be validated by this method. 4815 */ 4816 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4817 int filterCallingUid, int userId) { 4818 if (!sUserManager.exists(userId)) return null; 4819 flags = updateFlagsForComponent(flags, userId, component); 4820 4821 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4822 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4823 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4824 } 4825 4826 synchronized (mPackages) { 4827 PackageParser.Activity a = mActivities.mActivities.get(component); 4828 4829 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4830 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4831 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4832 if (ps == null) return null; 4833 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4834 return null; 4835 } 4836 return PackageParser.generateActivityInfo( 4837 a, flags, ps.readUserState(userId), userId); 4838 } 4839 if (mResolveComponentName.equals(component)) { 4840 return PackageParser.generateActivityInfo( 4841 mResolveActivity, flags, new PackageUserState(), userId); 4842 } 4843 } 4844 return null; 4845 } 4846 4847 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4848 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4849 return false; 4850 } 4851 final long token = Binder.clearCallingIdentity(); 4852 try { 4853 final int callingUserId = UserHandle.getUserId(callingUid); 4854 if (ActivityManager.getCurrentUser() != callingUserId) { 4855 return false; 4856 } 4857 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4858 } finally { 4859 Binder.restoreCallingIdentity(token); 4860 } 4861 } 4862 4863 @Override 4864 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4865 String resolvedType) { 4866 synchronized (mPackages) { 4867 if (component.equals(mResolveComponentName)) { 4868 // The resolver supports EVERYTHING! 4869 return true; 4870 } 4871 final int callingUid = Binder.getCallingUid(); 4872 final int callingUserId = UserHandle.getUserId(callingUid); 4873 PackageParser.Activity a = mActivities.mActivities.get(component); 4874 if (a == null) { 4875 return false; 4876 } 4877 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4878 if (ps == null) { 4879 return false; 4880 } 4881 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4882 return false; 4883 } 4884 for (int i=0; i<a.intents.size(); i++) { 4885 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4886 intent.getData(), intent.getCategories(), TAG) >= 0) { 4887 return true; 4888 } 4889 } 4890 return false; 4891 } 4892 } 4893 4894 @Override 4895 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4896 if (!sUserManager.exists(userId)) return null; 4897 final int callingUid = Binder.getCallingUid(); 4898 flags = updateFlagsForComponent(flags, userId, component); 4899 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4900 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4901 synchronized (mPackages) { 4902 PackageParser.Activity a = mReceivers.mActivities.get(component); 4903 if (DEBUG_PACKAGE_INFO) Log.v( 4904 TAG, "getReceiverInfo " + component + ": " + a); 4905 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4906 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4907 if (ps == null) return null; 4908 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4909 return null; 4910 } 4911 return PackageParser.generateActivityInfo( 4912 a, flags, ps.readUserState(userId), userId); 4913 } 4914 } 4915 return null; 4916 } 4917 4918 @Override 4919 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4920 int flags, int userId) { 4921 if (!sUserManager.exists(userId)) return null; 4922 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4923 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4924 return null; 4925 } 4926 4927 flags = updateFlagsForPackage(flags, userId, null); 4928 4929 final boolean canSeeStaticLibraries = 4930 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4931 == PERMISSION_GRANTED 4932 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4933 == PERMISSION_GRANTED 4934 || canRequestPackageInstallsInternal(packageName, 4935 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4936 false /* throwIfPermNotDeclared*/) 4937 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4938 == PERMISSION_GRANTED; 4939 4940 synchronized (mPackages) { 4941 List<SharedLibraryInfo> result = null; 4942 4943 final int libCount = mSharedLibraries.size(); 4944 for (int i = 0; i < libCount; i++) { 4945 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4946 if (versionedLib == null) { 4947 continue; 4948 } 4949 4950 final int versionCount = versionedLib.size(); 4951 for (int j = 0; j < versionCount; j++) { 4952 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4953 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4954 break; 4955 } 4956 final long identity = Binder.clearCallingIdentity(); 4957 try { 4958 PackageInfo packageInfo = getPackageInfoVersioned( 4959 libInfo.getDeclaringPackage(), flags 4960 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4961 if (packageInfo == null) { 4962 continue; 4963 } 4964 } finally { 4965 Binder.restoreCallingIdentity(identity); 4966 } 4967 4968 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4969 libInfo.getLongVersion(), libInfo.getType(), 4970 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4971 flags, userId)); 4972 4973 if (result == null) { 4974 result = new ArrayList<>(); 4975 } 4976 result.add(resLibInfo); 4977 } 4978 } 4979 4980 return result != null ? new ParceledListSlice<>(result) : null; 4981 } 4982 } 4983 4984 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4985 SharedLibraryInfo libInfo, int flags, int userId) { 4986 List<VersionedPackage> versionedPackages = null; 4987 final int packageCount = mSettings.mPackages.size(); 4988 for (int i = 0; i < packageCount; i++) { 4989 PackageSetting ps = mSettings.mPackages.valueAt(i); 4990 4991 if (ps == null) { 4992 continue; 4993 } 4994 4995 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4996 continue; 4997 } 4998 4999 final String libName = libInfo.getName(); 5000 if (libInfo.isStatic()) { 5001 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5002 if (libIdx < 0) { 5003 continue; 5004 } 5005 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5006 continue; 5007 } 5008 if (versionedPackages == null) { 5009 versionedPackages = new ArrayList<>(); 5010 } 5011 // If the dependent is a static shared lib, use the public package name 5012 String dependentPackageName = ps.name; 5013 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5014 dependentPackageName = ps.pkg.manifestPackageName; 5015 } 5016 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5017 } else if (ps.pkg != null) { 5018 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5019 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5020 if (versionedPackages == null) { 5021 versionedPackages = new ArrayList<>(); 5022 } 5023 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5024 } 5025 } 5026 } 5027 5028 return versionedPackages; 5029 } 5030 5031 @Override 5032 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5033 if (!sUserManager.exists(userId)) return null; 5034 final int callingUid = Binder.getCallingUid(); 5035 flags = updateFlagsForComponent(flags, userId, component); 5036 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5037 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5038 synchronized (mPackages) { 5039 PackageParser.Service s = mServices.mServices.get(component); 5040 if (DEBUG_PACKAGE_INFO) Log.v( 5041 TAG, "getServiceInfo " + component + ": " + s); 5042 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5043 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5044 if (ps == null) return null; 5045 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5046 return null; 5047 } 5048 return PackageParser.generateServiceInfo( 5049 s, flags, ps.readUserState(userId), userId); 5050 } 5051 } 5052 return null; 5053 } 5054 5055 @Override 5056 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5057 if (!sUserManager.exists(userId)) return null; 5058 final int callingUid = Binder.getCallingUid(); 5059 flags = updateFlagsForComponent(flags, userId, component); 5060 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5061 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5062 synchronized (mPackages) { 5063 PackageParser.Provider p = mProviders.mProviders.get(component); 5064 if (DEBUG_PACKAGE_INFO) Log.v( 5065 TAG, "getProviderInfo " + component + ": " + p); 5066 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5067 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5068 if (ps == null) return null; 5069 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5070 return null; 5071 } 5072 return PackageParser.generateProviderInfo( 5073 p, flags, ps.readUserState(userId), userId); 5074 } 5075 } 5076 return null; 5077 } 5078 5079 @Override 5080 public String[] getSystemSharedLibraryNames() { 5081 // allow instant applications 5082 synchronized (mPackages) { 5083 Set<String> libs = null; 5084 final int libCount = mSharedLibraries.size(); 5085 for (int i = 0; i < libCount; i++) { 5086 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5087 if (versionedLib == null) { 5088 continue; 5089 } 5090 final int versionCount = versionedLib.size(); 5091 for (int j = 0; j < versionCount; j++) { 5092 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5093 if (!libEntry.info.isStatic()) { 5094 if (libs == null) { 5095 libs = new ArraySet<>(); 5096 } 5097 libs.add(libEntry.info.getName()); 5098 break; 5099 } 5100 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5101 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5102 UserHandle.getUserId(Binder.getCallingUid()), 5103 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5104 if (libs == null) { 5105 libs = new ArraySet<>(); 5106 } 5107 libs.add(libEntry.info.getName()); 5108 break; 5109 } 5110 } 5111 } 5112 5113 if (libs != null) { 5114 String[] libsArray = new String[libs.size()]; 5115 libs.toArray(libsArray); 5116 return libsArray; 5117 } 5118 5119 return null; 5120 } 5121 } 5122 5123 @Override 5124 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5125 // allow instant applications 5126 synchronized (mPackages) { 5127 return mServicesSystemSharedLibraryPackageName; 5128 } 5129 } 5130 5131 @Override 5132 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5133 // allow instant applications 5134 synchronized (mPackages) { 5135 return mSharedSystemSharedLibraryPackageName; 5136 } 5137 } 5138 5139 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5140 for (int i = userList.length - 1; i >= 0; --i) { 5141 final int userId = userList[i]; 5142 // don't add instant app to the list of updates 5143 if (pkgSetting.getInstantApp(userId)) { 5144 continue; 5145 } 5146 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5147 if (changedPackages == null) { 5148 changedPackages = new SparseArray<>(); 5149 mChangedPackages.put(userId, changedPackages); 5150 } 5151 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5152 if (sequenceNumbers == null) { 5153 sequenceNumbers = new HashMap<>(); 5154 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5155 } 5156 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5157 if (sequenceNumber != null) { 5158 changedPackages.remove(sequenceNumber); 5159 } 5160 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5161 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5162 } 5163 mChangedPackagesSequenceNumber++; 5164 } 5165 5166 @Override 5167 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5168 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5169 return null; 5170 } 5171 synchronized (mPackages) { 5172 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5173 return null; 5174 } 5175 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5176 if (changedPackages == null) { 5177 return null; 5178 } 5179 final List<String> packageNames = 5180 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5181 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5182 final String packageName = changedPackages.get(i); 5183 if (packageName != null) { 5184 packageNames.add(packageName); 5185 } 5186 } 5187 return packageNames.isEmpty() 5188 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5189 } 5190 } 5191 5192 @Override 5193 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5194 // allow instant applications 5195 ArrayList<FeatureInfo> res; 5196 synchronized (mAvailableFeatures) { 5197 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5198 res.addAll(mAvailableFeatures.values()); 5199 } 5200 final FeatureInfo fi = new FeatureInfo(); 5201 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5202 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5203 res.add(fi); 5204 5205 return new ParceledListSlice<>(res); 5206 } 5207 5208 @Override 5209 public boolean hasSystemFeature(String name, int version) { 5210 // allow instant applications 5211 synchronized (mAvailableFeatures) { 5212 final FeatureInfo feat = mAvailableFeatures.get(name); 5213 if (feat == null) { 5214 return false; 5215 } else { 5216 return feat.version >= version; 5217 } 5218 } 5219 } 5220 5221 @Override 5222 public int checkPermission(String permName, String pkgName, int userId) { 5223 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5224 } 5225 5226 @Override 5227 public int checkUidPermission(String permName, int uid) { 5228 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5229 } 5230 5231 @Override 5232 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5233 if (UserHandle.getCallingUserId() != userId) { 5234 mContext.enforceCallingPermission( 5235 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5236 "isPermissionRevokedByPolicy for user " + userId); 5237 } 5238 5239 if (checkPermission(permission, packageName, userId) 5240 == PackageManager.PERMISSION_GRANTED) { 5241 return false; 5242 } 5243 5244 final int callingUid = Binder.getCallingUid(); 5245 if (getInstantAppPackageName(callingUid) != null) { 5246 if (!isCallerSameApp(packageName, callingUid)) { 5247 return false; 5248 } 5249 } else { 5250 if (isInstantApp(packageName, userId)) { 5251 return false; 5252 } 5253 } 5254 5255 final long identity = Binder.clearCallingIdentity(); 5256 try { 5257 final int flags = getPermissionFlags(permission, packageName, userId); 5258 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5259 } finally { 5260 Binder.restoreCallingIdentity(identity); 5261 } 5262 } 5263 5264 @Override 5265 public String getPermissionControllerPackageName() { 5266 synchronized (mPackages) { 5267 return mRequiredInstallerPackage; 5268 } 5269 } 5270 5271 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5272 return mPermissionManager.addDynamicPermission( 5273 info, async, getCallingUid(), new PermissionCallback() { 5274 @Override 5275 public void onPermissionChanged() { 5276 if (!async) { 5277 mSettings.writeLPr(); 5278 } else { 5279 scheduleWriteSettingsLocked(); 5280 } 5281 } 5282 }); 5283 } 5284 5285 @Override 5286 public boolean addPermission(PermissionInfo info) { 5287 synchronized (mPackages) { 5288 return addDynamicPermission(info, false); 5289 } 5290 } 5291 5292 @Override 5293 public boolean addPermissionAsync(PermissionInfo info) { 5294 synchronized (mPackages) { 5295 return addDynamicPermission(info, true); 5296 } 5297 } 5298 5299 @Override 5300 public void removePermission(String permName) { 5301 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5302 } 5303 5304 @Override 5305 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5306 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5307 getCallingUid(), userId, mPermissionCallback); 5308 } 5309 5310 @Override 5311 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5312 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5313 getCallingUid(), userId, mPermissionCallback); 5314 } 5315 5316 @Override 5317 public void resetRuntimePermissions() { 5318 mContext.enforceCallingOrSelfPermission( 5319 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5320 "revokeRuntimePermission"); 5321 5322 int callingUid = Binder.getCallingUid(); 5323 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5324 mContext.enforceCallingOrSelfPermission( 5325 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5326 "resetRuntimePermissions"); 5327 } 5328 5329 synchronized (mPackages) { 5330 mPermissionManager.updateAllPermissions( 5331 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5332 mPermissionCallback); 5333 for (int userId : UserManagerService.getInstance().getUserIds()) { 5334 final int packageCount = mPackages.size(); 5335 for (int i = 0; i < packageCount; i++) { 5336 PackageParser.Package pkg = mPackages.valueAt(i); 5337 if (!(pkg.mExtras instanceof PackageSetting)) { 5338 continue; 5339 } 5340 PackageSetting ps = (PackageSetting) pkg.mExtras; 5341 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5342 } 5343 } 5344 } 5345 } 5346 5347 @Override 5348 public int getPermissionFlags(String permName, String packageName, int userId) { 5349 return mPermissionManager.getPermissionFlags( 5350 permName, packageName, getCallingUid(), userId); 5351 } 5352 5353 @Override 5354 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5355 int flagValues, int userId) { 5356 mPermissionManager.updatePermissionFlags( 5357 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5358 mPermissionCallback); 5359 } 5360 5361 /** 5362 * Update the permission flags for all packages and runtime permissions of a user in order 5363 * to allow device or profile owner to remove POLICY_FIXED. 5364 */ 5365 @Override 5366 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5367 synchronized (mPackages) { 5368 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5369 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5370 mPermissionCallback); 5371 if (changed) { 5372 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5373 } 5374 } 5375 } 5376 5377 @Override 5378 public boolean shouldShowRequestPermissionRationale(String permissionName, 5379 String packageName, int userId) { 5380 if (UserHandle.getCallingUserId() != userId) { 5381 mContext.enforceCallingPermission( 5382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5383 "canShowRequestPermissionRationale for user " + userId); 5384 } 5385 5386 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5387 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5388 return false; 5389 } 5390 5391 if (checkPermission(permissionName, packageName, userId) 5392 == PackageManager.PERMISSION_GRANTED) { 5393 return false; 5394 } 5395 5396 final int flags; 5397 5398 final long identity = Binder.clearCallingIdentity(); 5399 try { 5400 flags = getPermissionFlags(permissionName, 5401 packageName, userId); 5402 } finally { 5403 Binder.restoreCallingIdentity(identity); 5404 } 5405 5406 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5407 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5408 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5409 5410 if ((flags & fixedFlags) != 0) { 5411 return false; 5412 } 5413 5414 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5415 } 5416 5417 @Override 5418 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5419 mContext.enforceCallingOrSelfPermission( 5420 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5421 "addOnPermissionsChangeListener"); 5422 5423 synchronized (mPackages) { 5424 mOnPermissionChangeListeners.addListenerLocked(listener); 5425 } 5426 } 5427 5428 @Override 5429 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5430 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5431 throw new SecurityException("Instant applications don't have access to this method"); 5432 } 5433 synchronized (mPackages) { 5434 mOnPermissionChangeListeners.removeListenerLocked(listener); 5435 } 5436 } 5437 5438 @Override 5439 public boolean isProtectedBroadcast(String actionName) { 5440 // allow instant applications 5441 synchronized (mProtectedBroadcasts) { 5442 if (mProtectedBroadcasts.contains(actionName)) { 5443 return true; 5444 } else if (actionName != null) { 5445 // TODO: remove these terrible hacks 5446 if (actionName.startsWith("android.net.netmon.lingerExpired") 5447 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5448 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5449 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5450 return true; 5451 } 5452 } 5453 } 5454 return false; 5455 } 5456 5457 @Override 5458 public int checkSignatures(String pkg1, String pkg2) { 5459 synchronized (mPackages) { 5460 final PackageParser.Package p1 = mPackages.get(pkg1); 5461 final PackageParser.Package p2 = mPackages.get(pkg2); 5462 if (p1 == null || p1.mExtras == null 5463 || p2 == null || p2.mExtras == null) { 5464 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5465 } 5466 final int callingUid = Binder.getCallingUid(); 5467 final int callingUserId = UserHandle.getUserId(callingUid); 5468 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5469 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5470 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5471 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5472 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5473 } 5474 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5475 } 5476 } 5477 5478 @Override 5479 public int checkUidSignatures(int uid1, int uid2) { 5480 final int callingUid = Binder.getCallingUid(); 5481 final int callingUserId = UserHandle.getUserId(callingUid); 5482 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5483 // Map to base uids. 5484 uid1 = UserHandle.getAppId(uid1); 5485 uid2 = UserHandle.getAppId(uid2); 5486 // reader 5487 synchronized (mPackages) { 5488 Signature[] s1; 5489 Signature[] s2; 5490 Object obj = mSettings.getUserIdLPr(uid1); 5491 if (obj != null) { 5492 if (obj instanceof SharedUserSetting) { 5493 if (isCallerInstantApp) { 5494 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5495 } 5496 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5497 } else if (obj instanceof PackageSetting) { 5498 final PackageSetting ps = (PackageSetting) obj; 5499 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5500 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5501 } 5502 s1 = ps.signatures.mSigningDetails.signatures; 5503 } else { 5504 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5505 } 5506 } else { 5507 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5508 } 5509 obj = mSettings.getUserIdLPr(uid2); 5510 if (obj != null) { 5511 if (obj instanceof SharedUserSetting) { 5512 if (isCallerInstantApp) { 5513 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5514 } 5515 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5516 } else if (obj instanceof PackageSetting) { 5517 final PackageSetting ps = (PackageSetting) obj; 5518 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5519 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5520 } 5521 s2 = ps.signatures.mSigningDetails.signatures; 5522 } else { 5523 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5524 } 5525 } else { 5526 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5527 } 5528 return compareSignatures(s1, s2); 5529 } 5530 } 5531 5532 @Override 5533 public boolean hasSigningCertificate( 5534 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5535 5536 synchronized (mPackages) { 5537 final PackageParser.Package p = mPackages.get(packageName); 5538 if (p == null || p.mExtras == null) { 5539 return false; 5540 } 5541 final int callingUid = Binder.getCallingUid(); 5542 final int callingUserId = UserHandle.getUserId(callingUid); 5543 final PackageSetting ps = (PackageSetting) p.mExtras; 5544 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5545 return false; 5546 } 5547 switch (type) { 5548 case CERT_INPUT_RAW_X509: 5549 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5550 case CERT_INPUT_SHA256: 5551 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5552 default: 5553 return false; 5554 } 5555 } 5556 } 5557 5558 @Override 5559 public boolean hasUidSigningCertificate( 5560 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5561 final int callingUid = Binder.getCallingUid(); 5562 final int callingUserId = UserHandle.getUserId(callingUid); 5563 // Map to base uids. 5564 uid = UserHandle.getAppId(uid); 5565 // reader 5566 synchronized (mPackages) { 5567 final PackageParser.SigningDetails signingDetails; 5568 final Object obj = mSettings.getUserIdLPr(uid); 5569 if (obj != null) { 5570 if (obj instanceof SharedUserSetting) { 5571 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5572 if (isCallerInstantApp) { 5573 return false; 5574 } 5575 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5576 } else if (obj instanceof PackageSetting) { 5577 final PackageSetting ps = (PackageSetting) obj; 5578 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5579 return false; 5580 } 5581 signingDetails = ps.signatures.mSigningDetails; 5582 } else { 5583 return false; 5584 } 5585 } else { 5586 return false; 5587 } 5588 switch (type) { 5589 case CERT_INPUT_RAW_X509: 5590 return signingDetailsHasCertificate(certificate, signingDetails); 5591 case CERT_INPUT_SHA256: 5592 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5593 default: 5594 return false; 5595 } 5596 } 5597 } 5598 5599 /** 5600 * This method should typically only be used when granting or revoking 5601 * permissions, since the app may immediately restart after this call. 5602 * <p> 5603 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5604 * guard your work against the app being relaunched. 5605 */ 5606 private void killUid(int appId, int userId, String reason) { 5607 final long identity = Binder.clearCallingIdentity(); 5608 try { 5609 IActivityManager am = ActivityManager.getService(); 5610 if (am != null) { 5611 try { 5612 am.killUid(appId, userId, reason); 5613 } catch (RemoteException e) { 5614 /* ignore - same process */ 5615 } 5616 } 5617 } finally { 5618 Binder.restoreCallingIdentity(identity); 5619 } 5620 } 5621 5622 /** 5623 * If the database version for this type of package (internal storage or 5624 * external storage) is less than the version where package signatures 5625 * were updated, return true. 5626 */ 5627 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5628 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5629 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5630 } 5631 5632 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5633 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5634 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5635 } 5636 5637 @Override 5638 public List<String> getAllPackages() { 5639 final int callingUid = Binder.getCallingUid(); 5640 final int callingUserId = UserHandle.getUserId(callingUid); 5641 synchronized (mPackages) { 5642 if (canViewInstantApps(callingUid, callingUserId)) { 5643 return new ArrayList<String>(mPackages.keySet()); 5644 } 5645 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5646 final List<String> result = new ArrayList<>(); 5647 if (instantAppPkgName != null) { 5648 // caller is an instant application; filter unexposed applications 5649 for (PackageParser.Package pkg : mPackages.values()) { 5650 if (!pkg.visibleToInstantApps) { 5651 continue; 5652 } 5653 result.add(pkg.packageName); 5654 } 5655 } else { 5656 // caller is a normal application; filter instant applications 5657 for (PackageParser.Package pkg : mPackages.values()) { 5658 final PackageSetting ps = 5659 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5660 if (ps != null 5661 && ps.getInstantApp(callingUserId) 5662 && !mInstantAppRegistry.isInstantAccessGranted( 5663 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5664 continue; 5665 } 5666 result.add(pkg.packageName); 5667 } 5668 } 5669 return result; 5670 } 5671 } 5672 5673 @Override 5674 public String[] getPackagesForUid(int uid) { 5675 final int callingUid = Binder.getCallingUid(); 5676 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5677 final int userId = UserHandle.getUserId(uid); 5678 uid = UserHandle.getAppId(uid); 5679 // reader 5680 synchronized (mPackages) { 5681 Object obj = mSettings.getUserIdLPr(uid); 5682 if (obj instanceof SharedUserSetting) { 5683 if (isCallerInstantApp) { 5684 return null; 5685 } 5686 final SharedUserSetting sus = (SharedUserSetting) obj; 5687 final int N = sus.packages.size(); 5688 String[] res = new String[N]; 5689 final Iterator<PackageSetting> it = sus.packages.iterator(); 5690 int i = 0; 5691 while (it.hasNext()) { 5692 PackageSetting ps = it.next(); 5693 if (ps.getInstalled(userId)) { 5694 res[i++] = ps.name; 5695 } else { 5696 res = ArrayUtils.removeElement(String.class, res, res[i]); 5697 } 5698 } 5699 return res; 5700 } else if (obj instanceof PackageSetting) { 5701 final PackageSetting ps = (PackageSetting) obj; 5702 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5703 return new String[]{ps.name}; 5704 } 5705 } 5706 } 5707 return null; 5708 } 5709 5710 @Override 5711 public String getNameForUid(int uid) { 5712 final int callingUid = Binder.getCallingUid(); 5713 if (getInstantAppPackageName(callingUid) != null) { 5714 return null; 5715 } 5716 synchronized (mPackages) { 5717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5718 if (obj instanceof SharedUserSetting) { 5719 final SharedUserSetting sus = (SharedUserSetting) obj; 5720 return sus.name + ":" + sus.userId; 5721 } else if (obj instanceof PackageSetting) { 5722 final PackageSetting ps = (PackageSetting) obj; 5723 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5724 return null; 5725 } 5726 return ps.name; 5727 } 5728 return null; 5729 } 5730 } 5731 5732 @Override 5733 public String[] getNamesForUids(int[] uids) { 5734 if (uids == null || uids.length == 0) { 5735 return null; 5736 } 5737 final int callingUid = Binder.getCallingUid(); 5738 if (getInstantAppPackageName(callingUid) != null) { 5739 return null; 5740 } 5741 final String[] names = new String[uids.length]; 5742 synchronized (mPackages) { 5743 for (int i = uids.length - 1; i >= 0; i--) { 5744 final int uid = uids[i]; 5745 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5746 if (obj instanceof SharedUserSetting) { 5747 final SharedUserSetting sus = (SharedUserSetting) obj; 5748 names[i] = "shared:" + sus.name; 5749 } else if (obj instanceof PackageSetting) { 5750 final PackageSetting ps = (PackageSetting) obj; 5751 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5752 names[i] = null; 5753 } else { 5754 names[i] = ps.name; 5755 } 5756 } else { 5757 names[i] = null; 5758 } 5759 } 5760 } 5761 return names; 5762 } 5763 5764 @Override 5765 public int getUidForSharedUser(String sharedUserName) { 5766 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5767 return -1; 5768 } 5769 if (sharedUserName == null) { 5770 return -1; 5771 } 5772 // reader 5773 synchronized (mPackages) { 5774 SharedUserSetting suid; 5775 try { 5776 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5777 if (suid != null) { 5778 return suid.userId; 5779 } 5780 } catch (PackageManagerException ignore) { 5781 // can't happen, but, still need to catch it 5782 } 5783 return -1; 5784 } 5785 } 5786 5787 @Override 5788 public int getFlagsForUid(int uid) { 5789 final int callingUid = Binder.getCallingUid(); 5790 if (getInstantAppPackageName(callingUid) != null) { 5791 return 0; 5792 } 5793 synchronized (mPackages) { 5794 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5795 if (obj instanceof SharedUserSetting) { 5796 final SharedUserSetting sus = (SharedUserSetting) obj; 5797 return sus.pkgFlags; 5798 } else if (obj instanceof PackageSetting) { 5799 final PackageSetting ps = (PackageSetting) obj; 5800 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5801 return 0; 5802 } 5803 return ps.pkgFlags; 5804 } 5805 } 5806 return 0; 5807 } 5808 5809 @Override 5810 public int getPrivateFlagsForUid(int uid) { 5811 final int callingUid = Binder.getCallingUid(); 5812 if (getInstantAppPackageName(callingUid) != null) { 5813 return 0; 5814 } 5815 synchronized (mPackages) { 5816 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5817 if (obj instanceof SharedUserSetting) { 5818 final SharedUserSetting sus = (SharedUserSetting) obj; 5819 return sus.pkgPrivateFlags; 5820 } else if (obj instanceof PackageSetting) { 5821 final PackageSetting ps = (PackageSetting) obj; 5822 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5823 return 0; 5824 } 5825 return ps.pkgPrivateFlags; 5826 } 5827 } 5828 return 0; 5829 } 5830 5831 @Override 5832 public boolean isUidPrivileged(int uid) { 5833 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5834 return false; 5835 } 5836 uid = UserHandle.getAppId(uid); 5837 // reader 5838 synchronized (mPackages) { 5839 Object obj = mSettings.getUserIdLPr(uid); 5840 if (obj instanceof SharedUserSetting) { 5841 final SharedUserSetting sus = (SharedUserSetting) obj; 5842 final Iterator<PackageSetting> it = sus.packages.iterator(); 5843 while (it.hasNext()) { 5844 if (it.next().isPrivileged()) { 5845 return true; 5846 } 5847 } 5848 } else if (obj instanceof PackageSetting) { 5849 final PackageSetting ps = (PackageSetting) obj; 5850 return ps.isPrivileged(); 5851 } 5852 } 5853 return false; 5854 } 5855 5856 @Override 5857 public String[] getAppOpPermissionPackages(String permName) { 5858 return mPermissionManager.getAppOpPermissionPackages(permName); 5859 } 5860 5861 @Override 5862 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5863 int flags, int userId) { 5864 return resolveIntentInternal( 5865 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5866 } 5867 5868 /** 5869 * Normally instant apps can only be resolved when they're visible to the caller. 5870 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5871 * since we need to allow the system to start any installed application. 5872 */ 5873 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5874 int flags, int userId, boolean resolveForStart) { 5875 try { 5876 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5877 5878 if (!sUserManager.exists(userId)) return null; 5879 final int callingUid = Binder.getCallingUid(); 5880 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5881 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5882 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5883 5884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5885 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5886 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5888 5889 final ResolveInfo bestChoice = 5890 chooseBestActivity(intent, resolvedType, flags, query, userId); 5891 return bestChoice; 5892 } finally { 5893 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5894 } 5895 } 5896 5897 @Override 5898 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5899 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5900 throw new SecurityException( 5901 "findPersistentPreferredActivity can only be run by the system"); 5902 } 5903 if (!sUserManager.exists(userId)) { 5904 return null; 5905 } 5906 final int callingUid = Binder.getCallingUid(); 5907 intent = updateIntentForResolve(intent); 5908 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5909 final int flags = updateFlagsForResolve( 5910 0, userId, intent, callingUid, false /*includeInstantApps*/); 5911 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5912 userId); 5913 synchronized (mPackages) { 5914 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5915 userId); 5916 } 5917 } 5918 5919 @Override 5920 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5921 IntentFilter filter, int match, ComponentName activity) { 5922 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5923 return; 5924 } 5925 final int userId = UserHandle.getCallingUserId(); 5926 if (DEBUG_PREFERRED) { 5927 Log.v(TAG, "setLastChosenActivity intent=" + intent 5928 + " resolvedType=" + resolvedType 5929 + " flags=" + flags 5930 + " filter=" + filter 5931 + " match=" + match 5932 + " activity=" + activity); 5933 filter.dump(new PrintStreamPrinter(System.out), " "); 5934 } 5935 intent.setComponent(null); 5936 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5937 userId); 5938 // Find any earlier preferred or last chosen entries and nuke them 5939 findPreferredActivity(intent, resolvedType, 5940 flags, query, 0, false, true, false, userId); 5941 // Add the new activity as the last chosen for this filter 5942 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5943 "Setting last chosen"); 5944 } 5945 5946 @Override 5947 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5948 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5949 return null; 5950 } 5951 final int userId = UserHandle.getCallingUserId(); 5952 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5953 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5954 userId); 5955 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5956 false, false, false, userId); 5957 } 5958 5959 /** 5960 * Returns whether or not instant apps have been disabled remotely. 5961 */ 5962 private boolean isEphemeralDisabled() { 5963 return mEphemeralAppsDisabled; 5964 } 5965 5966 private boolean isInstantAppAllowed( 5967 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5968 boolean skipPackageCheck) { 5969 if (mInstantAppResolverConnection == null) { 5970 return false; 5971 } 5972 if (mInstantAppInstallerActivity == null) { 5973 return false; 5974 } 5975 if (intent.getComponent() != null) { 5976 return false; 5977 } 5978 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5979 return false; 5980 } 5981 if (!skipPackageCheck && intent.getPackage() != null) { 5982 return false; 5983 } 5984 if (!intent.isBrowsableWebIntent()) { 5985 // for non web intents, we should not resolve externally if an app already exists to 5986 // handle it or if the caller didn't explicitly request it. 5987 if ((resolvedActivities != null && resolvedActivities.size() != 0) 5988 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 5989 return false; 5990 } 5991 } else if (intent.getData() == null) { 5992 return false; 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_EPHEMERAL) { 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_EPHEMERAL) { 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); 6524 } 6525 6526 // reader 6527 boolean sortResult = false; 6528 boolean addEphemeral = false; 6529 List<ResolveInfo> result; 6530 final boolean ephemeralDisabled = isEphemeralDisabled(); 6531 synchronized (mPackages) { 6532 if (pkgName == null) { 6533 List<CrossProfileIntentFilter> matchingFilters = 6534 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6535 // Check for results that need to skip the current profile. 6536 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6537 resolvedType, flags, userId); 6538 if (xpResolveInfo != null) { 6539 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6540 xpResult.add(xpResolveInfo); 6541 return applyPostResolutionFilter( 6542 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6543 allowDynamicSplits, filterCallingUid, userId); 6544 } 6545 6546 // Check for results in the current profile. 6547 result = filterIfNotSystemUser(mActivities.queryIntent( 6548 intent, resolvedType, flags, userId), userId); 6549 addEphemeral = !ephemeralDisabled 6550 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6551 // Check for cross profile results. 6552 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6553 xpResolveInfo = queryCrossProfileIntents( 6554 matchingFilters, intent, resolvedType, flags, userId, 6555 hasNonNegativePriorityResult); 6556 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6557 boolean isVisibleToUser = filterIfNotSystemUser( 6558 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6559 if (isVisibleToUser) { 6560 result.add(xpResolveInfo); 6561 sortResult = true; 6562 } 6563 } 6564 if (intent.hasWebURI()) { 6565 CrossProfileDomainInfo xpDomainInfo = null; 6566 final UserInfo parent = getProfileParent(userId); 6567 if (parent != null) { 6568 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6569 flags, userId, parent.id); 6570 } 6571 if (xpDomainInfo != null) { 6572 if (xpResolveInfo != null) { 6573 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6574 // in the result. 6575 result.remove(xpResolveInfo); 6576 } 6577 if (result.size() == 0 && !addEphemeral) { 6578 // No result in current profile, but found candidate in parent user. 6579 // And we are not going to add emphemeral app, so we can return the 6580 // result straight away. 6581 result.add(xpDomainInfo.resolveInfo); 6582 return applyPostResolutionFilter(result, instantAppPkgName, 6583 allowDynamicSplits, filterCallingUid, userId); 6584 } 6585 } else if (result.size() <= 1 && !addEphemeral) { 6586 // No result in parent user and <= 1 result in current profile, and we 6587 // are not going to add emphemeral app, so we can return the result without 6588 // further processing. 6589 return applyPostResolutionFilter(result, instantAppPkgName, 6590 allowDynamicSplits, filterCallingUid, userId); 6591 } 6592 // We have more than one candidate (combining results from current and parent 6593 // profile), so we need filtering and sorting. 6594 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6595 intent, flags, result, xpDomainInfo, userId); 6596 sortResult = true; 6597 } 6598 } else { 6599 final PackageParser.Package pkg = mPackages.get(pkgName); 6600 result = null; 6601 if (pkg != null) { 6602 result = filterIfNotSystemUser( 6603 mActivities.queryIntentForPackage( 6604 intent, resolvedType, flags, pkg.activities, userId), 6605 userId); 6606 } 6607 if (result == null || result.size() == 0) { 6608 // the caller wants to resolve for a particular package; however, there 6609 // were no installed results, so, try to find an ephemeral result 6610 addEphemeral = !ephemeralDisabled 6611 && isInstantAppAllowed( 6612 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6613 if (result == null) { 6614 result = new ArrayList<>(); 6615 } 6616 } 6617 } 6618 } 6619 if (addEphemeral) { 6620 result = maybeAddInstantAppInstaller( 6621 result, intent, resolvedType, flags, userId, resolveForStart); 6622 } 6623 if (sortResult) { 6624 Collections.sort(result, mResolvePrioritySorter); 6625 } 6626 return applyPostResolutionFilter( 6627 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6628 } 6629 6630 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6631 String resolvedType, int flags, int userId, boolean resolveForStart) { 6632 // first, check to see if we've got an instant app already installed 6633 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6634 ResolveInfo localInstantApp = null; 6635 boolean blockResolution = false; 6636 if (!alreadyResolvedLocally) { 6637 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6638 flags 6639 | PackageManager.GET_RESOLVED_FILTER 6640 | PackageManager.MATCH_INSTANT 6641 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6642 userId); 6643 for (int i = instantApps.size() - 1; i >= 0; --i) { 6644 final ResolveInfo info = instantApps.get(i); 6645 final String packageName = info.activityInfo.packageName; 6646 final PackageSetting ps = mSettings.mPackages.get(packageName); 6647 if (ps.getInstantApp(userId)) { 6648 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6649 final int status = (int)(packedStatus >> 32); 6650 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6651 // there's a local instant application installed, but, the user has 6652 // chosen to never use it; skip resolution and don't acknowledge 6653 // an instant application is even available 6654 if (DEBUG_EPHEMERAL) { 6655 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6656 } 6657 blockResolution = true; 6658 break; 6659 } else { 6660 // we have a locally installed instant application; skip resolution 6661 // but acknowledge there's an instant application available 6662 if (DEBUG_EPHEMERAL) { 6663 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6664 } 6665 localInstantApp = info; 6666 break; 6667 } 6668 } 6669 } 6670 } 6671 // no app installed, let's see if one's available 6672 AuxiliaryResolveInfo auxiliaryResponse = null; 6673 if (!blockResolution) { 6674 if (localInstantApp == null) { 6675 // we don't have an instant app locally, resolve externally 6676 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6677 final InstantAppRequest requestObject = new InstantAppRequest( 6678 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6679 null /*callingPackage*/, userId, null /*verificationBundle*/, 6680 resolveForStart); 6681 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6682 mInstantAppResolverConnection, requestObject); 6683 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6684 } else { 6685 // we have an instant application locally, but, we can't admit that since 6686 // callers shouldn't be able to determine prior browsing. create a dummy 6687 // auxiliary response so the downstream code behaves as if there's an 6688 // instant application available externally. when it comes time to start 6689 // the instant application, we'll do the right thing. 6690 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6691 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6692 ai.packageName, ai.versionCode, null /* splitName */); 6693 } 6694 } 6695 if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) { 6696 return result; 6697 } 6698 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6699 if (ps == null) { 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_EPHEMERAL) { 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 * @return A filtered list of resolved activities. 6832 */ 6833 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6834 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6835 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6836 final ResolveInfo info = resolveInfos.get(i); 6837 // allow activities that are defined in the provided package 6838 if (allowDynamicSplits 6839 && info.activityInfo != null 6840 && info.activityInfo.splitName != null 6841 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6842 info.activityInfo.splitName)) { 6843 if (mInstantAppInstallerActivity == null) { 6844 if (DEBUG_INSTALL) { 6845 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6846 } 6847 resolveInfos.remove(i); 6848 continue; 6849 } 6850 // requested activity is defined in a split that hasn't been installed yet. 6851 // add the installer to the resolve list 6852 if (DEBUG_INSTALL) { 6853 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6854 } 6855 final ResolveInfo installerInfo = new ResolveInfo( 6856 mInstantAppInstallerInfo); 6857 final ComponentName installFailureActivity = findInstallFailureActivity( 6858 info.activityInfo.packageName, filterCallingUid, userId); 6859 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6860 installFailureActivity, 6861 info.activityInfo.packageName, 6862 info.activityInfo.applicationInfo.versionCode, 6863 info.activityInfo.splitName); 6864 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6865 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6866 // add a non-generic filter 6867 installerInfo.filter = new IntentFilter(); 6868 6869 // This resolve info may appear in the chooser UI, so let us make it 6870 // look as the one it replaces as far as the user is concerned which 6871 // requires loading the correct label and icon for the resolve info. 6872 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6873 installerInfo.labelRes = info.resolveLabelResId(); 6874 installerInfo.icon = info.resolveIconResId(); 6875 6876 // propagate priority/preferred order/default 6877 installerInfo.priority = info.priority; 6878 installerInfo.preferredOrder = info.preferredOrder; 6879 installerInfo.isDefault = info.isDefault; 6880 installerInfo.isInstantAppAvailable = true; 6881 resolveInfos.set(i, installerInfo); 6882 continue; 6883 } 6884 // caller is a full app, don't need to apply any other filtering 6885 if (ephemeralPkgName == null) { 6886 continue; 6887 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6888 // caller is same app; don't need to apply any other filtering 6889 continue; 6890 } 6891 // allow activities that have been explicitly exposed to ephemeral apps 6892 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6893 if (!isEphemeralApp 6894 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6895 continue; 6896 } 6897 resolveInfos.remove(i); 6898 } 6899 return resolveInfos; 6900 } 6901 6902 /** 6903 * Returns the activity component that can handle install failures. 6904 * <p>By default, the instant application installer handles failures. However, an 6905 * application may want to handle failures on its own. Applications do this by 6906 * creating an activity with an intent filter that handles the action 6907 * {@link Intent#ACTION_INSTALL_FAILURE}. 6908 */ 6909 private @Nullable ComponentName findInstallFailureActivity( 6910 String packageName, int filterCallingUid, int userId) { 6911 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6912 failureActivityIntent.setPackage(packageName); 6913 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6914 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6915 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6916 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6917 final int NR = result.size(); 6918 if (NR > 0) { 6919 for (int i = 0; i < NR; i++) { 6920 final ResolveInfo info = result.get(i); 6921 if (info.activityInfo.splitName != null) { 6922 continue; 6923 } 6924 return new ComponentName(packageName, info.activityInfo.name); 6925 } 6926 } 6927 return null; 6928 } 6929 6930 /** 6931 * @param resolveInfos list of resolve infos in descending priority order 6932 * @return if the list contains a resolve info with non-negative priority 6933 */ 6934 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6935 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6936 } 6937 6938 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6939 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6940 int userId) { 6941 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6942 6943 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6944 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6945 candidates.size()); 6946 } 6947 6948 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6949 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6950 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6951 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6952 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6953 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6954 6955 synchronized (mPackages) { 6956 final int count = candidates.size(); 6957 // First, try to use linked apps. Partition the candidates into four lists: 6958 // one for the final results, one for the "do not use ever", one for "undefined status" 6959 // and finally one for "browser app type". 6960 for (int n=0; n<count; n++) { 6961 ResolveInfo info = candidates.get(n); 6962 String packageName = info.activityInfo.packageName; 6963 PackageSetting ps = mSettings.mPackages.get(packageName); 6964 if (ps != null) { 6965 // Add to the special match all list (Browser use case) 6966 if (info.handleAllWebDataURI) { 6967 matchAllList.add(info); 6968 continue; 6969 } 6970 // Try to get the status from User settings first 6971 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6972 int status = (int)(packedStatus >> 32); 6973 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6974 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6975 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6976 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6977 + " : linkgen=" + linkGeneration); 6978 } 6979 // Use link-enabled generation as preferredOrder, i.e. 6980 // prefer newly-enabled over earlier-enabled. 6981 info.preferredOrder = linkGeneration; 6982 alwaysList.add(info); 6983 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6984 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6985 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6986 } 6987 neverList.add(info); 6988 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6989 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6990 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6991 } 6992 alwaysAskList.add(info); 6993 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6994 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6995 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6996 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6997 } 6998 undefinedList.add(info); 6999 } 7000 } 7001 } 7002 7003 // We'll want to include browser possibilities in a few cases 7004 boolean includeBrowser = false; 7005 7006 // First try to add the "always" resolution(s) for the current user, if any 7007 if (alwaysList.size() > 0) { 7008 result.addAll(alwaysList); 7009 } else { 7010 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7011 result.addAll(undefinedList); 7012 // Maybe add one for the other profile. 7013 if (xpDomainInfo != null && ( 7014 xpDomainInfo.bestDomainVerificationStatus 7015 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7016 result.add(xpDomainInfo.resolveInfo); 7017 } 7018 includeBrowser = true; 7019 } 7020 7021 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7022 // If there were 'always' entries their preferred order has been set, so we also 7023 // back that off to make the alternatives equivalent 7024 if (alwaysAskList.size() > 0) { 7025 for (ResolveInfo i : result) { 7026 i.preferredOrder = 0; 7027 } 7028 result.addAll(alwaysAskList); 7029 includeBrowser = true; 7030 } 7031 7032 if (includeBrowser) { 7033 // Also add browsers (all of them or only the default one) 7034 if (DEBUG_DOMAIN_VERIFICATION) { 7035 Slog.v(TAG, " ...including browsers in candidate set"); 7036 } 7037 if ((matchFlags & MATCH_ALL) != 0) { 7038 result.addAll(matchAllList); 7039 } else { 7040 // Browser/generic handling case. If there's a default browser, go straight 7041 // to that (but only if there is no other higher-priority match). 7042 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7043 int maxMatchPrio = 0; 7044 ResolveInfo defaultBrowserMatch = null; 7045 final int numCandidates = matchAllList.size(); 7046 for (int n = 0; n < numCandidates; n++) { 7047 ResolveInfo info = matchAllList.get(n); 7048 // track the highest overall match priority... 7049 if (info.priority > maxMatchPrio) { 7050 maxMatchPrio = info.priority; 7051 } 7052 // ...and the highest-priority default browser match 7053 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7054 if (defaultBrowserMatch == null 7055 || (defaultBrowserMatch.priority < info.priority)) { 7056 if (debug) { 7057 Slog.v(TAG, "Considering default browser match " + info); 7058 } 7059 defaultBrowserMatch = info; 7060 } 7061 } 7062 } 7063 if (defaultBrowserMatch != null 7064 && defaultBrowserMatch.priority >= maxMatchPrio 7065 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7066 { 7067 if (debug) { 7068 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7069 } 7070 result.add(defaultBrowserMatch); 7071 } else { 7072 result.addAll(matchAllList); 7073 } 7074 } 7075 7076 // If there is nothing selected, add all candidates and remove the ones that the user 7077 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7078 if (result.size() == 0) { 7079 result.addAll(candidates); 7080 result.removeAll(neverList); 7081 } 7082 } 7083 } 7084 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7085 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7086 result.size()); 7087 for (ResolveInfo info : result) { 7088 Slog.v(TAG, " + " + info.activityInfo); 7089 } 7090 } 7091 return result; 7092 } 7093 7094 // Returns a packed value as a long: 7095 // 7096 // high 'int'-sized word: link status: undefined/ask/never/always. 7097 // low 'int'-sized word: relative priority among 'always' results. 7098 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7099 long result = ps.getDomainVerificationStatusForUser(userId); 7100 // if none available, get the master status 7101 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7102 if (ps.getIntentFilterVerificationInfo() != null) { 7103 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7104 } 7105 } 7106 return result; 7107 } 7108 7109 private ResolveInfo querySkipCurrentProfileIntents( 7110 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7111 int flags, int sourceUserId) { 7112 if (matchingFilters != null) { 7113 int size = matchingFilters.size(); 7114 for (int i = 0; i < size; i ++) { 7115 CrossProfileIntentFilter filter = matchingFilters.get(i); 7116 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7117 // Checking if there are activities in the target user that can handle the 7118 // intent. 7119 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7120 resolvedType, flags, sourceUserId); 7121 if (resolveInfo != null) { 7122 return resolveInfo; 7123 } 7124 } 7125 } 7126 } 7127 return null; 7128 } 7129 7130 // Return matching ResolveInfo in target user if any. 7131 private ResolveInfo queryCrossProfileIntents( 7132 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7133 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7134 if (matchingFilters != null) { 7135 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7136 // match the same intent. For performance reasons, it is better not to 7137 // run queryIntent twice for the same userId 7138 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7139 int size = matchingFilters.size(); 7140 for (int i = 0; i < size; i++) { 7141 CrossProfileIntentFilter filter = matchingFilters.get(i); 7142 int targetUserId = filter.getTargetUserId(); 7143 boolean skipCurrentProfile = 7144 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7145 boolean skipCurrentProfileIfNoMatchFound = 7146 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7147 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7148 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7149 // Checking if there are activities in the target user that can handle the 7150 // intent. 7151 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7152 resolvedType, flags, sourceUserId); 7153 if (resolveInfo != null) return resolveInfo; 7154 alreadyTriedUserIds.put(targetUserId, true); 7155 } 7156 } 7157 } 7158 return null; 7159 } 7160 7161 /** 7162 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7163 * will forward the intent to the filter's target user. 7164 * Otherwise, returns null. 7165 */ 7166 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7167 String resolvedType, int flags, int sourceUserId) { 7168 int targetUserId = filter.getTargetUserId(); 7169 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7170 resolvedType, flags, targetUserId); 7171 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7172 // If all the matches in the target profile are suspended, return null. 7173 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7174 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7175 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7176 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7177 targetUserId); 7178 } 7179 } 7180 } 7181 return null; 7182 } 7183 7184 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7185 int sourceUserId, int targetUserId) { 7186 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7187 long ident = Binder.clearCallingIdentity(); 7188 boolean targetIsProfile; 7189 try { 7190 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7191 } finally { 7192 Binder.restoreCallingIdentity(ident); 7193 } 7194 String className; 7195 if (targetIsProfile) { 7196 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7197 } else { 7198 className = FORWARD_INTENT_TO_PARENT; 7199 } 7200 ComponentName forwardingActivityComponentName = new ComponentName( 7201 mAndroidApplication.packageName, className); 7202 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7203 sourceUserId); 7204 if (!targetIsProfile) { 7205 forwardingActivityInfo.showUserIcon = targetUserId; 7206 forwardingResolveInfo.noResourceId = true; 7207 } 7208 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7209 forwardingResolveInfo.priority = 0; 7210 forwardingResolveInfo.preferredOrder = 0; 7211 forwardingResolveInfo.match = 0; 7212 forwardingResolveInfo.isDefault = true; 7213 forwardingResolveInfo.filter = filter; 7214 forwardingResolveInfo.targetUserId = targetUserId; 7215 return forwardingResolveInfo; 7216 } 7217 7218 @Override 7219 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7220 Intent[] specifics, String[] specificTypes, Intent intent, 7221 String resolvedType, int flags, int userId) { 7222 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7223 specificTypes, intent, resolvedType, flags, userId)); 7224 } 7225 7226 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7227 Intent[] specifics, String[] specificTypes, Intent intent, 7228 String resolvedType, int flags, int userId) { 7229 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7230 final int callingUid = Binder.getCallingUid(); 7231 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7232 false /*includeInstantApps*/); 7233 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7234 false /*requireFullPermission*/, false /*checkShell*/, 7235 "query intent activity options"); 7236 final String resultsAction = intent.getAction(); 7237 7238 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7239 | PackageManager.GET_RESOLVED_FILTER, userId); 7240 7241 if (DEBUG_INTENT_MATCHING) { 7242 Log.v(TAG, "Query " + intent + ": " + results); 7243 } 7244 7245 int specificsPos = 0; 7246 int N; 7247 7248 // todo: note that the algorithm used here is O(N^2). This 7249 // isn't a problem in our current environment, but if we start running 7250 // into situations where we have more than 5 or 10 matches then this 7251 // should probably be changed to something smarter... 7252 7253 // First we go through and resolve each of the specific items 7254 // that were supplied, taking care of removing any corresponding 7255 // duplicate items in the generic resolve list. 7256 if (specifics != null) { 7257 for (int i=0; i<specifics.length; i++) { 7258 final Intent sintent = specifics[i]; 7259 if (sintent == null) { 7260 continue; 7261 } 7262 7263 if (DEBUG_INTENT_MATCHING) { 7264 Log.v(TAG, "Specific #" + i + ": " + sintent); 7265 } 7266 7267 String action = sintent.getAction(); 7268 if (resultsAction != null && resultsAction.equals(action)) { 7269 // If this action was explicitly requested, then don't 7270 // remove things that have it. 7271 action = null; 7272 } 7273 7274 ResolveInfo ri = null; 7275 ActivityInfo ai = null; 7276 7277 ComponentName comp = sintent.getComponent(); 7278 if (comp == null) { 7279 ri = resolveIntent( 7280 sintent, 7281 specificTypes != null ? specificTypes[i] : null, 7282 flags, userId); 7283 if (ri == null) { 7284 continue; 7285 } 7286 if (ri == mResolveInfo) { 7287 // ACK! Must do something better with this. 7288 } 7289 ai = ri.activityInfo; 7290 comp = new ComponentName(ai.applicationInfo.packageName, 7291 ai.name); 7292 } else { 7293 ai = getActivityInfo(comp, flags, userId); 7294 if (ai == null) { 7295 continue; 7296 } 7297 } 7298 7299 // Look for any generic query activities that are duplicates 7300 // of this specific one, and remove them from the results. 7301 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7302 N = results.size(); 7303 int j; 7304 for (j=specificsPos; j<N; j++) { 7305 ResolveInfo sri = results.get(j); 7306 if ((sri.activityInfo.name.equals(comp.getClassName()) 7307 && sri.activityInfo.applicationInfo.packageName.equals( 7308 comp.getPackageName())) 7309 || (action != null && sri.filter.matchAction(action))) { 7310 results.remove(j); 7311 if (DEBUG_INTENT_MATCHING) Log.v( 7312 TAG, "Removing duplicate item from " + j 7313 + " due to specific " + specificsPos); 7314 if (ri == null) { 7315 ri = sri; 7316 } 7317 j--; 7318 N--; 7319 } 7320 } 7321 7322 // Add this specific item to its proper place. 7323 if (ri == null) { 7324 ri = new ResolveInfo(); 7325 ri.activityInfo = ai; 7326 } 7327 results.add(specificsPos, ri); 7328 ri.specificIndex = i; 7329 specificsPos++; 7330 } 7331 } 7332 7333 // Now we go through the remaining generic results and remove any 7334 // duplicate actions that are found here. 7335 N = results.size(); 7336 for (int i=specificsPos; i<N-1; i++) { 7337 final ResolveInfo rii = results.get(i); 7338 if (rii.filter == null) { 7339 continue; 7340 } 7341 7342 // Iterate over all of the actions of this result's intent 7343 // filter... typically this should be just one. 7344 final Iterator<String> it = rii.filter.actionsIterator(); 7345 if (it == null) { 7346 continue; 7347 } 7348 while (it.hasNext()) { 7349 final String action = it.next(); 7350 if (resultsAction != null && resultsAction.equals(action)) { 7351 // If this action was explicitly requested, then don't 7352 // remove things that have it. 7353 continue; 7354 } 7355 for (int j=i+1; j<N; j++) { 7356 final ResolveInfo rij = results.get(j); 7357 if (rij.filter != null && rij.filter.hasAction(action)) { 7358 results.remove(j); 7359 if (DEBUG_INTENT_MATCHING) Log.v( 7360 TAG, "Removing duplicate item from " + j 7361 + " due to action " + action + " at " + i); 7362 j--; 7363 N--; 7364 } 7365 } 7366 } 7367 7368 // If the caller didn't request filter information, drop it now 7369 // so we don't have to marshall/unmarshall it. 7370 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7371 rii.filter = null; 7372 } 7373 } 7374 7375 // Filter out the caller activity if so requested. 7376 if (caller != null) { 7377 N = results.size(); 7378 for (int i=0; i<N; i++) { 7379 ActivityInfo ainfo = results.get(i).activityInfo; 7380 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7381 && caller.getClassName().equals(ainfo.name)) { 7382 results.remove(i); 7383 break; 7384 } 7385 } 7386 } 7387 7388 // If the caller didn't request filter information, 7389 // drop them now so we don't have to 7390 // marshall/unmarshall it. 7391 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7392 N = results.size(); 7393 for (int i=0; i<N; i++) { 7394 results.get(i).filter = null; 7395 } 7396 } 7397 7398 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7399 return results; 7400 } 7401 7402 @Override 7403 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7404 String resolvedType, int flags, int userId) { 7405 return new ParceledListSlice<>( 7406 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7407 false /*allowDynamicSplits*/)); 7408 } 7409 7410 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7411 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7412 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7413 final int callingUid = Binder.getCallingUid(); 7414 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7415 false /*requireFullPermission*/, false /*checkShell*/, 7416 "query intent receivers"); 7417 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7418 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7419 false /*includeInstantApps*/); 7420 ComponentName comp = intent.getComponent(); 7421 if (comp == null) { 7422 if (intent.getSelector() != null) { 7423 intent = intent.getSelector(); 7424 comp = intent.getComponent(); 7425 } 7426 } 7427 if (comp != null) { 7428 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7429 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7430 if (ai != null) { 7431 // When specifying an explicit component, we prevent the activity from being 7432 // used when either 1) the calling package is normal and the activity is within 7433 // an instant application or 2) the calling package is ephemeral and the 7434 // activity is not visible to instant applications. 7435 final boolean matchInstantApp = 7436 (flags & PackageManager.MATCH_INSTANT) != 0; 7437 final boolean matchVisibleToInstantAppOnly = 7438 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7439 final boolean matchExplicitlyVisibleOnly = 7440 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7441 final boolean isCallerInstantApp = 7442 instantAppPkgName != null; 7443 final boolean isTargetSameInstantApp = 7444 comp.getPackageName().equals(instantAppPkgName); 7445 final boolean isTargetInstantApp = 7446 (ai.applicationInfo.privateFlags 7447 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7448 final boolean isTargetVisibleToInstantApp = 7449 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7450 final boolean isTargetExplicitlyVisibleToInstantApp = 7451 isTargetVisibleToInstantApp 7452 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7453 final boolean isTargetHiddenFromInstantApp = 7454 !isTargetVisibleToInstantApp 7455 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7456 final boolean blockResolution = 7457 !isTargetSameInstantApp 7458 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7459 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7460 && isTargetHiddenFromInstantApp)); 7461 if (!blockResolution) { 7462 ResolveInfo ri = new ResolveInfo(); 7463 ri.activityInfo = ai; 7464 list.add(ri); 7465 } 7466 } 7467 return applyPostResolutionFilter( 7468 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7469 } 7470 7471 // reader 7472 synchronized (mPackages) { 7473 String pkgName = intent.getPackage(); 7474 if (pkgName == null) { 7475 final List<ResolveInfo> result = 7476 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7477 return applyPostResolutionFilter( 7478 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7479 } 7480 final PackageParser.Package pkg = mPackages.get(pkgName); 7481 if (pkg != null) { 7482 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7483 intent, resolvedType, flags, pkg.receivers, userId); 7484 return applyPostResolutionFilter( 7485 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7486 } 7487 return Collections.emptyList(); 7488 } 7489 } 7490 7491 @Override 7492 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7493 final int callingUid = Binder.getCallingUid(); 7494 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7495 } 7496 7497 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7498 int userId, int callingUid) { 7499 if (!sUserManager.exists(userId)) return null; 7500 flags = updateFlagsForResolve( 7501 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7502 List<ResolveInfo> query = queryIntentServicesInternal( 7503 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7504 if (query != null) { 7505 if (query.size() >= 1) { 7506 // If there is more than one service with the same priority, 7507 // just arbitrarily pick the first one. 7508 return query.get(0); 7509 } 7510 } 7511 return null; 7512 } 7513 7514 @Override 7515 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7516 String resolvedType, int flags, int userId) { 7517 final int callingUid = Binder.getCallingUid(); 7518 return new ParceledListSlice<>(queryIntentServicesInternal( 7519 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7520 } 7521 7522 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7523 String resolvedType, int flags, int userId, int callingUid, 7524 boolean includeInstantApps) { 7525 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7526 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7527 false /*requireFullPermission*/, false /*checkShell*/, 7528 "query intent receivers"); 7529 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7530 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7531 ComponentName comp = intent.getComponent(); 7532 if (comp == null) { 7533 if (intent.getSelector() != null) { 7534 intent = intent.getSelector(); 7535 comp = intent.getComponent(); 7536 } 7537 } 7538 if (comp != null) { 7539 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7540 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7541 if (si != null) { 7542 // When specifying an explicit component, we prevent the service from being 7543 // used when either 1) the service is in an instant application and the 7544 // caller is not the same instant application or 2) the calling package is 7545 // ephemeral and the activity is not visible to ephemeral applications. 7546 final boolean matchInstantApp = 7547 (flags & PackageManager.MATCH_INSTANT) != 0; 7548 final boolean matchVisibleToInstantAppOnly = 7549 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7550 final boolean isCallerInstantApp = 7551 instantAppPkgName != null; 7552 final boolean isTargetSameInstantApp = 7553 comp.getPackageName().equals(instantAppPkgName); 7554 final boolean isTargetInstantApp = 7555 (si.applicationInfo.privateFlags 7556 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7557 final boolean isTargetHiddenFromInstantApp = 7558 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7559 final boolean blockResolution = 7560 !isTargetSameInstantApp 7561 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7562 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7563 && isTargetHiddenFromInstantApp)); 7564 if (!blockResolution) { 7565 final ResolveInfo ri = new ResolveInfo(); 7566 ri.serviceInfo = si; 7567 list.add(ri); 7568 } 7569 } 7570 return list; 7571 } 7572 7573 // reader 7574 synchronized (mPackages) { 7575 String pkgName = intent.getPackage(); 7576 if (pkgName == null) { 7577 return applyPostServiceResolutionFilter( 7578 mServices.queryIntent(intent, resolvedType, flags, userId), 7579 instantAppPkgName); 7580 } 7581 final PackageParser.Package pkg = mPackages.get(pkgName); 7582 if (pkg != null) { 7583 return applyPostServiceResolutionFilter( 7584 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7585 userId), 7586 instantAppPkgName); 7587 } 7588 return Collections.emptyList(); 7589 } 7590 } 7591 7592 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7593 String instantAppPkgName) { 7594 if (instantAppPkgName == null) { 7595 return resolveInfos; 7596 } 7597 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7598 final ResolveInfo info = resolveInfos.get(i); 7599 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7600 // allow services that are defined in the provided package 7601 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7602 if (info.serviceInfo.splitName != null 7603 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7604 info.serviceInfo.splitName)) { 7605 // requested service is defined in a split that hasn't been installed yet. 7606 // add the installer to the resolve list 7607 if (DEBUG_EPHEMERAL) { 7608 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7609 } 7610 final ResolveInfo installerInfo = new ResolveInfo( 7611 mInstantAppInstallerInfo); 7612 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7613 null /* installFailureActivity */, 7614 info.serviceInfo.packageName, 7615 info.serviceInfo.applicationInfo.versionCode, 7616 info.serviceInfo.splitName); 7617 // make sure this resolver is the default 7618 installerInfo.isDefault = true; 7619 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7620 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7621 // add a non-generic filter 7622 installerInfo.filter = new IntentFilter(); 7623 // load resources from the correct package 7624 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7625 resolveInfos.set(i, installerInfo); 7626 } 7627 continue; 7628 } 7629 // allow services that have been explicitly exposed to ephemeral apps 7630 if (!isEphemeralApp 7631 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7632 continue; 7633 } 7634 resolveInfos.remove(i); 7635 } 7636 return resolveInfos; 7637 } 7638 7639 @Override 7640 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7641 String resolvedType, int flags, int userId) { 7642 return new ParceledListSlice<>( 7643 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7644 } 7645 7646 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7647 Intent intent, String resolvedType, int flags, int userId) { 7648 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7649 final int callingUid = Binder.getCallingUid(); 7650 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7651 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7652 false /*includeInstantApps*/); 7653 ComponentName comp = intent.getComponent(); 7654 if (comp == null) { 7655 if (intent.getSelector() != null) { 7656 intent = intent.getSelector(); 7657 comp = intent.getComponent(); 7658 } 7659 } 7660 if (comp != null) { 7661 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7662 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7663 if (pi != null) { 7664 // When specifying an explicit component, we prevent the provider from being 7665 // used when either 1) the provider is in an instant application and the 7666 // caller is not the same instant application or 2) the calling package is an 7667 // instant application and the provider is not visible to instant applications. 7668 final boolean matchInstantApp = 7669 (flags & PackageManager.MATCH_INSTANT) != 0; 7670 final boolean matchVisibleToInstantAppOnly = 7671 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7672 final boolean isCallerInstantApp = 7673 instantAppPkgName != null; 7674 final boolean isTargetSameInstantApp = 7675 comp.getPackageName().equals(instantAppPkgName); 7676 final boolean isTargetInstantApp = 7677 (pi.applicationInfo.privateFlags 7678 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7679 final boolean isTargetHiddenFromInstantApp = 7680 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7681 final boolean blockResolution = 7682 !isTargetSameInstantApp 7683 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7684 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7685 && isTargetHiddenFromInstantApp)); 7686 if (!blockResolution) { 7687 final ResolveInfo ri = new ResolveInfo(); 7688 ri.providerInfo = pi; 7689 list.add(ri); 7690 } 7691 } 7692 return list; 7693 } 7694 7695 // reader 7696 synchronized (mPackages) { 7697 String pkgName = intent.getPackage(); 7698 if (pkgName == null) { 7699 return applyPostContentProviderResolutionFilter( 7700 mProviders.queryIntent(intent, resolvedType, flags, userId), 7701 instantAppPkgName); 7702 } 7703 final PackageParser.Package pkg = mPackages.get(pkgName); 7704 if (pkg != null) { 7705 return applyPostContentProviderResolutionFilter( 7706 mProviders.queryIntentForPackage( 7707 intent, resolvedType, flags, pkg.providers, userId), 7708 instantAppPkgName); 7709 } 7710 return Collections.emptyList(); 7711 } 7712 } 7713 7714 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7715 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7716 if (instantAppPkgName == null) { 7717 return resolveInfos; 7718 } 7719 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7720 final ResolveInfo info = resolveInfos.get(i); 7721 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7722 // allow providers that are defined in the provided package 7723 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7724 if (info.providerInfo.splitName != null 7725 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7726 info.providerInfo.splitName)) { 7727 // requested provider is defined in a split that hasn't been installed yet. 7728 // add the installer to the resolve list 7729 if (DEBUG_EPHEMERAL) { 7730 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7731 } 7732 final ResolveInfo installerInfo = new ResolveInfo( 7733 mInstantAppInstallerInfo); 7734 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7735 null /*failureActivity*/, 7736 info.providerInfo.packageName, 7737 info.providerInfo.applicationInfo.versionCode, 7738 info.providerInfo.splitName); 7739 // make sure this resolver is the default 7740 installerInfo.isDefault = true; 7741 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7742 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7743 // add a non-generic filter 7744 installerInfo.filter = new IntentFilter(); 7745 // load resources from the correct package 7746 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7747 resolveInfos.set(i, installerInfo); 7748 } 7749 continue; 7750 } 7751 // allow providers that have been explicitly exposed to instant applications 7752 if (!isEphemeralApp 7753 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7754 continue; 7755 } 7756 resolveInfos.remove(i); 7757 } 7758 return resolveInfos; 7759 } 7760 7761 @Override 7762 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7763 final int callingUid = Binder.getCallingUid(); 7764 if (getInstantAppPackageName(callingUid) != null) { 7765 return ParceledListSlice.emptyList(); 7766 } 7767 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7768 flags = updateFlagsForPackage(flags, userId, null); 7769 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7770 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7771 true /* requireFullPermission */, false /* checkShell */, 7772 "get installed packages"); 7773 7774 // writer 7775 synchronized (mPackages) { 7776 ArrayList<PackageInfo> list; 7777 if (listUninstalled) { 7778 list = new ArrayList<>(mSettings.mPackages.size()); 7779 for (PackageSetting ps : mSettings.mPackages.values()) { 7780 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7781 continue; 7782 } 7783 if (filterAppAccessLPr(ps, callingUid, userId)) { 7784 continue; 7785 } 7786 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7787 if (pi != null) { 7788 list.add(pi); 7789 } 7790 } 7791 } else { 7792 list = new ArrayList<>(mPackages.size()); 7793 for (PackageParser.Package p : mPackages.values()) { 7794 final PackageSetting ps = (PackageSetting) p.mExtras; 7795 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7796 continue; 7797 } 7798 if (filterAppAccessLPr(ps, callingUid, userId)) { 7799 continue; 7800 } 7801 final PackageInfo pi = generatePackageInfo((PackageSetting) 7802 p.mExtras, flags, userId); 7803 if (pi != null) { 7804 list.add(pi); 7805 } 7806 } 7807 } 7808 7809 return new ParceledListSlice<>(list); 7810 } 7811 } 7812 7813 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7814 String[] permissions, boolean[] tmp, int flags, int userId) { 7815 int numMatch = 0; 7816 final PermissionsState permissionsState = ps.getPermissionsState(); 7817 for (int i=0; i<permissions.length; i++) { 7818 final String permission = permissions[i]; 7819 if (permissionsState.hasPermission(permission, userId)) { 7820 tmp[i] = true; 7821 numMatch++; 7822 } else { 7823 tmp[i] = false; 7824 } 7825 } 7826 if (numMatch == 0) { 7827 return; 7828 } 7829 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7830 7831 // The above might return null in cases of uninstalled apps or install-state 7832 // skew across users/profiles. 7833 if (pi != null) { 7834 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7835 if (numMatch == permissions.length) { 7836 pi.requestedPermissions = permissions; 7837 } else { 7838 pi.requestedPermissions = new String[numMatch]; 7839 numMatch = 0; 7840 for (int i=0; i<permissions.length; i++) { 7841 if (tmp[i]) { 7842 pi.requestedPermissions[numMatch] = permissions[i]; 7843 numMatch++; 7844 } 7845 } 7846 } 7847 } 7848 list.add(pi); 7849 } 7850 } 7851 7852 @Override 7853 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7854 String[] permissions, int flags, int userId) { 7855 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7856 flags = updateFlagsForPackage(flags, userId, permissions); 7857 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7858 true /* requireFullPermission */, false /* checkShell */, 7859 "get packages holding permissions"); 7860 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7861 7862 // writer 7863 synchronized (mPackages) { 7864 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7865 boolean[] tmpBools = new boolean[permissions.length]; 7866 if (listUninstalled) { 7867 for (PackageSetting ps : mSettings.mPackages.values()) { 7868 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7869 userId); 7870 } 7871 } else { 7872 for (PackageParser.Package pkg : mPackages.values()) { 7873 PackageSetting ps = (PackageSetting)pkg.mExtras; 7874 if (ps != null) { 7875 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7876 userId); 7877 } 7878 } 7879 } 7880 7881 return new ParceledListSlice<PackageInfo>(list); 7882 } 7883 } 7884 7885 @Override 7886 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7887 final int callingUid = Binder.getCallingUid(); 7888 if (getInstantAppPackageName(callingUid) != null) { 7889 return ParceledListSlice.emptyList(); 7890 } 7891 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7892 flags = updateFlagsForApplication(flags, userId, null); 7893 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7894 7895 // writer 7896 synchronized (mPackages) { 7897 ArrayList<ApplicationInfo> list; 7898 if (listUninstalled) { 7899 list = new ArrayList<>(mSettings.mPackages.size()); 7900 for (PackageSetting ps : mSettings.mPackages.values()) { 7901 ApplicationInfo ai; 7902 int effectiveFlags = flags; 7903 if (ps.isSystem()) { 7904 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7905 } 7906 if (ps.pkg != null) { 7907 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7908 continue; 7909 } 7910 if (filterAppAccessLPr(ps, callingUid, userId)) { 7911 continue; 7912 } 7913 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7914 ps.readUserState(userId), userId); 7915 if (ai != null) { 7916 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7917 } 7918 } else { 7919 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7920 // and already converts to externally visible package name 7921 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7922 callingUid, effectiveFlags, userId); 7923 } 7924 if (ai != null) { 7925 list.add(ai); 7926 } 7927 } 7928 } else { 7929 list = new ArrayList<>(mPackages.size()); 7930 for (PackageParser.Package p : mPackages.values()) { 7931 if (p.mExtras != null) { 7932 PackageSetting ps = (PackageSetting) p.mExtras; 7933 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7934 continue; 7935 } 7936 if (filterAppAccessLPr(ps, callingUid, userId)) { 7937 continue; 7938 } 7939 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7940 ps.readUserState(userId), userId); 7941 if (ai != null) { 7942 ai.packageName = resolveExternalPackageNameLPr(p); 7943 list.add(ai); 7944 } 7945 } 7946 } 7947 } 7948 7949 return new ParceledListSlice<>(list); 7950 } 7951 } 7952 7953 @Override 7954 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7955 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7956 return null; 7957 } 7958 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7959 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7960 "getEphemeralApplications"); 7961 } 7962 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7963 true /* requireFullPermission */, false /* checkShell */, 7964 "getEphemeralApplications"); 7965 synchronized (mPackages) { 7966 List<InstantAppInfo> instantApps = mInstantAppRegistry 7967 .getInstantAppsLPr(userId); 7968 if (instantApps != null) { 7969 return new ParceledListSlice<>(instantApps); 7970 } 7971 } 7972 return null; 7973 } 7974 7975 @Override 7976 public boolean isInstantApp(String packageName, int userId) { 7977 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7978 true /* requireFullPermission */, false /* checkShell */, 7979 "isInstantApp"); 7980 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7981 return false; 7982 } 7983 7984 synchronized (mPackages) { 7985 int callingUid = Binder.getCallingUid(); 7986 if (Process.isIsolated(callingUid)) { 7987 callingUid = mIsolatedOwners.get(callingUid); 7988 } 7989 final PackageSetting ps = mSettings.mPackages.get(packageName); 7990 PackageParser.Package pkg = mPackages.get(packageName); 7991 final boolean returnAllowed = 7992 ps != null 7993 && (isCallerSameApp(packageName, callingUid) 7994 || canViewInstantApps(callingUid, userId) 7995 || mInstantAppRegistry.isInstantAccessGranted( 7996 userId, UserHandle.getAppId(callingUid), ps.appId)); 7997 if (returnAllowed) { 7998 return ps.getInstantApp(userId); 7999 } 8000 } 8001 return false; 8002 } 8003 8004 @Override 8005 public byte[] getInstantAppCookie(String packageName, int userId) { 8006 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8007 return null; 8008 } 8009 8010 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8011 true /* requireFullPermission */, false /* checkShell */, 8012 "getInstantAppCookie"); 8013 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8014 return null; 8015 } 8016 synchronized (mPackages) { 8017 return mInstantAppRegistry.getInstantAppCookieLPw( 8018 packageName, userId); 8019 } 8020 } 8021 8022 @Override 8023 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8024 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8025 return true; 8026 } 8027 8028 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8029 true /* requireFullPermission */, true /* checkShell */, 8030 "setInstantAppCookie"); 8031 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8032 return false; 8033 } 8034 synchronized (mPackages) { 8035 return mInstantAppRegistry.setInstantAppCookieLPw( 8036 packageName, cookie, userId); 8037 } 8038 } 8039 8040 @Override 8041 public Bitmap getInstantAppIcon(String packageName, int userId) { 8042 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8043 return null; 8044 } 8045 8046 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8047 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8048 "getInstantAppIcon"); 8049 } 8050 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8051 true /* requireFullPermission */, false /* checkShell */, 8052 "getInstantAppIcon"); 8053 8054 synchronized (mPackages) { 8055 return mInstantAppRegistry.getInstantAppIconLPw( 8056 packageName, userId); 8057 } 8058 } 8059 8060 private boolean isCallerSameApp(String packageName, int uid) { 8061 PackageParser.Package pkg = mPackages.get(packageName); 8062 return pkg != null 8063 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8064 } 8065 8066 @Override 8067 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8068 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8069 return ParceledListSlice.emptyList(); 8070 } 8071 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8072 } 8073 8074 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8075 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8076 8077 // reader 8078 synchronized (mPackages) { 8079 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8080 final int userId = UserHandle.getCallingUserId(); 8081 while (i.hasNext()) { 8082 final PackageParser.Package p = i.next(); 8083 if (p.applicationInfo == null) continue; 8084 8085 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8086 && !p.applicationInfo.isDirectBootAware(); 8087 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8088 && p.applicationInfo.isDirectBootAware(); 8089 8090 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8091 && (!mSafeMode || isSystemApp(p)) 8092 && (matchesUnaware || matchesAware)) { 8093 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8094 if (ps != null) { 8095 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8096 ps.readUserState(userId), userId); 8097 if (ai != null) { 8098 finalList.add(ai); 8099 } 8100 } 8101 } 8102 } 8103 } 8104 8105 return finalList; 8106 } 8107 8108 @Override 8109 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8110 return resolveContentProviderInternal(name, flags, userId); 8111 } 8112 8113 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8114 if (!sUserManager.exists(userId)) return null; 8115 flags = updateFlagsForComponent(flags, userId, name); 8116 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8117 // reader 8118 synchronized (mPackages) { 8119 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8120 PackageSetting ps = provider != null 8121 ? mSettings.mPackages.get(provider.owner.packageName) 8122 : null; 8123 if (ps != null) { 8124 final boolean isInstantApp = ps.getInstantApp(userId); 8125 // normal application; filter out instant application provider 8126 if (instantAppPkgName == null && isInstantApp) { 8127 return null; 8128 } 8129 // instant application; filter out other instant applications 8130 if (instantAppPkgName != null 8131 && isInstantApp 8132 && !provider.owner.packageName.equals(instantAppPkgName)) { 8133 return null; 8134 } 8135 // instant application; filter out non-exposed provider 8136 if (instantAppPkgName != null 8137 && !isInstantApp 8138 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8139 return null; 8140 } 8141 // provider not enabled 8142 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8143 return null; 8144 } 8145 return PackageParser.generateProviderInfo( 8146 provider, flags, ps.readUserState(userId), userId); 8147 } 8148 return null; 8149 } 8150 } 8151 8152 /** 8153 * @deprecated 8154 */ 8155 @Deprecated 8156 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8157 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8158 return; 8159 } 8160 // reader 8161 synchronized (mPackages) { 8162 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8163 .entrySet().iterator(); 8164 final int userId = UserHandle.getCallingUserId(); 8165 while (i.hasNext()) { 8166 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8167 PackageParser.Provider p = entry.getValue(); 8168 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8169 8170 if (ps != null && p.syncable 8171 && (!mSafeMode || (p.info.applicationInfo.flags 8172 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8173 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8174 ps.readUserState(userId), userId); 8175 if (info != null) { 8176 outNames.add(entry.getKey()); 8177 outInfo.add(info); 8178 } 8179 } 8180 } 8181 } 8182 } 8183 8184 @Override 8185 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8186 int uid, int flags, String metaDataKey) { 8187 final int callingUid = Binder.getCallingUid(); 8188 final int userId = processName != null ? UserHandle.getUserId(uid) 8189 : UserHandle.getCallingUserId(); 8190 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8191 flags = updateFlagsForComponent(flags, userId, processName); 8192 ArrayList<ProviderInfo> finalList = null; 8193 // reader 8194 synchronized (mPackages) { 8195 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8196 while (i.hasNext()) { 8197 final PackageParser.Provider p = i.next(); 8198 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8199 if (ps != null && p.info.authority != null 8200 && (processName == null 8201 || (p.info.processName.equals(processName) 8202 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8203 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8204 8205 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8206 // parameter. 8207 if (metaDataKey != null 8208 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8209 continue; 8210 } 8211 final ComponentName component = 8212 new ComponentName(p.info.packageName, p.info.name); 8213 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8214 continue; 8215 } 8216 if (finalList == null) { 8217 finalList = new ArrayList<ProviderInfo>(3); 8218 } 8219 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8220 ps.readUserState(userId), userId); 8221 if (info != null) { 8222 finalList.add(info); 8223 } 8224 } 8225 } 8226 } 8227 8228 if (finalList != null) { 8229 Collections.sort(finalList, mProviderInitOrderSorter); 8230 return new ParceledListSlice<ProviderInfo>(finalList); 8231 } 8232 8233 return ParceledListSlice.emptyList(); 8234 } 8235 8236 @Override 8237 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8238 // reader 8239 synchronized (mPackages) { 8240 final int callingUid = Binder.getCallingUid(); 8241 final int callingUserId = UserHandle.getUserId(callingUid); 8242 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8243 if (ps == null) return null; 8244 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8245 return null; 8246 } 8247 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8248 return PackageParser.generateInstrumentationInfo(i, flags); 8249 } 8250 } 8251 8252 @Override 8253 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8254 String targetPackage, int flags) { 8255 final int callingUid = Binder.getCallingUid(); 8256 final int callingUserId = UserHandle.getUserId(callingUid); 8257 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8258 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8259 return ParceledListSlice.emptyList(); 8260 } 8261 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8262 } 8263 8264 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8265 int flags) { 8266 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8267 8268 // reader 8269 synchronized (mPackages) { 8270 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8271 while (i.hasNext()) { 8272 final PackageParser.Instrumentation p = i.next(); 8273 if (targetPackage == null 8274 || targetPackage.equals(p.info.targetPackage)) { 8275 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8276 flags); 8277 if (ii != null) { 8278 finalList.add(ii); 8279 } 8280 } 8281 } 8282 } 8283 8284 return finalList; 8285 } 8286 8287 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8289 try { 8290 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8291 } finally { 8292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8293 } 8294 } 8295 8296 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8297 final File[] files = scanDir.listFiles(); 8298 if (ArrayUtils.isEmpty(files)) { 8299 Log.d(TAG, "No files in app dir " + scanDir); 8300 return; 8301 } 8302 8303 if (DEBUG_PACKAGE_SCANNING) { 8304 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8305 + " flags=0x" + Integer.toHexString(parseFlags)); 8306 } 8307 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8308 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8309 mParallelPackageParserCallback)) { 8310 // Submit files for parsing in parallel 8311 int fileCount = 0; 8312 for (File file : files) { 8313 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8314 && !PackageInstallerService.isStageName(file.getName()); 8315 if (!isPackage) { 8316 // Ignore entries which are not packages 8317 continue; 8318 } 8319 parallelPackageParser.submit(file, parseFlags); 8320 fileCount++; 8321 } 8322 8323 // Process results one by one 8324 for (; fileCount > 0; fileCount--) { 8325 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8326 Throwable throwable = parseResult.throwable; 8327 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8328 8329 if (throwable == null) { 8330 // TODO(toddke): move lower in the scan chain 8331 // Static shared libraries have synthetic package names 8332 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8333 renameStaticSharedLibraryPackage(parseResult.pkg); 8334 } 8335 try { 8336 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8337 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8338 currentTime, null); 8339 } 8340 } catch (PackageManagerException e) { 8341 errorCode = e.error; 8342 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8343 } 8344 } else if (throwable instanceof PackageParser.PackageParserException) { 8345 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8346 throwable; 8347 errorCode = e.error; 8348 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8349 } else { 8350 throw new IllegalStateException("Unexpected exception occurred while parsing " 8351 + parseResult.scanFile, throwable); 8352 } 8353 8354 // Delete invalid userdata apps 8355 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8356 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8357 logCriticalInfo(Log.WARN, 8358 "Deleting invalid package at " + parseResult.scanFile); 8359 removeCodePathLI(parseResult.scanFile); 8360 } 8361 } 8362 } 8363 } 8364 8365 public static void reportSettingsProblem(int priority, String msg) { 8366 logCriticalInfo(priority, msg); 8367 } 8368 8369 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8370 boolean forceCollect) throws PackageManagerException { 8371 // When upgrading from pre-N MR1, verify the package time stamp using the package 8372 // directory and not the APK file. 8373 final long lastModifiedTime = mIsPreNMR1Upgrade 8374 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8375 // Note that currently skipVerify skips verification on both base and splits for simplicity. 8376 final boolean skipVerify = forceCollect && canSkipFullPackageVerification(pkg); 8377 if (ps != null && !forceCollect 8378 && ps.codePathString.equals(pkg.codePath) 8379 && ps.timeStamp == lastModifiedTime 8380 && !isCompatSignatureUpdateNeeded(pkg) 8381 && !isRecoverSignatureUpdateNeeded(pkg)) { 8382 if (ps.signatures.mSigningDetails.signatures != null 8383 && ps.signatures.mSigningDetails.signatures.length != 0 8384 && ps.signatures.mSigningDetails.signatureSchemeVersion 8385 != SignatureSchemeVersion.UNKNOWN) { 8386 // Optimization: reuse the existing cached signing data 8387 // if the package appears to be unchanged. 8388 pkg.mSigningDetails = 8389 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8390 return; 8391 } 8392 8393 Slog.w(TAG, "PackageSetting for " + ps.name 8394 + " is missing signatures. Collecting certs again to recover them."); 8395 } else { 8396 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8397 (forceCollect ? " (forced)" : "")); 8398 } 8399 8400 try { 8401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8402 PackageParser.collectCertificates(pkg, skipVerify); 8403 } catch (PackageParserException e) { 8404 throw PackageManagerException.from(e); 8405 } finally { 8406 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8407 } 8408 } 8409 8410 /** 8411 * Traces a package scan. 8412 * @see #scanPackageLI(File, int, int, long, UserHandle) 8413 */ 8414 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8415 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8417 try { 8418 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8419 } finally { 8420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8421 } 8422 } 8423 8424 /** 8425 * Scans a package and returns the newly parsed package. 8426 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8427 */ 8428 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8429 long currentTime, UserHandle user) throws PackageManagerException { 8430 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8431 PackageParser pp = new PackageParser(); 8432 pp.setSeparateProcesses(mSeparateProcesses); 8433 pp.setOnlyCoreApps(mOnlyCore); 8434 pp.setDisplayMetrics(mMetrics); 8435 pp.setCallback(mPackageParserCallback); 8436 8437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8438 final PackageParser.Package pkg; 8439 try { 8440 pkg = pp.parsePackage(scanFile, parseFlags); 8441 } catch (PackageParserException e) { 8442 throw PackageManagerException.from(e); 8443 } finally { 8444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8445 } 8446 8447 // Static shared libraries have synthetic package names 8448 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8449 renameStaticSharedLibraryPackage(pkg); 8450 } 8451 8452 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8453 } 8454 8455 /** 8456 * Scans a package and returns the newly parsed package. 8457 * @throws PackageManagerException on a parse error. 8458 */ 8459 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8460 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8461 @Nullable UserHandle user) 8462 throws PackageManagerException { 8463 // If the package has children and this is the first dive in the function 8464 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8465 // packages (parent and children) would be successfully scanned before the 8466 // actual scan since scanning mutates internal state and we want to atomically 8467 // install the package and its children. 8468 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8469 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8470 scanFlags |= SCAN_CHECK_ONLY; 8471 } 8472 } else { 8473 scanFlags &= ~SCAN_CHECK_ONLY; 8474 } 8475 8476 // Scan the parent 8477 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8478 scanFlags, currentTime, user); 8479 8480 // Scan the children 8481 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8482 for (int i = 0; i < childCount; i++) { 8483 PackageParser.Package childPackage = pkg.childPackages.get(i); 8484 addForInitLI(childPackage, parseFlags, scanFlags, 8485 currentTime, user); 8486 } 8487 8488 8489 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8490 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8491 } 8492 8493 return scannedPkg; 8494 } 8495 8496 /** 8497 * Returns if full apk verification can be skipped for the whole package, including the splits. 8498 */ 8499 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8500 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8501 return false; 8502 } 8503 // TODO: Allow base and splits to be verified individually. 8504 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8505 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8506 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8507 return false; 8508 } 8509 } 8510 } 8511 return true; 8512 } 8513 8514 /** 8515 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8516 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8517 * match one in a trusted source, and should be done separately. 8518 */ 8519 private boolean canSkipFullApkVerification(String apkPath) { 8520 byte[] rootHashObserved = null; 8521 try { 8522 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8523 if (rootHashObserved == null) { 8524 return false; // APK does not contain Merkle tree root hash. 8525 } 8526 synchronized (mInstallLock) { 8527 // Returns whether the observed root hash matches what kernel has. 8528 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8529 return true; 8530 } 8531 } catch (InstallerException | IOException | DigestException | 8532 NoSuchAlgorithmException e) { 8533 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8534 } 8535 return false; 8536 } 8537 8538 // Temporary to catch potential issues with refactoring 8539 private static boolean REFACTOR_DEBUG = true; 8540 /** 8541 * Adds a new package to the internal data structures during platform initialization. 8542 * <p>After adding, the package is known to the system and available for querying. 8543 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8544 * etc...], additional checks are performed. Basic verification [such as ensuring 8545 * matching signatures, checking version codes, etc...] occurs if the package is 8546 * identical to a previously known package. If the package fails a signature check, 8547 * the version installed on /data will be removed. If the version of the new package 8548 * is less than or equal than the version on /data, it will be ignored. 8549 * <p>Regardless of the package location, the results are applied to the internal 8550 * structures and the package is made available to the rest of the system. 8551 * <p>NOTE: The return value should be removed. It's the passed in package object. 8552 */ 8553 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8554 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8555 @Nullable UserHandle user) 8556 throws PackageManagerException { 8557 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8558 final String renamedPkgName; 8559 final PackageSetting disabledPkgSetting; 8560 final boolean isSystemPkgUpdated; 8561 final boolean pkgAlreadyExists; 8562 PackageSetting pkgSetting; 8563 8564 // NOTE: installPackageLI() has the same code to setup the package's 8565 // application info. This probably should be done lower in the call 8566 // stack [such as scanPackageOnly()]. However, we verify the application 8567 // info prior to that [in scanPackageNew()] and thus have to setup 8568 // the application info early. 8569 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8570 pkg.setApplicationInfoCodePath(pkg.codePath); 8571 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8572 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8573 pkg.setApplicationInfoResourcePath(pkg.codePath); 8574 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8575 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8576 8577 synchronized (mPackages) { 8578 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8579 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8580if (REFACTOR_DEBUG) { 8581Slog.e("TODD", 8582 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8583} 8584 if (realPkgName != null) { 8585 ensurePackageRenamed(pkg, renamedPkgName); 8586 } 8587 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8588 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8589 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8590 pkgAlreadyExists = pkgSetting != null; 8591 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8592 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8593 isSystemPkgUpdated = disabledPkgSetting != null; 8594 8595 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8596 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8597 } 8598if (REFACTOR_DEBUG) { 8599Slog.e("TODD", 8600 "SSP? " + scanSystemPartition 8601 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8602 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8603} 8604 8605 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8606 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8607 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8608 : null; 8609 if (DEBUG_PACKAGE_SCANNING 8610 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8611 && sharedUserSetting != null) { 8612 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8613 + " (uid=" + sharedUserSetting.userId + "):" 8614 + " packages=" + sharedUserSetting.packages); 8615if (REFACTOR_DEBUG) { 8616Slog.e("TODD", 8617 "Shared UserID " + pkg.mSharedUserId 8618 + " (uid=" + sharedUserSetting.userId + "):" 8619 + " packages=" + sharedUserSetting.packages); 8620} 8621 } 8622 8623 if (scanSystemPartition) { 8624 // Potentially prune child packages. If the application on the /system 8625 // partition has been updated via OTA, but, is still disabled by a 8626 // version on /data, cycle through all of its children packages and 8627 // remove children that are no longer defined. 8628 if (isSystemPkgUpdated) { 8629if (REFACTOR_DEBUG) { 8630Slog.e("TODD", 8631 "Disable child packages"); 8632} 8633 final int scannedChildCount = (pkg.childPackages != null) 8634 ? pkg.childPackages.size() : 0; 8635 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8636 ? disabledPkgSetting.childPackageNames.size() : 0; 8637 for (int i = 0; i < disabledChildCount; i++) { 8638 String disabledChildPackageName = 8639 disabledPkgSetting.childPackageNames.get(i); 8640 boolean disabledPackageAvailable = false; 8641 for (int j = 0; j < scannedChildCount; j++) { 8642 PackageParser.Package childPkg = pkg.childPackages.get(j); 8643 if (childPkg.packageName.equals(disabledChildPackageName)) { 8644if (REFACTOR_DEBUG) { 8645Slog.e("TODD", 8646 "Ignore " + disabledChildPackageName); 8647} 8648 disabledPackageAvailable = true; 8649 break; 8650 } 8651 } 8652 if (!disabledPackageAvailable) { 8653if (REFACTOR_DEBUG) { 8654Slog.e("TODD", 8655 "Disable " + disabledChildPackageName); 8656} 8657 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8658 } 8659 } 8660 // we're updating the disabled package, so, scan it as the package setting 8661 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8662 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8663 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8664 (pkg == mPlatformPackage), user); 8665if (REFACTOR_DEBUG) { 8666Slog.e("TODD", 8667 "Scan disabled system package"); 8668Slog.e("TODD", 8669 "Pre: " + request.pkgSetting.dumpState_temp()); 8670} 8671final ScanResult result = 8672 scanPackageOnlyLI(request, mFactoryTest, -1L); 8673if (REFACTOR_DEBUG) { 8674Slog.e("TODD", 8675 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8676} 8677 } 8678 } 8679 } 8680 8681 final boolean newPkgChangedPaths = 8682 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8683if (REFACTOR_DEBUG) { 8684Slog.e("TODD", 8685 "paths changed? " + newPkgChangedPaths 8686 + "; old: " + pkg.codePath 8687 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8688} 8689 final boolean newPkgVersionGreater = 8690 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8691if (REFACTOR_DEBUG) { 8692Slog.e("TODD", 8693 "version greater? " + newPkgVersionGreater 8694 + "; old: " + pkg.getLongVersionCode() 8695 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8696} 8697 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8698 && newPkgChangedPaths && newPkgVersionGreater; 8699if (REFACTOR_DEBUG) { 8700 Slog.e("TODD", 8701 "system better? " + isSystemPkgBetter); 8702} 8703 if (isSystemPkgBetter) { 8704 // The version of the application on /system is greater than the version on 8705 // /data. Switch back to the application on /system. 8706 // It's safe to assume the application on /system will correctly scan. If not, 8707 // there won't be a working copy of the application. 8708 synchronized (mPackages) { 8709 // just remove the loaded entries from package lists 8710 mPackages.remove(pkgSetting.name); 8711 } 8712 8713 logCriticalInfo(Log.WARN, 8714 "System package updated;" 8715 + " name: " + pkgSetting.name 8716 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8717 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8718if (REFACTOR_DEBUG) { 8719Slog.e("TODD", 8720 "System package changed;" 8721 + " name: " + pkgSetting.name 8722 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8723 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8724} 8725 8726 final InstallArgs args = createInstallArgsForExisting( 8727 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8728 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8729 args.cleanUpResourcesLI(); 8730 synchronized (mPackages) { 8731 mSettings.enableSystemPackageLPw(pkgSetting.name); 8732 } 8733 } 8734 8735 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8736if (REFACTOR_DEBUG) { 8737Slog.e("TODD", 8738 "THROW exception; system pkg version not good enough"); 8739} 8740 // The version of the application on the /system partition is less than or 8741 // equal to the version on the /data partition. Throw an exception and use 8742 // the application already installed on the /data partition. 8743 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8744 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8745 + " better than this " + pkg.getLongVersionCode()); 8746 } 8747 8748 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8749 // force re-collecting certificate. Full apk verification will happen unless apk verity is 8750 // set up for the file. In that case, only small part of the apk is verified upfront. 8751 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8752 disabledPkgSetting); 8753 collectCertificatesLI(pkgSetting, pkg, forceCollect); 8754 8755 boolean shouldHideSystemApp = false; 8756 // A new application appeared on /system, but, we already have a copy of 8757 // the application installed on /data. 8758 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8759 && !pkgSetting.isSystem()) { 8760 // if the signatures don't match, wipe the installed application and its data 8761 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8762 pkg.mSigningDetails.signatures) 8763 != PackageManager.SIGNATURE_MATCH) { 8764 logCriticalInfo(Log.WARN, 8765 "System package signature mismatch;" 8766 + " name: " + pkgSetting.name); 8767if (REFACTOR_DEBUG) { 8768Slog.e("TODD", 8769 "System package signature mismatch;" 8770 + " name: " + pkgSetting.name); 8771} 8772 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8773 "scanPackageInternalLI")) { 8774 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8775 } 8776 pkgSetting = null; 8777 } else if (newPkgVersionGreater) { 8778 // The application on /system is newer than the application on /data. 8779 // Simply remove the application on /data [keeping application data] 8780 // and replace it with the version on /system. 8781 logCriticalInfo(Log.WARN, 8782 "System package enabled;" 8783 + " name: " + pkgSetting.name 8784 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8785 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8786if (REFACTOR_DEBUG) { 8787Slog.e("TODD", 8788 "System package enabled;" 8789 + " name: " + pkgSetting.name 8790 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8791 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8792} 8793 InstallArgs args = createInstallArgsForExisting( 8794 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8795 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8796 synchronized (mInstallLock) { 8797 args.cleanUpResourcesLI(); 8798 } 8799 } else { 8800 // The application on /system is older than the application on /data. Hide 8801 // the application on /system and the version on /data will be scanned later 8802 // and re-added like an update. 8803 shouldHideSystemApp = true; 8804 logCriticalInfo(Log.INFO, 8805 "System package disabled;" 8806 + " name: " + pkgSetting.name 8807 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8808 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8809if (REFACTOR_DEBUG) { 8810Slog.e("TODD", 8811 "System package disabled;" 8812 + " name: " + pkgSetting.name 8813 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8814 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8815} 8816 } 8817 } 8818 8819if (REFACTOR_DEBUG) { 8820Slog.e("TODD", 8821 "Scan package"); 8822Slog.e("TODD", 8823 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8824} 8825 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8826 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8827if (REFACTOR_DEBUG) { 8828pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8829Slog.e("TODD", 8830 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8831} 8832 8833 if (shouldHideSystemApp) { 8834if (REFACTOR_DEBUG) { 8835Slog.e("TODD", 8836 "Disable package: " + pkg.packageName); 8837} 8838 synchronized (mPackages) { 8839 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8840 } 8841 } 8842 return scannedPkg; 8843 } 8844 8845 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8846 // Derive the new package synthetic package name 8847 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8848 + pkg.staticSharedLibVersion); 8849 } 8850 8851 private static String fixProcessName(String defProcessName, 8852 String processName) { 8853 if (processName == null) { 8854 return defProcessName; 8855 } 8856 return processName; 8857 } 8858 8859 /** 8860 * Enforces that only the system UID or root's UID can call a method exposed 8861 * via Binder. 8862 * 8863 * @param message used as message if SecurityException is thrown 8864 * @throws SecurityException if the caller is not system or root 8865 */ 8866 private static final void enforceSystemOrRoot(String message) { 8867 final int uid = Binder.getCallingUid(); 8868 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8869 throw new SecurityException(message); 8870 } 8871 } 8872 8873 @Override 8874 public void performFstrimIfNeeded() { 8875 enforceSystemOrRoot("Only the system can request fstrim"); 8876 8877 // Before everything else, see whether we need to fstrim. 8878 try { 8879 IStorageManager sm = PackageHelper.getStorageManager(); 8880 if (sm != null) { 8881 boolean doTrim = false; 8882 final long interval = android.provider.Settings.Global.getLong( 8883 mContext.getContentResolver(), 8884 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8885 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8886 if (interval > 0) { 8887 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8888 if (timeSinceLast > interval) { 8889 doTrim = true; 8890 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8891 + "; running immediately"); 8892 } 8893 } 8894 if (doTrim) { 8895 final boolean dexOptDialogShown; 8896 synchronized (mPackages) { 8897 dexOptDialogShown = mDexOptDialogShown; 8898 } 8899 if (!isFirstBoot() && dexOptDialogShown) { 8900 try { 8901 ActivityManager.getService().showBootMessage( 8902 mContext.getResources().getString( 8903 R.string.android_upgrading_fstrim), true); 8904 } catch (RemoteException e) { 8905 } 8906 } 8907 sm.runMaintenance(); 8908 } 8909 } else { 8910 Slog.e(TAG, "storageManager service unavailable!"); 8911 } 8912 } catch (RemoteException e) { 8913 // Can't happen; StorageManagerService is local 8914 } 8915 } 8916 8917 @Override 8918 public void updatePackagesIfNeeded() { 8919 enforceSystemOrRoot("Only the system can request package update"); 8920 8921 // We need to re-extract after an OTA. 8922 boolean causeUpgrade = isUpgrade(); 8923 8924 // First boot or factory reset. 8925 // Note: we also handle devices that are upgrading to N right now as if it is their 8926 // first boot, as they do not have profile data. 8927 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8928 8929 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8930 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8931 8932 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8933 return; 8934 } 8935 8936 List<PackageParser.Package> pkgs; 8937 synchronized (mPackages) { 8938 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8939 } 8940 8941 final long startTime = System.nanoTime(); 8942 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8943 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8944 false /* bootComplete */); 8945 8946 final int elapsedTimeSeconds = 8947 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8948 8949 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8950 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8951 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8952 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8953 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8954 } 8955 8956 /* 8957 * Return the prebuilt profile path given a package base code path. 8958 */ 8959 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8960 return pkg.baseCodePath + ".prof"; 8961 } 8962 8963 /** 8964 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8965 * containing statistics about the invocation. The array consists of three elements, 8966 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8967 * and {@code numberOfPackagesFailed}. 8968 */ 8969 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8970 final String compilerFilter, boolean bootComplete) { 8971 8972 int numberOfPackagesVisited = 0; 8973 int numberOfPackagesOptimized = 0; 8974 int numberOfPackagesSkipped = 0; 8975 int numberOfPackagesFailed = 0; 8976 final int numberOfPackagesToDexopt = pkgs.size(); 8977 8978 for (PackageParser.Package pkg : pkgs) { 8979 numberOfPackagesVisited++; 8980 8981 boolean useProfileForDexopt = false; 8982 8983 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8984 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8985 // that are already compiled. 8986 File profileFile = new File(getPrebuildProfilePath(pkg)); 8987 // Copy profile if it exists. 8988 if (profileFile.exists()) { 8989 try { 8990 // We could also do this lazily before calling dexopt in 8991 // PackageDexOptimizer to prevent this happening on first boot. The issue 8992 // is that we don't have a good way to say "do this only once". 8993 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8994 pkg.applicationInfo.uid, pkg.packageName, 8995 ArtManager.getProfileName(null))) { 8996 Log.e(TAG, "Installer failed to copy system profile!"); 8997 } else { 8998 // Disabled as this causes speed-profile compilation during first boot 8999 // even if things are already compiled. 9000 // useProfileForDexopt = true; 9001 } 9002 } catch (Exception e) { 9003 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 9004 e); 9005 } 9006 } else { 9007 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9008 // Handle compressed APKs in this path. Only do this for stubs with profiles to 9009 // minimize the number off apps being speed-profile compiled during first boot. 9010 // The other paths will not change the filter. 9011 if (disabledPs != null && disabledPs.pkg.isStub) { 9012 // The package is the stub one, remove the stub suffix to get the normal 9013 // package and APK names. 9014 String systemProfilePath = 9015 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9016 profileFile = new File(systemProfilePath); 9017 // If we have a profile for a compressed APK, copy it to the reference 9018 // location. 9019 // Note that copying the profile here will cause it to override the 9020 // reference profile every OTA even though the existing reference profile 9021 // may have more data. We can't copy during decompression since the 9022 // directories are not set up at that point. 9023 if (profileFile.exists()) { 9024 try { 9025 // We could also do this lazily before calling dexopt in 9026 // PackageDexOptimizer to prevent this happening on first boot. The 9027 // issue is that we don't have a good way to say "do this only 9028 // once". 9029 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9030 pkg.applicationInfo.uid, pkg.packageName, 9031 ArtManager.getProfileName(null))) { 9032 Log.e(TAG, "Failed to copy system profile for stub package!"); 9033 } else { 9034 useProfileForDexopt = true; 9035 } 9036 } catch (Exception e) { 9037 Log.e(TAG, "Failed to copy profile " + 9038 profileFile.getAbsolutePath() + " ", e); 9039 } 9040 } 9041 } 9042 } 9043 } 9044 9045 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9046 if (DEBUG_DEXOPT) { 9047 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9048 } 9049 numberOfPackagesSkipped++; 9050 continue; 9051 } 9052 9053 if (DEBUG_DEXOPT) { 9054 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9055 numberOfPackagesToDexopt + ": " + pkg.packageName); 9056 } 9057 9058 if (showDialog) { 9059 try { 9060 ActivityManager.getService().showBootMessage( 9061 mContext.getResources().getString(R.string.android_upgrading_apk, 9062 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9063 } catch (RemoteException e) { 9064 } 9065 synchronized (mPackages) { 9066 mDexOptDialogShown = true; 9067 } 9068 } 9069 9070 String pkgCompilerFilter = compilerFilter; 9071 if (useProfileForDexopt) { 9072 // Use background dexopt mode to try and use the profile. Note that this does not 9073 // guarantee usage of the profile. 9074 pkgCompilerFilter = 9075 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9076 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9077 } 9078 9079 // checkProfiles is false to avoid merging profiles during boot which 9080 // might interfere with background compilation (b/28612421). 9081 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9082 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9083 // trade-off worth doing to save boot time work. 9084 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9085 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9086 pkg.packageName, 9087 pkgCompilerFilter, 9088 dexoptFlags)); 9089 9090 switch (primaryDexOptStaus) { 9091 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9092 numberOfPackagesOptimized++; 9093 break; 9094 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9095 numberOfPackagesSkipped++; 9096 break; 9097 case PackageDexOptimizer.DEX_OPT_FAILED: 9098 numberOfPackagesFailed++; 9099 break; 9100 default: 9101 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9102 break; 9103 } 9104 } 9105 9106 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9107 numberOfPackagesFailed }; 9108 } 9109 9110 @Override 9111 public void notifyPackageUse(String packageName, int reason) { 9112 synchronized (mPackages) { 9113 final int callingUid = Binder.getCallingUid(); 9114 final int callingUserId = UserHandle.getUserId(callingUid); 9115 if (getInstantAppPackageName(callingUid) != null) { 9116 if (!isCallerSameApp(packageName, callingUid)) { 9117 return; 9118 } 9119 } else { 9120 if (isInstantApp(packageName, callingUserId)) { 9121 return; 9122 } 9123 } 9124 notifyPackageUseLocked(packageName, reason); 9125 } 9126 } 9127 9128 private void notifyPackageUseLocked(String packageName, int reason) { 9129 final PackageParser.Package p = mPackages.get(packageName); 9130 if (p == null) { 9131 return; 9132 } 9133 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9134 } 9135 9136 @Override 9137 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9138 List<String> classPaths, String loaderIsa) { 9139 int userId = UserHandle.getCallingUserId(); 9140 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9141 if (ai == null) { 9142 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9143 + loadingPackageName + ", user=" + userId); 9144 return; 9145 } 9146 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9147 } 9148 9149 @Override 9150 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9151 IDexModuleRegisterCallback callback) { 9152 int userId = UserHandle.getCallingUserId(); 9153 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9154 DexManager.RegisterDexModuleResult result; 9155 if (ai == null) { 9156 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9157 " calling user. package=" + packageName + ", user=" + userId); 9158 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9159 } else { 9160 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9161 } 9162 9163 if (callback != null) { 9164 mHandler.post(() -> { 9165 try { 9166 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9167 } catch (RemoteException e) { 9168 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9169 } 9170 }); 9171 } 9172 } 9173 9174 /** 9175 * Ask the package manager to perform a dex-opt with the given compiler filter. 9176 * 9177 * Note: exposed only for the shell command to allow moving packages explicitly to a 9178 * definite state. 9179 */ 9180 @Override 9181 public boolean performDexOptMode(String packageName, 9182 boolean checkProfiles, String targetCompilerFilter, boolean force, 9183 boolean bootComplete, String splitName) { 9184 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9185 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9186 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9187 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9188 splitName, flags)); 9189 } 9190 9191 /** 9192 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9193 * secondary dex files belonging to the given package. 9194 * 9195 * Note: exposed only for the shell command to allow moving packages explicitly to a 9196 * definite state. 9197 */ 9198 @Override 9199 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9200 boolean force) { 9201 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9202 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9203 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9204 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9205 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9206 } 9207 9208 /*package*/ boolean performDexOpt(DexoptOptions options) { 9209 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9210 return false; 9211 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9212 return false; 9213 } 9214 9215 if (options.isDexoptOnlySecondaryDex()) { 9216 return mDexManager.dexoptSecondaryDex(options); 9217 } else { 9218 int dexoptStatus = performDexOptWithStatus(options); 9219 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9220 } 9221 } 9222 9223 /** 9224 * Perform dexopt on the given package and return one of following result: 9225 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9226 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9227 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9228 */ 9229 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9230 return performDexOptTraced(options); 9231 } 9232 9233 private int performDexOptTraced(DexoptOptions options) { 9234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9235 try { 9236 return performDexOptInternal(options); 9237 } finally { 9238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9239 } 9240 } 9241 9242 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9243 // if the package can now be considered up to date for the given filter. 9244 private int performDexOptInternal(DexoptOptions options) { 9245 PackageParser.Package p; 9246 synchronized (mPackages) { 9247 p = mPackages.get(options.getPackageName()); 9248 if (p == null) { 9249 // Package could not be found. Report failure. 9250 return PackageDexOptimizer.DEX_OPT_FAILED; 9251 } 9252 mPackageUsage.maybeWriteAsync(mPackages); 9253 mCompilerStats.maybeWriteAsync(); 9254 } 9255 long callingId = Binder.clearCallingIdentity(); 9256 try { 9257 synchronized (mInstallLock) { 9258 return performDexOptInternalWithDependenciesLI(p, options); 9259 } 9260 } finally { 9261 Binder.restoreCallingIdentity(callingId); 9262 } 9263 } 9264 9265 public ArraySet<String> getOptimizablePackages() { 9266 ArraySet<String> pkgs = new ArraySet<String>(); 9267 synchronized (mPackages) { 9268 for (PackageParser.Package p : mPackages.values()) { 9269 if (PackageDexOptimizer.canOptimizePackage(p)) { 9270 pkgs.add(p.packageName); 9271 } 9272 } 9273 } 9274 return pkgs; 9275 } 9276 9277 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9278 DexoptOptions options) { 9279 // Select the dex optimizer based on the force parameter. 9280 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9281 // allocate an object here. 9282 PackageDexOptimizer pdo = options.isForce() 9283 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9284 : mPackageDexOptimizer; 9285 9286 // Dexopt all dependencies first. Note: we ignore the return value and march on 9287 // on errors. 9288 // Note that we are going to call performDexOpt on those libraries as many times as 9289 // they are referenced in packages. When we do a batch of performDexOpt (for example 9290 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9291 // and the first package that uses the library will dexopt it. The 9292 // others will see that the compiled code for the library is up to date. 9293 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9294 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9295 if (!deps.isEmpty()) { 9296 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9297 options.getCompilerFilter(), options.getSplitName(), 9298 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9299 for (PackageParser.Package depPackage : deps) { 9300 // TODO: Analyze and investigate if we (should) profile libraries. 9301 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9302 getOrCreateCompilerPackageStats(depPackage), 9303 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9304 } 9305 } 9306 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9307 getOrCreateCompilerPackageStats(p), 9308 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9309 } 9310 9311 /** 9312 * Reconcile the information we have about the secondary dex files belonging to 9313 * {@code packagName} and the actual dex files. For all dex files that were 9314 * deleted, update the internal records and delete the generated oat files. 9315 */ 9316 @Override 9317 public void reconcileSecondaryDexFiles(String packageName) { 9318 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9319 return; 9320 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9321 return; 9322 } 9323 mDexManager.reconcileSecondaryDexFiles(packageName); 9324 } 9325 9326 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9327 // a reference there. 9328 /*package*/ DexManager getDexManager() { 9329 return mDexManager; 9330 } 9331 9332 /** 9333 * Execute the background dexopt job immediately. 9334 */ 9335 @Override 9336 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9337 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9338 return false; 9339 } 9340 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9341 } 9342 9343 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9344 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9345 || p.usesStaticLibraries != null) { 9346 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9347 Set<String> collectedNames = new HashSet<>(); 9348 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9349 9350 retValue.remove(p); 9351 9352 return retValue; 9353 } else { 9354 return Collections.emptyList(); 9355 } 9356 } 9357 9358 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9359 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9360 if (!collectedNames.contains(p.packageName)) { 9361 collectedNames.add(p.packageName); 9362 collected.add(p); 9363 9364 if (p.usesLibraries != null) { 9365 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9366 null, collected, collectedNames); 9367 } 9368 if (p.usesOptionalLibraries != null) { 9369 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9370 null, collected, collectedNames); 9371 } 9372 if (p.usesStaticLibraries != null) { 9373 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9374 p.usesStaticLibrariesVersions, collected, collectedNames); 9375 } 9376 } 9377 } 9378 9379 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9380 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9381 final int libNameCount = libs.size(); 9382 for (int i = 0; i < libNameCount; i++) { 9383 String libName = libs.get(i); 9384 long version = (versions != null && versions.length == libNameCount) 9385 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9386 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9387 if (libPkg != null) { 9388 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9389 } 9390 } 9391 } 9392 9393 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9394 synchronized (mPackages) { 9395 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9396 if (libEntry != null) { 9397 return mPackages.get(libEntry.apk); 9398 } 9399 return null; 9400 } 9401 } 9402 9403 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9404 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9405 if (versionedLib == null) { 9406 return null; 9407 } 9408 return versionedLib.get(version); 9409 } 9410 9411 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9412 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9413 pkg.staticSharedLibName); 9414 if (versionedLib == null) { 9415 return null; 9416 } 9417 long previousLibVersion = -1; 9418 final int versionCount = versionedLib.size(); 9419 for (int i = 0; i < versionCount; i++) { 9420 final long libVersion = versionedLib.keyAt(i); 9421 if (libVersion < pkg.staticSharedLibVersion) { 9422 previousLibVersion = Math.max(previousLibVersion, libVersion); 9423 } 9424 } 9425 if (previousLibVersion >= 0) { 9426 return versionedLib.get(previousLibVersion); 9427 } 9428 return null; 9429 } 9430 9431 public void shutdown() { 9432 mPackageUsage.writeNow(mPackages); 9433 mCompilerStats.writeNow(); 9434 mDexManager.writePackageDexUsageNow(); 9435 } 9436 9437 @Override 9438 public void dumpProfiles(String packageName) { 9439 PackageParser.Package pkg; 9440 synchronized (mPackages) { 9441 pkg = mPackages.get(packageName); 9442 if (pkg == null) { 9443 throw new IllegalArgumentException("Unknown package: " + packageName); 9444 } 9445 } 9446 /* Only the shell, root, or the app user should be able to dump profiles. */ 9447 int callingUid = Binder.getCallingUid(); 9448 if (callingUid != Process.SHELL_UID && 9449 callingUid != Process.ROOT_UID && 9450 callingUid != pkg.applicationInfo.uid) { 9451 throw new SecurityException("dumpProfiles"); 9452 } 9453 9454 synchronized (mInstallLock) { 9455 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9456 mArtManagerService.dumpProfiles(pkg); 9457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9458 } 9459 } 9460 9461 @Override 9462 public void forceDexOpt(String packageName) { 9463 enforceSystemOrRoot("forceDexOpt"); 9464 9465 PackageParser.Package pkg; 9466 synchronized (mPackages) { 9467 pkg = mPackages.get(packageName); 9468 if (pkg == null) { 9469 throw new IllegalArgumentException("Unknown package: " + packageName); 9470 } 9471 } 9472 9473 synchronized (mInstallLock) { 9474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9475 9476 // Whoever is calling forceDexOpt wants a compiled package. 9477 // Don't use profiles since that may cause compilation to be skipped. 9478 final int res = performDexOptInternalWithDependenciesLI( 9479 pkg, 9480 new DexoptOptions(packageName, 9481 getDefaultCompilerFilter(), 9482 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9483 9484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9485 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9486 throw new IllegalStateException("Failed to dexopt: " + res); 9487 } 9488 } 9489 } 9490 9491 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9492 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9493 Slog.w(TAG, "Unable to update from " + oldPkg.name 9494 + " to " + newPkg.packageName 9495 + ": old package not in system partition"); 9496 return false; 9497 } else if (mPackages.get(oldPkg.name) != null) { 9498 Slog.w(TAG, "Unable to update from " + oldPkg.name 9499 + " to " + newPkg.packageName 9500 + ": old package still exists"); 9501 return false; 9502 } 9503 return true; 9504 } 9505 9506 void removeCodePathLI(File codePath) { 9507 if (codePath.isDirectory()) { 9508 try { 9509 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9510 } catch (InstallerException e) { 9511 Slog.w(TAG, "Failed to remove code path", e); 9512 } 9513 } else { 9514 codePath.delete(); 9515 } 9516 } 9517 9518 private int[] resolveUserIds(int userId) { 9519 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9520 } 9521 9522 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9523 if (pkg == null) { 9524 Slog.wtf(TAG, "Package was null!", new Throwable()); 9525 return; 9526 } 9527 clearAppDataLeafLIF(pkg, userId, flags); 9528 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9529 for (int i = 0; i < childCount; i++) { 9530 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9531 } 9532 9533 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9534 } 9535 9536 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9537 final PackageSetting ps; 9538 synchronized (mPackages) { 9539 ps = mSettings.mPackages.get(pkg.packageName); 9540 } 9541 for (int realUserId : resolveUserIds(userId)) { 9542 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9543 try { 9544 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9545 ceDataInode); 9546 } catch (InstallerException e) { 9547 Slog.w(TAG, String.valueOf(e)); 9548 } 9549 } 9550 } 9551 9552 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9553 if (pkg == null) { 9554 Slog.wtf(TAG, "Package was null!", new Throwable()); 9555 return; 9556 } 9557 destroyAppDataLeafLIF(pkg, userId, flags); 9558 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9559 for (int i = 0; i < childCount; i++) { 9560 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9561 } 9562 } 9563 9564 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9565 final PackageSetting ps; 9566 synchronized (mPackages) { 9567 ps = mSettings.mPackages.get(pkg.packageName); 9568 } 9569 for (int realUserId : resolveUserIds(userId)) { 9570 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9571 try { 9572 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9573 ceDataInode); 9574 } catch (InstallerException e) { 9575 Slog.w(TAG, String.valueOf(e)); 9576 } 9577 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9578 } 9579 } 9580 9581 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9582 if (pkg == null) { 9583 Slog.wtf(TAG, "Package was null!", new Throwable()); 9584 return; 9585 } 9586 destroyAppProfilesLeafLIF(pkg); 9587 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9588 for (int i = 0; i < childCount; i++) { 9589 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9590 } 9591 } 9592 9593 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9594 try { 9595 mInstaller.destroyAppProfiles(pkg.packageName); 9596 } catch (InstallerException e) { 9597 Slog.w(TAG, String.valueOf(e)); 9598 } 9599 } 9600 9601 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9602 if (pkg == null) { 9603 Slog.wtf(TAG, "Package was null!", new Throwable()); 9604 return; 9605 } 9606 mArtManagerService.clearAppProfiles(pkg); 9607 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9608 for (int i = 0; i < childCount; i++) { 9609 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9610 } 9611 } 9612 9613 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9614 long lastUpdateTime) { 9615 // Set parent install/update time 9616 PackageSetting ps = (PackageSetting) pkg.mExtras; 9617 if (ps != null) { 9618 ps.firstInstallTime = firstInstallTime; 9619 ps.lastUpdateTime = lastUpdateTime; 9620 } 9621 // Set children install/update time 9622 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9623 for (int i = 0; i < childCount; i++) { 9624 PackageParser.Package childPkg = pkg.childPackages.get(i); 9625 ps = (PackageSetting) childPkg.mExtras; 9626 if (ps != null) { 9627 ps.firstInstallTime = firstInstallTime; 9628 ps.lastUpdateTime = lastUpdateTime; 9629 } 9630 } 9631 } 9632 9633 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9634 SharedLibraryEntry file, 9635 PackageParser.Package changingLib) { 9636 if (file.path != null) { 9637 usesLibraryFiles.add(file.path); 9638 return; 9639 } 9640 PackageParser.Package p = mPackages.get(file.apk); 9641 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9642 // If we are doing this while in the middle of updating a library apk, 9643 // then we need to make sure to use that new apk for determining the 9644 // dependencies here. (We haven't yet finished committing the new apk 9645 // to the package manager state.) 9646 if (p == null || p.packageName.equals(changingLib.packageName)) { 9647 p = changingLib; 9648 } 9649 } 9650 if (p != null) { 9651 usesLibraryFiles.addAll(p.getAllCodePaths()); 9652 if (p.usesLibraryFiles != null) { 9653 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9654 } 9655 } 9656 } 9657 9658 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9659 PackageParser.Package changingLib) throws PackageManagerException { 9660 if (pkg == null) { 9661 return; 9662 } 9663 // The collection used here must maintain the order of addition (so 9664 // that libraries are searched in the correct order) and must have no 9665 // duplicates. 9666 Set<String> usesLibraryFiles = null; 9667 if (pkg.usesLibraries != null) { 9668 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9669 null, null, pkg.packageName, changingLib, true, 9670 pkg.applicationInfo.targetSdkVersion, null); 9671 } 9672 if (pkg.usesStaticLibraries != null) { 9673 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9674 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9675 pkg.packageName, changingLib, true, 9676 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9677 } 9678 if (pkg.usesOptionalLibraries != null) { 9679 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9680 null, null, pkg.packageName, changingLib, false, 9681 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9682 } 9683 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9684 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9685 } else { 9686 pkg.usesLibraryFiles = null; 9687 } 9688 } 9689 9690 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9691 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9692 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9693 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9694 throws PackageManagerException { 9695 final int libCount = requestedLibraries.size(); 9696 for (int i = 0; i < libCount; i++) { 9697 final String libName = requestedLibraries.get(i); 9698 final long libVersion = requiredVersions != null ? requiredVersions[i] 9699 : SharedLibraryInfo.VERSION_UNDEFINED; 9700 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9701 if (libEntry == null) { 9702 if (required) { 9703 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9704 "Package " + packageName + " requires unavailable shared library " 9705 + libName + "; failing!"); 9706 } else if (DEBUG_SHARED_LIBRARIES) { 9707 Slog.i(TAG, "Package " + packageName 9708 + " desires unavailable shared library " 9709 + libName + "; ignoring!"); 9710 } 9711 } else { 9712 if (requiredVersions != null && requiredCertDigests != null) { 9713 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9714 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9715 "Package " + packageName + " requires unavailable static shared" 9716 + " library " + libName + " version " 9717 + libEntry.info.getLongVersion() + "; failing!"); 9718 } 9719 9720 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9721 if (libPkg == null) { 9722 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9723 "Package " + packageName + " requires unavailable static shared" 9724 + " library; failing!"); 9725 } 9726 9727 final String[] expectedCertDigests = requiredCertDigests[i]; 9728 // For apps targeting O MR1 we require explicit enumeration of all certs. 9729 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9730 ? PackageUtils.computeSignaturesSha256Digests( 9731 libPkg.mSigningDetails.signatures) 9732 : PackageUtils.computeSignaturesSha256Digests( 9733 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9734 9735 // Take a shortcut if sizes don't match. Note that if an app doesn't 9736 // target O we don't parse the "additional-certificate" tags similarly 9737 // how we only consider all certs only for apps targeting O (see above). 9738 // Therefore, the size check is safe to make. 9739 if (expectedCertDigests.length != libCertDigests.length) { 9740 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9741 "Package " + packageName + " requires differently signed" + 9742 " static shared library; failing!"); 9743 } 9744 9745 // Use a predictable order as signature order may vary 9746 Arrays.sort(libCertDigests); 9747 Arrays.sort(expectedCertDigests); 9748 9749 final int certCount = libCertDigests.length; 9750 for (int j = 0; j < certCount; j++) { 9751 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9752 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9753 "Package " + packageName + " requires differently signed" + 9754 " static shared library; failing!"); 9755 } 9756 } 9757 } 9758 9759 if (outUsedLibraries == null) { 9760 // Use LinkedHashSet to preserve the order of files added to 9761 // usesLibraryFiles while eliminating duplicates. 9762 outUsedLibraries = new LinkedHashSet<>(); 9763 } 9764 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9765 } 9766 } 9767 return outUsedLibraries; 9768 } 9769 9770 private static boolean hasString(List<String> list, List<String> which) { 9771 if (list == null) { 9772 return false; 9773 } 9774 for (int i=list.size()-1; i>=0; i--) { 9775 for (int j=which.size()-1; j>=0; j--) { 9776 if (which.get(j).equals(list.get(i))) { 9777 return true; 9778 } 9779 } 9780 } 9781 return false; 9782 } 9783 9784 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9785 PackageParser.Package changingPkg) { 9786 ArrayList<PackageParser.Package> res = null; 9787 for (PackageParser.Package pkg : mPackages.values()) { 9788 if (changingPkg != null 9789 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9790 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9791 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9792 changingPkg.staticSharedLibName)) { 9793 return null; 9794 } 9795 if (res == null) { 9796 res = new ArrayList<>(); 9797 } 9798 res.add(pkg); 9799 try { 9800 updateSharedLibrariesLPr(pkg, changingPkg); 9801 } catch (PackageManagerException e) { 9802 // If a system app update or an app and a required lib missing we 9803 // delete the package and for updated system apps keep the data as 9804 // it is better for the user to reinstall than to be in an limbo 9805 // state. Also libs disappearing under an app should never happen 9806 // - just in case. 9807 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9808 final int flags = pkg.isUpdatedSystemApp() 9809 ? PackageManager.DELETE_KEEP_DATA : 0; 9810 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9811 flags , null, true, null); 9812 } 9813 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9814 } 9815 } 9816 return res; 9817 } 9818 9819 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9820 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9821 @Nullable UserHandle user) throws PackageManagerException { 9822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9823 // If the package has children and this is the first dive in the function 9824 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9825 // whether all packages (parent and children) would be successfully scanned 9826 // before the actual scan since scanning mutates internal state and we want 9827 // to atomically install the package and its children. 9828 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9829 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9830 scanFlags |= SCAN_CHECK_ONLY; 9831 } 9832 } else { 9833 scanFlags &= ~SCAN_CHECK_ONLY; 9834 } 9835 9836 final PackageParser.Package scannedPkg; 9837 try { 9838 // Scan the parent 9839 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9840 // Scan the children 9841 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9842 for (int i = 0; i < childCount; i++) { 9843 PackageParser.Package childPkg = pkg.childPackages.get(i); 9844 scanPackageNewLI(childPkg, parseFlags, 9845 scanFlags, currentTime, user); 9846 } 9847 } finally { 9848 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9849 } 9850 9851 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9852 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9853 } 9854 9855 return scannedPkg; 9856 } 9857 9858 /** The result of a package scan. */ 9859 private static class ScanResult { 9860 /** Whether or not the package scan was successful */ 9861 public final boolean success; 9862 /** 9863 * The final package settings. This may be the same object passed in 9864 * the {@link ScanRequest}, but, with modified values. 9865 */ 9866 @Nullable public final PackageSetting pkgSetting; 9867 /** ABI code paths that have changed in the package scan */ 9868 @Nullable public final List<String> changedAbiCodePath; 9869 public ScanResult( 9870 boolean success, 9871 @Nullable PackageSetting pkgSetting, 9872 @Nullable List<String> changedAbiCodePath) { 9873 this.success = success; 9874 this.pkgSetting = pkgSetting; 9875 this.changedAbiCodePath = changedAbiCodePath; 9876 } 9877 } 9878 9879 /** A package to be scanned */ 9880 private static class ScanRequest { 9881 /** The parsed package */ 9882 @NonNull public final PackageParser.Package pkg; 9883 /** Shared user settings, if the package has a shared user */ 9884 @Nullable public final SharedUserSetting sharedUserSetting; 9885 /** 9886 * Package settings of the currently installed version. 9887 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9888 * during scan. 9889 */ 9890 @Nullable public final PackageSetting pkgSetting; 9891 /** A copy of the settings for the currently installed version */ 9892 @Nullable public final PackageSetting oldPkgSetting; 9893 /** Package settings for the disabled version on the /system partition */ 9894 @Nullable public final PackageSetting disabledPkgSetting; 9895 /** Package settings for the installed version under its original package name */ 9896 @Nullable public final PackageSetting originalPkgSetting; 9897 /** The real package name of a renamed application */ 9898 @Nullable public final String realPkgName; 9899 public final @ParseFlags int parseFlags; 9900 public final @ScanFlags int scanFlags; 9901 /** The user for which the package is being scanned */ 9902 @Nullable public final UserHandle user; 9903 /** Whether or not the platform package is being scanned */ 9904 public final boolean isPlatformPackage; 9905 public ScanRequest( 9906 @NonNull PackageParser.Package pkg, 9907 @Nullable SharedUserSetting sharedUserSetting, 9908 @Nullable PackageSetting pkgSetting, 9909 @Nullable PackageSetting disabledPkgSetting, 9910 @Nullable PackageSetting originalPkgSetting, 9911 @Nullable String realPkgName, 9912 @ParseFlags int parseFlags, 9913 @ScanFlags int scanFlags, 9914 boolean isPlatformPackage, 9915 @Nullable UserHandle user) { 9916 this.pkg = pkg; 9917 this.pkgSetting = pkgSetting; 9918 this.sharedUserSetting = sharedUserSetting; 9919 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9920 this.disabledPkgSetting = disabledPkgSetting; 9921 this.originalPkgSetting = originalPkgSetting; 9922 this.realPkgName = realPkgName; 9923 this.parseFlags = parseFlags; 9924 this.scanFlags = scanFlags; 9925 this.isPlatformPackage = isPlatformPackage; 9926 this.user = user; 9927 } 9928 } 9929 9930 /** 9931 * Returns the actual scan flags depending upon the state of the other settings. 9932 * <p>Updated system applications will not have the following flags set 9933 * by default and need to be adjusted after the fact: 9934 * <ul> 9935 * <li>{@link #SCAN_AS_SYSTEM}</li> 9936 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9937 * <li>{@link #SCAN_AS_OEM}</li> 9938 * <li>{@link #SCAN_AS_VENDOR}</li> 9939 * <li>{@link #SCAN_AS_PRODUCT}</li> 9940 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9941 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9942 * </ul> 9943 */ 9944 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9945 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9946 PackageParser.Package pkg) { 9947 if (disabledPkgSetting != null) { 9948 // updated system application, must at least have SCAN_AS_SYSTEM 9949 scanFlags |= SCAN_AS_SYSTEM; 9950 if ((disabledPkgSetting.pkgPrivateFlags 9951 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9952 scanFlags |= SCAN_AS_PRIVILEGED; 9953 } 9954 if ((disabledPkgSetting.pkgPrivateFlags 9955 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9956 scanFlags |= SCAN_AS_OEM; 9957 } 9958 if ((disabledPkgSetting.pkgPrivateFlags 9959 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9960 scanFlags |= SCAN_AS_VENDOR; 9961 } 9962 if ((disabledPkgSetting.pkgPrivateFlags 9963 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9964 scanFlags |= SCAN_AS_PRODUCT; 9965 } 9966 } 9967 if (pkgSetting != null) { 9968 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9969 if (pkgSetting.getInstantApp(userId)) { 9970 scanFlags |= SCAN_AS_INSTANT_APP; 9971 } 9972 if (pkgSetting.getVirtulalPreload(userId)) { 9973 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9974 } 9975 } 9976 9977 // Scan as privileged apps that share a user with a priv-app. 9978 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9979 && (pkg.mSharedUserId != null)) { 9980 SharedUserSetting sharedUserSetting = null; 9981 try { 9982 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9983 } catch (PackageManagerException ignore) {} 9984 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9985 // Exempt SharedUsers signed with the platform key. 9986 // TODO(b/72378145) Fix this exemption. Force signature apps 9987 // to whitelist their privileged permissions just like other 9988 // priv-apps. 9989 synchronized (mPackages) { 9990 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9991 if (!pkg.packageName.equals("android") 9992 && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9993 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9994 scanFlags |= SCAN_AS_PRIVILEGED; 9995 } 9996 } 9997 } 9998 } 9999 10000 return scanFlags; 10001 } 10002 10003 @GuardedBy("mInstallLock") 10004 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 10005 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10006 @Nullable UserHandle user) throws PackageManagerException { 10007 10008 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10009 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 10010 if (realPkgName != null) { 10011 ensurePackageRenamed(pkg, renamedPkgName); 10012 } 10013 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10014 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10015 final PackageSetting disabledPkgSetting = 10016 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10017 10018 if (mTransferedPackages.contains(pkg.packageName)) { 10019 Slog.w(TAG, "Package " + pkg.packageName 10020 + " was transferred to another, but its .apk remains"); 10021 } 10022 10023 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10024 synchronized (mPackages) { 10025 applyPolicy(pkg, parseFlags, scanFlags); 10026 assertPackageIsValid(pkg, parseFlags, scanFlags); 10027 10028 SharedUserSetting sharedUserSetting = null; 10029 if (pkg.mSharedUserId != null) { 10030 // SIDE EFFECTS; may potentially allocate a new shared user 10031 sharedUserSetting = mSettings.getSharedUserLPw( 10032 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10033 if (DEBUG_PACKAGE_SCANNING) { 10034 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10035 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10036 + " (uid=" + sharedUserSetting.userId + "):" 10037 + " packages=" + sharedUserSetting.packages); 10038 } 10039 } 10040 10041 boolean scanSucceeded = false; 10042 try { 10043 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10044 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10045 (pkg == mPlatformPackage), user); 10046 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10047 if (result.success) { 10048 commitScanResultsLocked(request, result); 10049 } 10050 scanSucceeded = true; 10051 } finally { 10052 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10053 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10054 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10056 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10057 } 10058 } 10059 } 10060 return pkg; 10061 } 10062 10063 /** 10064 * Commits the package scan and modifies system state. 10065 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10066 * of committing the package, leaving the system in an inconsistent state. 10067 * This needs to be fixed so, once we get to this point, no errors are 10068 * possible and the system is not left in an inconsistent state. 10069 */ 10070 @GuardedBy("mPackages") 10071 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10072 throws PackageManagerException { 10073 final PackageParser.Package pkg = request.pkg; 10074 final @ParseFlags int parseFlags = request.parseFlags; 10075 final @ScanFlags int scanFlags = request.scanFlags; 10076 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10077 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10078 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10079 final UserHandle user = request.user; 10080 final String realPkgName = request.realPkgName; 10081 final PackageSetting pkgSetting = result.pkgSetting; 10082 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10083 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10084 10085 if (newPkgSettingCreated) { 10086 if (originalPkgSetting != null) { 10087 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10088 } 10089 // THROWS: when we can't allocate a user id. add call to check if there's 10090 // enough space to ensure we won't throw; otherwise, don't modify state 10091 mSettings.addUserToSettingLPw(pkgSetting); 10092 10093 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10094 mTransferedPackages.add(originalPkgSetting.name); 10095 } 10096 } 10097 // TODO(toddke): Consider a method specifically for modifying the Package object 10098 // post scan; or, moving this stuff out of the Package object since it has nothing 10099 // to do with the package on disk. 10100 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10101 // for creating the application ID. If we did this earlier, we would be saving the 10102 // correct ID. 10103 pkg.applicationInfo.uid = pkgSetting.appId; 10104 10105 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10106 10107 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10108 mTransferedPackages.add(pkg.packageName); 10109 } 10110 10111 // THROWS: when requested libraries that can't be found. it only changes 10112 // the state of the passed in pkg object, so, move to the top of the method 10113 // and allow it to abort 10114 if ((scanFlags & SCAN_BOOTING) == 0 10115 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10116 // Check all shared libraries and map to their actual file path. 10117 // We only do this here for apps not on a system dir, because those 10118 // are the only ones that can fail an install due to this. We 10119 // will take care of the system apps by updating all of their 10120 // library paths after the scan is done. Also during the initial 10121 // scan don't update any libs as we do this wholesale after all 10122 // apps are scanned to avoid dependency based scanning. 10123 updateSharedLibrariesLPr(pkg, null); 10124 } 10125 10126 // All versions of a static shared library are referenced with the same 10127 // package name. Internally, we use a synthetic package name to allow 10128 // multiple versions of the same shared library to be installed. So, 10129 // we need to generate the synthetic package name of the latest shared 10130 // library in order to compare signatures. 10131 PackageSetting signatureCheckPs = pkgSetting; 10132 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10133 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10134 if (libraryEntry != null) { 10135 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10136 } 10137 } 10138 10139 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10140 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10141 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10142 // We just determined the app is signed correctly, so bring 10143 // over the latest parsed certs. 10144 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10145 } else { 10146 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10147 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10148 "Package " + pkg.packageName + " upgrade keys do not match the " 10149 + "previously installed version"); 10150 } else { 10151 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10152 String msg = "System package " + pkg.packageName 10153 + " signature changed; retaining data."; 10154 reportSettingsProblem(Log.WARN, msg); 10155 } 10156 } 10157 } else { 10158 try { 10159 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10160 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10161 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10162 pkg.mSigningDetails, compareCompat, compareRecover); 10163 // The new KeySets will be re-added later in the scanning process. 10164 if (compatMatch) { 10165 synchronized (mPackages) { 10166 ksms.removeAppKeySetDataLPw(pkg.packageName); 10167 } 10168 } 10169 // We just determined the app is signed correctly, so bring 10170 // over the latest parsed certs. 10171 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10172 } catch (PackageManagerException e) { 10173 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10174 throw e; 10175 } 10176 // The signature has changed, but this package is in the system 10177 // image... let's recover! 10178 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10179 // However... if this package is part of a shared user, but it 10180 // doesn't match the signature of the shared user, let's fail. 10181 // What this means is that you can't change the signatures 10182 // associated with an overall shared user, which doesn't seem all 10183 // that unreasonable. 10184 if (signatureCheckPs.sharedUser != null) { 10185 if (compareSignatures( 10186 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10187 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10188 throw new PackageManagerException( 10189 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10190 "Signature mismatch for shared user: " 10191 + pkgSetting.sharedUser); 10192 } 10193 } 10194 // File a report about this. 10195 String msg = "System package " + pkg.packageName 10196 + " signature changed; retaining data."; 10197 reportSettingsProblem(Log.WARN, msg); 10198 } 10199 } 10200 10201 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10202 // This package wants to adopt ownership of permissions from 10203 // another package. 10204 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10205 final String origName = pkg.mAdoptPermissions.get(i); 10206 final PackageSetting orig = mSettings.getPackageLPr(origName); 10207 if (orig != null) { 10208 if (verifyPackageUpdateLPr(orig, pkg)) { 10209 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10210 + pkg.packageName); 10211 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10212 } 10213 } 10214 } 10215 } 10216 10217 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10218 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10219 final String codePathString = changedAbiCodePath.get(i); 10220 try { 10221 mInstaller.rmdex(codePathString, 10222 getDexCodeInstructionSet(getPreferredInstructionSet())); 10223 } catch (InstallerException ignored) { 10224 } 10225 } 10226 } 10227 10228 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10229 if (oldPkgSetting != null) { 10230 synchronized (mPackages) { 10231 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10232 } 10233 } 10234 } else { 10235 final int userId = user == null ? 0 : user.getIdentifier(); 10236 // Modify state for the given package setting 10237 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10238 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10239 if (pkgSetting.getInstantApp(userId)) { 10240 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10241 } 10242 } 10243 } 10244 10245 /** 10246 * Returns the "real" name of the package. 10247 * <p>This may differ from the package's actual name if the application has already 10248 * been installed under one of this package's original names. 10249 */ 10250 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10251 @Nullable String renamedPkgName) { 10252 if (isPackageRenamed(pkg, renamedPkgName)) { 10253 return pkg.mRealPackage; 10254 } 10255 return null; 10256 } 10257 10258 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10259 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10260 @Nullable String renamedPkgName) { 10261 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10262 } 10263 10264 /** 10265 * Returns the original package setting. 10266 * <p>A package can migrate its name during an update. In this scenario, a package 10267 * designates a set of names that it considers as one of its original names. 10268 * <p>An original package must be signed identically and it must have the same 10269 * shared user [if any]. 10270 */ 10271 @GuardedBy("mPackages") 10272 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10273 @Nullable String renamedPkgName) { 10274 if (!isPackageRenamed(pkg, renamedPkgName)) { 10275 return null; 10276 } 10277 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10278 final PackageSetting originalPs = 10279 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10280 if (originalPs != null) { 10281 // the package is already installed under its original name... 10282 // but, should we use it? 10283 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10284 // the new package is incompatible with the original 10285 continue; 10286 } else if (originalPs.sharedUser != null) { 10287 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10288 // the shared user id is incompatible with the original 10289 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10290 + " to " + pkg.packageName + ": old uid " 10291 + originalPs.sharedUser.name 10292 + " differs from " + pkg.mSharedUserId); 10293 continue; 10294 } 10295 // TODO: Add case when shared user id is added [b/28144775] 10296 } else { 10297 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10298 + pkg.packageName + " to old name " + originalPs.name); 10299 } 10300 return originalPs; 10301 } 10302 } 10303 return null; 10304 } 10305 10306 /** 10307 * Renames the package if it was installed under a different name. 10308 * <p>When we've already installed the package under an original name, update 10309 * the new package so we can continue to have the old name. 10310 */ 10311 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10312 @NonNull String renamedPackageName) { 10313 if (pkg.mOriginalPackages == null 10314 || !pkg.mOriginalPackages.contains(renamedPackageName) 10315 || pkg.packageName.equals(renamedPackageName)) { 10316 return; 10317 } 10318 pkg.setPackageName(renamedPackageName); 10319 } 10320 10321 /** 10322 * Just scans the package without any side effects. 10323 * <p>Not entirely true at the moment. There is still one side effect -- this 10324 * method potentially modifies a live {@link PackageSetting} object representing 10325 * the package being scanned. This will be resolved in the future. 10326 * 10327 * @param request Information about the package to be scanned 10328 * @param isUnderFactoryTest Whether or not the device is under factory test 10329 * @param currentTime The current time, in millis 10330 * @return The results of the scan 10331 */ 10332 @GuardedBy("mInstallLock") 10333 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10334 boolean isUnderFactoryTest, long currentTime) 10335 throws PackageManagerException { 10336 final PackageParser.Package pkg = request.pkg; 10337 PackageSetting pkgSetting = request.pkgSetting; 10338 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10339 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10340 final @ParseFlags int parseFlags = request.parseFlags; 10341 final @ScanFlags int scanFlags = request.scanFlags; 10342 final String realPkgName = request.realPkgName; 10343 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10344 final UserHandle user = request.user; 10345 final boolean isPlatformPackage = request.isPlatformPackage; 10346 10347 List<String> changedAbiCodePath = null; 10348 10349 if (DEBUG_PACKAGE_SCANNING) { 10350 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10351 Log.d(TAG, "Scanning package " + pkg.packageName); 10352 } 10353 10354 if (Build.IS_DEBUGGABLE && 10355 pkg.isPrivileged() && 10356 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10357 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10358 } 10359 10360 // Initialize package source and resource directories 10361 final File scanFile = new File(pkg.codePath); 10362 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10363 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10364 10365 // We keep references to the derived CPU Abis from settings in oder to reuse 10366 // them in the case where we're not upgrading or booting for the first time. 10367 String primaryCpuAbiFromSettings = null; 10368 String secondaryCpuAbiFromSettings = null; 10369 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10370 10371 if (!needToDeriveAbi) { 10372 if (pkgSetting != null) { 10373 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10374 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10375 } else { 10376 // Re-scanning a system package after uninstalling updates; need to derive ABI 10377 needToDeriveAbi = true; 10378 } 10379 } 10380 10381 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10382 PackageManagerService.reportSettingsProblem(Log.WARN, 10383 "Package " + pkg.packageName + " shared user changed from " 10384 + (pkgSetting.sharedUser != null 10385 ? pkgSetting.sharedUser.name : "<nothing>") 10386 + " to " 10387 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10388 + "; replacing with new"); 10389 pkgSetting = null; 10390 } 10391 10392 String[] usesStaticLibraries = null; 10393 if (pkg.usesStaticLibraries != null) { 10394 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10395 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10396 } 10397 final boolean createNewPackage = (pkgSetting == null); 10398 if (createNewPackage) { 10399 final String parentPackageName = (pkg.parentPackage != null) 10400 ? pkg.parentPackage.packageName : null; 10401 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10402 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10403 // REMOVE SharedUserSetting from method; update in a separate call 10404 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10405 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10406 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10407 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10408 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10409 user, true /*allowInstall*/, instantApp, virtualPreload, 10410 parentPackageName, pkg.getChildPackageNames(), 10411 UserManagerService.getInstance(), usesStaticLibraries, 10412 pkg.usesStaticLibrariesVersions); 10413 } else { 10414 // REMOVE SharedUserSetting from method; update in a separate call. 10415 // 10416 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10417 // secondaryCpuAbi are not known at this point so we always update them 10418 // to null here, only to reset them at a later point. 10419 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10420 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10421 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10422 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10423 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10424 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10425 } 10426 if (createNewPackage && originalPkgSetting != null) { 10427 // This is the initial transition from the original package, so, 10428 // fix up the new package's name now. We must do this after looking 10429 // up the package under its new name, so getPackageLP takes care of 10430 // fiddling things correctly. 10431 pkg.setPackageName(originalPkgSetting.name); 10432 10433 // File a report about this. 10434 String msg = "New package " + pkgSetting.realName 10435 + " renamed to replace old package " + pkgSetting.name; 10436 reportSettingsProblem(Log.WARN, msg); 10437 } 10438 10439 if (disabledPkgSetting != null) { 10440 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10441 } 10442 10443 SELinuxMMAC.assignSeInfoValue(pkg); 10444 10445 pkg.mExtras = pkgSetting; 10446 pkg.applicationInfo.processName = fixProcessName( 10447 pkg.applicationInfo.packageName, 10448 pkg.applicationInfo.processName); 10449 10450 if (!isPlatformPackage) { 10451 // Get all of our default paths setup 10452 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10453 } 10454 10455 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10456 10457 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10458 if (needToDeriveAbi) { 10459 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10460 final boolean extractNativeLibs = !pkg.isLibrary(); 10461 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10462 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10463 10464 // Some system apps still use directory structure for native libraries 10465 // in which case we might end up not detecting abi solely based on apk 10466 // structure. Try to detect abi based on directory structure. 10467 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10468 pkg.applicationInfo.primaryCpuAbi == null) { 10469 setBundledAppAbisAndRoots(pkg, pkgSetting); 10470 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10471 } 10472 } else { 10473 // This is not a first boot or an upgrade, don't bother deriving the 10474 // ABI during the scan. Instead, trust the value that was stored in the 10475 // package setting. 10476 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10477 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10478 10479 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10480 10481 if (DEBUG_ABI_SELECTION) { 10482 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10483 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10484 pkg.applicationInfo.secondaryCpuAbi); 10485 } 10486 } 10487 } else { 10488 if ((scanFlags & SCAN_MOVE) != 0) { 10489 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10490 // but we already have this packages package info in the PackageSetting. We just 10491 // use that and derive the native library path based on the new codepath. 10492 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10493 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10494 } 10495 10496 // Set native library paths again. For moves, the path will be updated based on the 10497 // ABIs we've determined above. For non-moves, the path will be updated based on the 10498 // ABIs we determined during compilation, but the path will depend on the final 10499 // package path (after the rename away from the stage path). 10500 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10501 } 10502 10503 // This is a special case for the "system" package, where the ABI is 10504 // dictated by the zygote configuration (and init.rc). We should keep track 10505 // of this ABI so that we can deal with "normal" applications that run under 10506 // the same UID correctly. 10507 if (isPlatformPackage) { 10508 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10509 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10510 } 10511 10512 // If there's a mismatch between the abi-override in the package setting 10513 // and the abiOverride specified for the install. Warn about this because we 10514 // would've already compiled the app without taking the package setting into 10515 // account. 10516 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10517 if (cpuAbiOverride == null && pkg.packageName != null) { 10518 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10519 " for package " + pkg.packageName); 10520 } 10521 } 10522 10523 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10524 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10525 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10526 10527 // Copy the derived override back to the parsed package, so that we can 10528 // update the package settings accordingly. 10529 pkg.cpuAbiOverride = cpuAbiOverride; 10530 10531 if (DEBUG_ABI_SELECTION) { 10532 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10533 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10534 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10535 } 10536 10537 // Push the derived path down into PackageSettings so we know what to 10538 // clean up at uninstall time. 10539 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10540 10541 if (DEBUG_ABI_SELECTION) { 10542 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10543 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10544 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10545 } 10546 10547 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10548 // We don't do this here during boot because we can do it all 10549 // at once after scanning all existing packages. 10550 // 10551 // We also do this *before* we perform dexopt on this package, so that 10552 // we can avoid redundant dexopts, and also to make sure we've got the 10553 // code and package path correct. 10554 changedAbiCodePath = 10555 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10556 } 10557 10558 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10559 android.Manifest.permission.FACTORY_TEST)) { 10560 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10561 } 10562 10563 if (isSystemApp(pkg)) { 10564 pkgSetting.isOrphaned = true; 10565 } 10566 10567 // Take care of first install / last update times. 10568 final long scanFileTime = getLastModifiedTime(pkg); 10569 if (currentTime != 0) { 10570 if (pkgSetting.firstInstallTime == 0) { 10571 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10572 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10573 pkgSetting.lastUpdateTime = currentTime; 10574 } 10575 } else if (pkgSetting.firstInstallTime == 0) { 10576 // We need *something*. Take time time stamp of the file. 10577 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10578 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10579 if (scanFileTime != pkgSetting.timeStamp) { 10580 // A package on the system image has changed; consider this 10581 // to be an update. 10582 pkgSetting.lastUpdateTime = scanFileTime; 10583 } 10584 } 10585 pkgSetting.setTimeStamp(scanFileTime); 10586 10587 pkgSetting.pkg = pkg; 10588 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10589 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10590 pkgSetting.versionCode = pkg.getLongVersionCode(); 10591 } 10592 // Update volume if needed 10593 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10594 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10595 Slog.i(PackageManagerService.TAG, 10596 "Update" + (pkgSetting.isSystem() ? " system" : "") 10597 + " package " + pkg.packageName 10598 + " volume from " + pkgSetting.volumeUuid 10599 + " to " + volumeUuid); 10600 pkgSetting.volumeUuid = volumeUuid; 10601 } 10602 10603 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10604 } 10605 10606 /** 10607 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10608 */ 10609 private static boolean apkHasCode(String fileName) { 10610 StrictJarFile jarFile = null; 10611 try { 10612 jarFile = new StrictJarFile(fileName, 10613 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10614 return jarFile.findEntry("classes.dex") != null; 10615 } catch (IOException ignore) { 10616 } finally { 10617 try { 10618 if (jarFile != null) { 10619 jarFile.close(); 10620 } 10621 } catch (IOException ignore) {} 10622 } 10623 return false; 10624 } 10625 10626 /** 10627 * Enforces code policy for the package. This ensures that if an APK has 10628 * declared hasCode="true" in its manifest that the APK actually contains 10629 * code. 10630 * 10631 * @throws PackageManagerException If bytecode could not be found when it should exist 10632 */ 10633 private static void assertCodePolicy(PackageParser.Package pkg) 10634 throws PackageManagerException { 10635 final boolean shouldHaveCode = 10636 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10637 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10638 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10639 "Package " + pkg.baseCodePath + " code is missing"); 10640 } 10641 10642 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10643 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10644 final boolean splitShouldHaveCode = 10645 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10646 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10647 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10648 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10649 } 10650 } 10651 } 10652 } 10653 10654 /** 10655 * Applies policy to the parsed package based upon the given policy flags. 10656 * Ensures the package is in a good state. 10657 * <p> 10658 * Implementation detail: This method must NOT have any side effect. It would 10659 * ideally be static, but, it requires locks to read system state. 10660 */ 10661 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10662 final @ScanFlags int scanFlags) { 10663 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10664 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10665 if (pkg.applicationInfo.isDirectBootAware()) { 10666 // we're direct boot aware; set for all components 10667 for (PackageParser.Service s : pkg.services) { 10668 s.info.encryptionAware = s.info.directBootAware = true; 10669 } 10670 for (PackageParser.Provider p : pkg.providers) { 10671 p.info.encryptionAware = p.info.directBootAware = true; 10672 } 10673 for (PackageParser.Activity a : pkg.activities) { 10674 a.info.encryptionAware = a.info.directBootAware = true; 10675 } 10676 for (PackageParser.Activity r : pkg.receivers) { 10677 r.info.encryptionAware = r.info.directBootAware = true; 10678 } 10679 } 10680 if (compressedFileExists(pkg.codePath)) { 10681 pkg.isStub = true; 10682 } 10683 } else { 10684 // non system apps can't be flagged as core 10685 pkg.coreApp = false; 10686 // clear flags not applicable to regular apps 10687 pkg.applicationInfo.flags &= 10688 ~ApplicationInfo.FLAG_PERSISTENT; 10689 pkg.applicationInfo.privateFlags &= 10690 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10691 pkg.applicationInfo.privateFlags &= 10692 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10693 // clear protected broadcasts 10694 pkg.protectedBroadcasts = null; 10695 // cap permission priorities 10696 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10697 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10698 pkg.permissionGroups.get(i).info.priority = 0; 10699 } 10700 } 10701 } 10702 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10703 // ignore export request for single user receivers 10704 if (pkg.receivers != null) { 10705 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10706 final PackageParser.Activity receiver = pkg.receivers.get(i); 10707 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10708 receiver.info.exported = false; 10709 } 10710 } 10711 } 10712 // ignore export request for single user services 10713 if (pkg.services != null) { 10714 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10715 final PackageParser.Service service = pkg.services.get(i); 10716 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10717 service.info.exported = false; 10718 } 10719 } 10720 } 10721 // ignore export request for single user providers 10722 if (pkg.providers != null) { 10723 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10724 final PackageParser.Provider provider = pkg.providers.get(i); 10725 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10726 provider.info.exported = false; 10727 } 10728 } 10729 } 10730 } 10731 10732 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10733 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10734 } 10735 10736 if ((scanFlags & SCAN_AS_OEM) != 0) { 10737 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10738 } 10739 10740 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10741 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10742 } 10743 10744 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10745 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10746 } 10747 10748 if (!isSystemApp(pkg)) { 10749 // Only system apps can use these features. 10750 pkg.mOriginalPackages = null; 10751 pkg.mRealPackage = null; 10752 pkg.mAdoptPermissions = null; 10753 } 10754 } 10755 10756 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10757 throws PackageManagerException { 10758 if (object == null) { 10759 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10760 } 10761 return object; 10762 } 10763 10764 /** 10765 * Asserts the parsed package is valid according to the given policy. If the 10766 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10767 * <p> 10768 * Implementation detail: This method must NOT have any side effects. It would 10769 * ideally be static, but, it requires locks to read system state. 10770 * 10771 * @throws PackageManagerException If the package fails any of the validation checks 10772 */ 10773 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10774 final @ScanFlags int scanFlags) 10775 throws PackageManagerException { 10776 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10777 assertCodePolicy(pkg); 10778 } 10779 10780 if (pkg.applicationInfo.getCodePath() == null || 10781 pkg.applicationInfo.getResourcePath() == null) { 10782 // Bail out. The resource and code paths haven't been set. 10783 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10784 "Code and resource paths haven't been set correctly"); 10785 } 10786 10787 // Make sure we're not adding any bogus keyset info 10788 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10789 ksms.assertScannedPackageValid(pkg); 10790 10791 synchronized (mPackages) { 10792 // The special "android" package can only be defined once 10793 if (pkg.packageName.equals("android")) { 10794 if (mAndroidApplication != null) { 10795 Slog.w(TAG, "*************************************************"); 10796 Slog.w(TAG, "Core android package being redefined. Skipping."); 10797 Slog.w(TAG, " codePath=" + pkg.codePath); 10798 Slog.w(TAG, "*************************************************"); 10799 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10800 "Core android package being redefined. Skipping."); 10801 } 10802 } 10803 10804 // A package name must be unique; don't allow duplicates 10805 if (mPackages.containsKey(pkg.packageName)) { 10806 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10807 "Application package " + pkg.packageName 10808 + " already installed. Skipping duplicate."); 10809 } 10810 10811 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10812 // Static libs have a synthetic package name containing the version 10813 // but we still want the base name to be unique. 10814 if (mPackages.containsKey(pkg.manifestPackageName)) { 10815 throw new PackageManagerException( 10816 "Duplicate static shared lib provider package"); 10817 } 10818 10819 // Static shared libraries should have at least O target SDK 10820 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10821 throw new PackageManagerException( 10822 "Packages declaring static-shared libs must target O SDK or higher"); 10823 } 10824 10825 // Package declaring static a shared lib cannot be instant apps 10826 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10827 throw new PackageManagerException( 10828 "Packages declaring static-shared libs cannot be instant apps"); 10829 } 10830 10831 // Package declaring static a shared lib cannot be renamed since the package 10832 // name is synthetic and apps can't code around package manager internals. 10833 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10834 throw new PackageManagerException( 10835 "Packages declaring static-shared libs cannot be renamed"); 10836 } 10837 10838 // Package declaring static a shared lib cannot declare child packages 10839 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10840 throw new PackageManagerException( 10841 "Packages declaring static-shared libs cannot have child packages"); 10842 } 10843 10844 // Package declaring static a shared lib cannot declare dynamic libs 10845 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10846 throw new PackageManagerException( 10847 "Packages declaring static-shared libs cannot declare dynamic libs"); 10848 } 10849 10850 // Package declaring static a shared lib cannot declare shared users 10851 if (pkg.mSharedUserId != null) { 10852 throw new PackageManagerException( 10853 "Packages declaring static-shared libs cannot declare shared users"); 10854 } 10855 10856 // Static shared libs cannot declare activities 10857 if (!pkg.activities.isEmpty()) { 10858 throw new PackageManagerException( 10859 "Static shared libs cannot declare activities"); 10860 } 10861 10862 // Static shared libs cannot declare services 10863 if (!pkg.services.isEmpty()) { 10864 throw new PackageManagerException( 10865 "Static shared libs cannot declare services"); 10866 } 10867 10868 // Static shared libs cannot declare providers 10869 if (!pkg.providers.isEmpty()) { 10870 throw new PackageManagerException( 10871 "Static shared libs cannot declare content providers"); 10872 } 10873 10874 // Static shared libs cannot declare receivers 10875 if (!pkg.receivers.isEmpty()) { 10876 throw new PackageManagerException( 10877 "Static shared libs cannot declare broadcast receivers"); 10878 } 10879 10880 // Static shared libs cannot declare permission groups 10881 if (!pkg.permissionGroups.isEmpty()) { 10882 throw new PackageManagerException( 10883 "Static shared libs cannot declare permission groups"); 10884 } 10885 10886 // Static shared libs cannot declare permissions 10887 if (!pkg.permissions.isEmpty()) { 10888 throw new PackageManagerException( 10889 "Static shared libs cannot declare permissions"); 10890 } 10891 10892 // Static shared libs cannot declare protected broadcasts 10893 if (pkg.protectedBroadcasts != null) { 10894 throw new PackageManagerException( 10895 "Static shared libs cannot declare protected broadcasts"); 10896 } 10897 10898 // Static shared libs cannot be overlay targets 10899 if (pkg.mOverlayTarget != null) { 10900 throw new PackageManagerException( 10901 "Static shared libs cannot be overlay targets"); 10902 } 10903 10904 // The version codes must be ordered as lib versions 10905 long minVersionCode = Long.MIN_VALUE; 10906 long maxVersionCode = Long.MAX_VALUE; 10907 10908 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10909 pkg.staticSharedLibName); 10910 if (versionedLib != null) { 10911 final int versionCount = versionedLib.size(); 10912 for (int i = 0; i < versionCount; i++) { 10913 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10914 final long libVersionCode = libInfo.getDeclaringPackage() 10915 .getLongVersionCode(); 10916 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10917 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10918 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10919 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10920 } else { 10921 minVersionCode = maxVersionCode = libVersionCode; 10922 break; 10923 } 10924 } 10925 } 10926 if (pkg.getLongVersionCode() < minVersionCode 10927 || pkg.getLongVersionCode() > maxVersionCode) { 10928 throw new PackageManagerException("Static shared" 10929 + " lib version codes must be ordered as lib versions"); 10930 } 10931 } 10932 10933 // Only privileged apps and updated privileged apps can add child packages. 10934 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10935 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10936 throw new PackageManagerException("Only privileged apps can add child " 10937 + "packages. Ignoring package " + pkg.packageName); 10938 } 10939 final int childCount = pkg.childPackages.size(); 10940 for (int i = 0; i < childCount; i++) { 10941 PackageParser.Package childPkg = pkg.childPackages.get(i); 10942 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10943 childPkg.packageName)) { 10944 throw new PackageManagerException("Can't override child of " 10945 + "another disabled app. Ignoring package " + pkg.packageName); 10946 } 10947 } 10948 } 10949 10950 // If we're only installing presumed-existing packages, require that the 10951 // scanned APK is both already known and at the path previously established 10952 // for it. Previously unknown packages we pick up normally, but if we have an 10953 // a priori expectation about this package's install presence, enforce it. 10954 // With a singular exception for new system packages. When an OTA contains 10955 // a new system package, we allow the codepath to change from a system location 10956 // to the user-installed location. If we don't allow this change, any newer, 10957 // user-installed version of the application will be ignored. 10958 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10959 if (mExpectingBetter.containsKey(pkg.packageName)) { 10960 logCriticalInfo(Log.WARN, 10961 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10962 } else { 10963 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10964 if (known != null) { 10965 if (DEBUG_PACKAGE_SCANNING) { 10966 Log.d(TAG, "Examining " + pkg.codePath 10967 + " and requiring known paths " + known.codePathString 10968 + " & " + known.resourcePathString); 10969 } 10970 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10971 || !pkg.applicationInfo.getResourcePath().equals( 10972 known.resourcePathString)) { 10973 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10974 "Application package " + pkg.packageName 10975 + " found at " + pkg.applicationInfo.getCodePath() 10976 + " but expected at " + known.codePathString 10977 + "; ignoring."); 10978 } 10979 } else { 10980 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10981 "Application package " + pkg.packageName 10982 + " not found; ignoring."); 10983 } 10984 } 10985 } 10986 10987 // Verify that this new package doesn't have any content providers 10988 // that conflict with existing packages. Only do this if the 10989 // package isn't already installed, since we don't want to break 10990 // things that are installed. 10991 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10992 final int N = pkg.providers.size(); 10993 int i; 10994 for (i=0; i<N; i++) { 10995 PackageParser.Provider p = pkg.providers.get(i); 10996 if (p.info.authority != null) { 10997 String names[] = p.info.authority.split(";"); 10998 for (int j = 0; j < names.length; j++) { 10999 if (mProvidersByAuthority.containsKey(names[j])) { 11000 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11001 final String otherPackageName = 11002 ((other != null && other.getComponentName() != null) ? 11003 other.getComponentName().getPackageName() : "?"); 11004 throw new PackageManagerException( 11005 INSTALL_FAILED_CONFLICTING_PROVIDER, 11006 "Can't install because provider name " + names[j] 11007 + " (in package " + pkg.applicationInfo.packageName 11008 + ") is already used by " + otherPackageName); 11009 } 11010 } 11011 } 11012 } 11013 } 11014 11015 // Verify that packages sharing a user with a privileged app are marked as privileged. 11016 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11017 SharedUserSetting sharedUserSetting = null; 11018 try { 11019 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11020 } catch (PackageManagerException ignore) {} 11021 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11022 // Exempt SharedUsers signed with the platform key. 11023 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11024 if ((platformPkgSetting.signatures.mSigningDetails 11025 != PackageParser.SigningDetails.UNKNOWN) 11026 && (compareSignatures( 11027 platformPkgSetting.signatures.mSigningDetails.signatures, 11028 pkg.mSigningDetails.signatures) 11029 != PackageManager.SIGNATURE_MATCH)) { 11030 throw new PackageManagerException("Apps that share a user with a " + 11031 "privileged app must themselves be marked as privileged. " + 11032 pkg.packageName + " shares privileged user " + 11033 pkg.mSharedUserId + "."); 11034 } 11035 } 11036 } 11037 11038 // Apply policies specific for runtime resource overlays (RROs). 11039 if (pkg.mOverlayTarget != null) { 11040 // System overlays have some restrictions on their use of the 'static' state. 11041 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11042 // We are scanning a system overlay. This can be the first scan of the 11043 // system/vendor/oem partition, or an update to the system overlay. 11044 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11045 // This must be an update to a system overlay. 11046 final PackageSetting previousPkg = assertNotNull( 11047 mSettings.getPackageLPr(pkg.packageName), 11048 "previous package state not present"); 11049 11050 // Static overlays cannot be updated. 11051 if (previousPkg.pkg.mOverlayIsStatic) { 11052 throw new PackageManagerException("Overlay " + pkg.packageName + 11053 " is static and cannot be upgraded."); 11054 // Non-static overlays cannot be converted to static overlays. 11055 } else if (pkg.mOverlayIsStatic) { 11056 throw new PackageManagerException("Overlay " + pkg.packageName + 11057 " cannot be upgraded into a static overlay."); 11058 } 11059 } 11060 } else { 11061 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11062 if (pkg.mOverlayIsStatic) { 11063 throw new PackageManagerException("Overlay " + pkg.packageName + 11064 " is static but not pre-installed."); 11065 } 11066 11067 // The only case where we allow installation of a non-system overlay is when 11068 // its signature is signed with the platform certificate. 11069 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11070 if ((platformPkgSetting.signatures.mSigningDetails 11071 != PackageParser.SigningDetails.UNKNOWN) 11072 && (compareSignatures( 11073 platformPkgSetting.signatures.mSigningDetails.signatures, 11074 pkg.mSigningDetails.signatures) 11075 != PackageManager.SIGNATURE_MATCH)) { 11076 throw new PackageManagerException("Overlay " + pkg.packageName + 11077 " must be signed with the platform certificate."); 11078 } 11079 } 11080 } 11081 } 11082 } 11083 11084 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11085 int type, String declaringPackageName, long declaringVersionCode) { 11086 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11087 if (versionedLib == null) { 11088 versionedLib = new LongSparseArray<>(); 11089 mSharedLibraries.put(name, versionedLib); 11090 if (type == SharedLibraryInfo.TYPE_STATIC) { 11091 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11092 } 11093 } else if (versionedLib.indexOfKey(version) >= 0) { 11094 return false; 11095 } 11096 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11097 version, type, declaringPackageName, declaringVersionCode); 11098 versionedLib.put(version, libEntry); 11099 return true; 11100 } 11101 11102 private boolean removeSharedLibraryLPw(String name, long version) { 11103 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11104 if (versionedLib == null) { 11105 return false; 11106 } 11107 final int libIdx = versionedLib.indexOfKey(version); 11108 if (libIdx < 0) { 11109 return false; 11110 } 11111 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11112 versionedLib.remove(version); 11113 if (versionedLib.size() <= 0) { 11114 mSharedLibraries.remove(name); 11115 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11116 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11117 .getPackageName()); 11118 } 11119 } 11120 return true; 11121 } 11122 11123 /** 11124 * Adds a scanned package to the system. When this method is finished, the package will 11125 * be available for query, resolution, etc... 11126 */ 11127 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11128 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11129 final String pkgName = pkg.packageName; 11130 if (mCustomResolverComponentName != null && 11131 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11132 setUpCustomResolverActivity(pkg); 11133 } 11134 11135 if (pkg.packageName.equals("android")) { 11136 synchronized (mPackages) { 11137 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11138 // Set up information for our fall-back user intent resolution activity. 11139 mPlatformPackage = pkg; 11140 pkg.mVersionCode = mSdkVersion; 11141 pkg.mVersionCodeMajor = 0; 11142 mAndroidApplication = pkg.applicationInfo; 11143 if (!mResolverReplaced) { 11144 mResolveActivity.applicationInfo = mAndroidApplication; 11145 mResolveActivity.name = ResolverActivity.class.getName(); 11146 mResolveActivity.packageName = mAndroidApplication.packageName; 11147 mResolveActivity.processName = "system:ui"; 11148 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11149 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11150 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11151 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11152 mResolveActivity.exported = true; 11153 mResolveActivity.enabled = true; 11154 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11155 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11156 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11157 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11158 | ActivityInfo.CONFIG_ORIENTATION 11159 | ActivityInfo.CONFIG_KEYBOARD 11160 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11161 mResolveInfo.activityInfo = mResolveActivity; 11162 mResolveInfo.priority = 0; 11163 mResolveInfo.preferredOrder = 0; 11164 mResolveInfo.match = 0; 11165 mResolveComponentName = new ComponentName( 11166 mAndroidApplication.packageName, mResolveActivity.name); 11167 } 11168 } 11169 } 11170 } 11171 11172 ArrayList<PackageParser.Package> clientLibPkgs = null; 11173 // writer 11174 synchronized (mPackages) { 11175 boolean hasStaticSharedLibs = false; 11176 11177 // Any app can add new static shared libraries 11178 if (pkg.staticSharedLibName != null) { 11179 // Static shared libs don't allow renaming as they have synthetic package 11180 // names to allow install of multiple versions, so use name from manifest. 11181 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11182 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11183 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11184 hasStaticSharedLibs = true; 11185 } else { 11186 Slog.w(TAG, "Package " + pkg.packageName + " library " 11187 + pkg.staticSharedLibName + " already exists; skipping"); 11188 } 11189 // Static shared libs cannot be updated once installed since they 11190 // use synthetic package name which includes the version code, so 11191 // not need to update other packages's shared lib dependencies. 11192 } 11193 11194 if (!hasStaticSharedLibs 11195 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11196 // Only system apps can add new dynamic shared libraries. 11197 if (pkg.libraryNames != null) { 11198 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11199 String name = pkg.libraryNames.get(i); 11200 boolean allowed = false; 11201 if (pkg.isUpdatedSystemApp()) { 11202 // New library entries can only be added through the 11203 // system image. This is important to get rid of a lot 11204 // of nasty edge cases: for example if we allowed a non- 11205 // system update of the app to add a library, then uninstalling 11206 // the update would make the library go away, and assumptions 11207 // we made such as through app install filtering would now 11208 // have allowed apps on the device which aren't compatible 11209 // with it. Better to just have the restriction here, be 11210 // conservative, and create many fewer cases that can negatively 11211 // impact the user experience. 11212 final PackageSetting sysPs = mSettings 11213 .getDisabledSystemPkgLPr(pkg.packageName); 11214 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11215 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11216 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11217 allowed = true; 11218 break; 11219 } 11220 } 11221 } 11222 } else { 11223 allowed = true; 11224 } 11225 if (allowed) { 11226 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11227 SharedLibraryInfo.VERSION_UNDEFINED, 11228 SharedLibraryInfo.TYPE_DYNAMIC, 11229 pkg.packageName, pkg.getLongVersionCode())) { 11230 Slog.w(TAG, "Package " + pkg.packageName + " library " 11231 + name + " already exists; skipping"); 11232 } 11233 } else { 11234 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11235 + name + " that is not declared on system image; skipping"); 11236 } 11237 } 11238 11239 if ((scanFlags & SCAN_BOOTING) == 0) { 11240 // If we are not booting, we need to update any applications 11241 // that are clients of our shared library. If we are booting, 11242 // this will all be done once the scan is complete. 11243 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11244 } 11245 } 11246 } 11247 } 11248 11249 if ((scanFlags & SCAN_BOOTING) != 0) { 11250 // No apps can run during boot scan, so they don't need to be frozen 11251 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11252 // Caller asked to not kill app, so it's probably not frozen 11253 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11254 // Caller asked us to ignore frozen check for some reason; they 11255 // probably didn't know the package name 11256 } else { 11257 // We're doing major surgery on this package, so it better be frozen 11258 // right now to keep it from launching 11259 checkPackageFrozen(pkgName); 11260 } 11261 11262 // Also need to kill any apps that are dependent on the library. 11263 if (clientLibPkgs != null) { 11264 for (int i=0; i<clientLibPkgs.size(); i++) { 11265 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11266 killApplication(clientPkg.applicationInfo.packageName, 11267 clientPkg.applicationInfo.uid, "update lib"); 11268 } 11269 } 11270 11271 // writer 11272 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11273 11274 synchronized (mPackages) { 11275 // We don't expect installation to fail beyond this point 11276 11277 // Add the new setting to mSettings 11278 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11279 // Add the new setting to mPackages 11280 mPackages.put(pkg.applicationInfo.packageName, pkg); 11281 // Make sure we don't accidentally delete its data. 11282 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11283 while (iter.hasNext()) { 11284 PackageCleanItem item = iter.next(); 11285 if (pkgName.equals(item.packageName)) { 11286 iter.remove(); 11287 } 11288 } 11289 11290 // Add the package's KeySets to the global KeySetManagerService 11291 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11292 ksms.addScannedPackageLPw(pkg); 11293 11294 int N = pkg.providers.size(); 11295 StringBuilder r = null; 11296 int i; 11297 for (i=0; i<N; i++) { 11298 PackageParser.Provider p = pkg.providers.get(i); 11299 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11300 p.info.processName); 11301 mProviders.addProvider(p); 11302 p.syncable = p.info.isSyncable; 11303 if (p.info.authority != null) { 11304 String names[] = p.info.authority.split(";"); 11305 p.info.authority = null; 11306 for (int j = 0; j < names.length; j++) { 11307 if (j == 1 && p.syncable) { 11308 // We only want the first authority for a provider to possibly be 11309 // syncable, so if we already added this provider using a different 11310 // authority clear the syncable flag. We copy the provider before 11311 // changing it because the mProviders object contains a reference 11312 // to a provider that we don't want to change. 11313 // Only do this for the second authority since the resulting provider 11314 // object can be the same for all future authorities for this provider. 11315 p = new PackageParser.Provider(p); 11316 p.syncable = false; 11317 } 11318 if (!mProvidersByAuthority.containsKey(names[j])) { 11319 mProvidersByAuthority.put(names[j], p); 11320 if (p.info.authority == null) { 11321 p.info.authority = names[j]; 11322 } else { 11323 p.info.authority = p.info.authority + ";" + names[j]; 11324 } 11325 if (DEBUG_PACKAGE_SCANNING) { 11326 if (chatty) 11327 Log.d(TAG, "Registered content provider: " + names[j] 11328 + ", className = " + p.info.name + ", isSyncable = " 11329 + p.info.isSyncable); 11330 } 11331 } else { 11332 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11333 Slog.w(TAG, "Skipping provider name " + names[j] + 11334 " (in package " + pkg.applicationInfo.packageName + 11335 "): name already used by " 11336 + ((other != null && other.getComponentName() != null) 11337 ? other.getComponentName().getPackageName() : "?")); 11338 } 11339 } 11340 } 11341 if (chatty) { 11342 if (r == null) { 11343 r = new StringBuilder(256); 11344 } else { 11345 r.append(' '); 11346 } 11347 r.append(p.info.name); 11348 } 11349 } 11350 if (r != null) { 11351 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11352 } 11353 11354 N = pkg.services.size(); 11355 r = null; 11356 for (i=0; i<N; i++) { 11357 PackageParser.Service s = pkg.services.get(i); 11358 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11359 s.info.processName); 11360 mServices.addService(s); 11361 if (chatty) { 11362 if (r == null) { 11363 r = new StringBuilder(256); 11364 } else { 11365 r.append(' '); 11366 } 11367 r.append(s.info.name); 11368 } 11369 } 11370 if (r != null) { 11371 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11372 } 11373 11374 N = pkg.receivers.size(); 11375 r = null; 11376 for (i=0; i<N; i++) { 11377 PackageParser.Activity a = pkg.receivers.get(i); 11378 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11379 a.info.processName); 11380 mReceivers.addActivity(a, "receiver"); 11381 if (chatty) { 11382 if (r == null) { 11383 r = new StringBuilder(256); 11384 } else { 11385 r.append(' '); 11386 } 11387 r.append(a.info.name); 11388 } 11389 } 11390 if (r != null) { 11391 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11392 } 11393 11394 N = pkg.activities.size(); 11395 r = null; 11396 for (i=0; i<N; i++) { 11397 PackageParser.Activity a = pkg.activities.get(i); 11398 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11399 a.info.processName); 11400 mActivities.addActivity(a, "activity"); 11401 if (chatty) { 11402 if (r == null) { 11403 r = new StringBuilder(256); 11404 } else { 11405 r.append(' '); 11406 } 11407 r.append(a.info.name); 11408 } 11409 } 11410 if (r != null) { 11411 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11412 } 11413 11414 // Don't allow ephemeral applications to define new permissions groups. 11415 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11416 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11417 + " ignored: instant apps cannot define new permission groups."); 11418 } else { 11419 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11420 } 11421 11422 // Don't allow ephemeral applications to define new permissions. 11423 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11424 Slog.w(TAG, "Permissions from package " + pkg.packageName 11425 + " ignored: instant apps cannot define new permissions."); 11426 } else { 11427 mPermissionManager.addAllPermissions(pkg, chatty); 11428 } 11429 11430 N = pkg.instrumentation.size(); 11431 r = null; 11432 for (i=0; i<N; i++) { 11433 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11434 a.info.packageName = pkg.applicationInfo.packageName; 11435 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11436 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11437 a.info.splitNames = pkg.splitNames; 11438 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11439 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11440 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11441 a.info.dataDir = pkg.applicationInfo.dataDir; 11442 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11443 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11444 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11445 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11446 mInstrumentation.put(a.getComponentName(), a); 11447 if (chatty) { 11448 if (r == null) { 11449 r = new StringBuilder(256); 11450 } else { 11451 r.append(' '); 11452 } 11453 r.append(a.info.name); 11454 } 11455 } 11456 if (r != null) { 11457 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11458 } 11459 11460 if (pkg.protectedBroadcasts != null) { 11461 N = pkg.protectedBroadcasts.size(); 11462 synchronized (mProtectedBroadcasts) { 11463 for (i = 0; i < N; i++) { 11464 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11465 } 11466 } 11467 } 11468 } 11469 11470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11471 } 11472 11473 /** 11474 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11475 * is derived purely on the basis of the contents of {@code scanFile} and 11476 * {@code cpuAbiOverride}. 11477 * 11478 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11479 */ 11480 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11481 boolean extractLibs) 11482 throws PackageManagerException { 11483 // Give ourselves some initial paths; we'll come back for another 11484 // pass once we've determined ABI below. 11485 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11486 11487 // We would never need to extract libs for forward-locked and external packages, 11488 // since the container service will do it for us. We shouldn't attempt to 11489 // extract libs from system app when it was not updated. 11490 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11491 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11492 extractLibs = false; 11493 } 11494 11495 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11496 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11497 11498 NativeLibraryHelper.Handle handle = null; 11499 try { 11500 handle = NativeLibraryHelper.Handle.create(pkg); 11501 // TODO(multiArch): This can be null for apps that didn't go through the 11502 // usual installation process. We can calculate it again, like we 11503 // do during install time. 11504 // 11505 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11506 // unnecessary. 11507 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11508 11509 // Null out the abis so that they can be recalculated. 11510 pkg.applicationInfo.primaryCpuAbi = null; 11511 pkg.applicationInfo.secondaryCpuAbi = null; 11512 if (isMultiArch(pkg.applicationInfo)) { 11513 // Warn if we've set an abiOverride for multi-lib packages.. 11514 // By definition, we need to copy both 32 and 64 bit libraries for 11515 // such packages. 11516 if (pkg.cpuAbiOverride != null 11517 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11518 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11519 } 11520 11521 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11522 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11523 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11524 if (extractLibs) { 11525 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11526 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11527 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11528 useIsaSpecificSubdirs); 11529 } else { 11530 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11531 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11532 } 11533 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11534 } 11535 11536 // Shared library native code should be in the APK zip aligned 11537 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11538 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11539 "Shared library native lib extraction not supported"); 11540 } 11541 11542 maybeThrowExceptionForMultiArchCopy( 11543 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11544 11545 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11546 if (extractLibs) { 11547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11548 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11549 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11550 useIsaSpecificSubdirs); 11551 } else { 11552 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11553 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11554 } 11555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11556 } 11557 11558 maybeThrowExceptionForMultiArchCopy( 11559 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11560 11561 if (abi64 >= 0) { 11562 // Shared library native libs should be in the APK zip aligned 11563 if (extractLibs && pkg.isLibrary()) { 11564 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11565 "Shared library native lib extraction not supported"); 11566 } 11567 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11568 } 11569 11570 if (abi32 >= 0) { 11571 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11572 if (abi64 >= 0) { 11573 if (pkg.use32bitAbi) { 11574 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11575 pkg.applicationInfo.primaryCpuAbi = abi; 11576 } else { 11577 pkg.applicationInfo.secondaryCpuAbi = abi; 11578 } 11579 } else { 11580 pkg.applicationInfo.primaryCpuAbi = abi; 11581 } 11582 } 11583 } else { 11584 String[] abiList = (cpuAbiOverride != null) ? 11585 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11586 11587 // Enable gross and lame hacks for apps that are built with old 11588 // SDK tools. We must scan their APKs for renderscript bitcode and 11589 // not launch them if it's present. Don't bother checking on devices 11590 // that don't have 64 bit support. 11591 boolean needsRenderScriptOverride = false; 11592 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11593 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11594 abiList = Build.SUPPORTED_32_BIT_ABIS; 11595 needsRenderScriptOverride = true; 11596 } 11597 11598 final int copyRet; 11599 if (extractLibs) { 11600 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11601 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11602 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11603 } else { 11604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11605 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11606 } 11607 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11608 11609 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11610 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11611 "Error unpackaging native libs for app, errorCode=" + copyRet); 11612 } 11613 11614 if (copyRet >= 0) { 11615 // Shared libraries that have native libs must be multi-architecture 11616 if (pkg.isLibrary()) { 11617 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11618 "Shared library with native libs must be multiarch"); 11619 } 11620 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11621 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11622 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11623 } else if (needsRenderScriptOverride) { 11624 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11625 } 11626 } 11627 } catch (IOException ioe) { 11628 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11629 } finally { 11630 IoUtils.closeQuietly(handle); 11631 } 11632 11633 // Now that we've calculated the ABIs and determined if it's an internal app, 11634 // we will go ahead and populate the nativeLibraryPath. 11635 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11636 } 11637 11638 /** 11639 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11640 * i.e, so that all packages can be run inside a single process if required. 11641 * 11642 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11643 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11644 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11645 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11646 * updating a package that belongs to a shared user. 11647 * 11648 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11649 * adds unnecessary complexity. 11650 */ 11651 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11652 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11653 List<String> changedAbiCodePath = null; 11654 String requiredInstructionSet = null; 11655 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11656 requiredInstructionSet = VMRuntime.getInstructionSet( 11657 scannedPackage.applicationInfo.primaryCpuAbi); 11658 } 11659 11660 PackageSetting requirer = null; 11661 for (PackageSetting ps : packagesForUser) { 11662 // If packagesForUser contains scannedPackage, we skip it. This will happen 11663 // when scannedPackage is an update of an existing package. Without this check, 11664 // we will never be able to change the ABI of any package belonging to a shared 11665 // user, even if it's compatible with other packages. 11666 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11667 if (ps.primaryCpuAbiString == null) { 11668 continue; 11669 } 11670 11671 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11672 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11673 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11674 // this but there's not much we can do. 11675 String errorMessage = "Instruction set mismatch, " 11676 + ((requirer == null) ? "[caller]" : requirer) 11677 + " requires " + requiredInstructionSet + " whereas " + ps 11678 + " requires " + instructionSet; 11679 Slog.w(TAG, errorMessage); 11680 } 11681 11682 if (requiredInstructionSet == null) { 11683 requiredInstructionSet = instructionSet; 11684 requirer = ps; 11685 } 11686 } 11687 } 11688 11689 if (requiredInstructionSet != null) { 11690 String adjustedAbi; 11691 if (requirer != null) { 11692 // requirer != null implies that either scannedPackage was null or that scannedPackage 11693 // did not require an ABI, in which case we have to adjust scannedPackage to match 11694 // the ABI of the set (which is the same as requirer's ABI) 11695 adjustedAbi = requirer.primaryCpuAbiString; 11696 if (scannedPackage != null) { 11697 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11698 } 11699 } else { 11700 // requirer == null implies that we're updating all ABIs in the set to 11701 // match scannedPackage. 11702 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11703 } 11704 11705 for (PackageSetting ps : packagesForUser) { 11706 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11707 if (ps.primaryCpuAbiString != null) { 11708 continue; 11709 } 11710 11711 ps.primaryCpuAbiString = adjustedAbi; 11712 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11713 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11714 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11715 if (DEBUG_ABI_SELECTION) { 11716 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11717 + " (requirer=" 11718 + (requirer != null ? requirer.pkg : "null") 11719 + ", scannedPackage=" 11720 + (scannedPackage != null ? scannedPackage : "null") 11721 + ")"); 11722 } 11723 if (changedAbiCodePath == null) { 11724 changedAbiCodePath = new ArrayList<>(); 11725 } 11726 changedAbiCodePath.add(ps.codePathString); 11727 } 11728 } 11729 } 11730 } 11731 return changedAbiCodePath; 11732 } 11733 11734 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11735 synchronized (mPackages) { 11736 mResolverReplaced = true; 11737 // Set up information for custom user intent resolution activity. 11738 mResolveActivity.applicationInfo = pkg.applicationInfo; 11739 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11740 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11741 mResolveActivity.processName = pkg.applicationInfo.packageName; 11742 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11743 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11744 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11745 mResolveActivity.theme = 0; 11746 mResolveActivity.exported = true; 11747 mResolveActivity.enabled = true; 11748 mResolveInfo.activityInfo = mResolveActivity; 11749 mResolveInfo.priority = 0; 11750 mResolveInfo.preferredOrder = 0; 11751 mResolveInfo.match = 0; 11752 mResolveComponentName = mCustomResolverComponentName; 11753 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11754 mResolveComponentName); 11755 } 11756 } 11757 11758 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11759 if (installerActivity == null) { 11760 if (DEBUG_EPHEMERAL) { 11761 Slog.d(TAG, "Clear ephemeral installer activity"); 11762 } 11763 mInstantAppInstallerActivity = null; 11764 return; 11765 } 11766 11767 if (DEBUG_EPHEMERAL) { 11768 Slog.d(TAG, "Set ephemeral installer activity: " 11769 + installerActivity.getComponentName()); 11770 } 11771 // Set up information for ephemeral installer activity 11772 mInstantAppInstallerActivity = installerActivity; 11773 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11774 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11775 mInstantAppInstallerActivity.exported = true; 11776 mInstantAppInstallerActivity.enabled = true; 11777 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11778 mInstantAppInstallerInfo.priority = 1; 11779 mInstantAppInstallerInfo.preferredOrder = 1; 11780 mInstantAppInstallerInfo.isDefault = true; 11781 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11782 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11783 } 11784 11785 private static String calculateBundledApkRoot(final String codePathString) { 11786 final File codePath = new File(codePathString); 11787 final File codeRoot; 11788 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11789 codeRoot = Environment.getRootDirectory(); 11790 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11791 codeRoot = Environment.getOemDirectory(); 11792 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11793 codeRoot = Environment.getVendorDirectory(); 11794 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11795 codeRoot = Environment.getProductDirectory(); 11796 } else { 11797 // Unrecognized code path; take its top real segment as the apk root: 11798 // e.g. /something/app/blah.apk => /something 11799 try { 11800 File f = codePath.getCanonicalFile(); 11801 File parent = f.getParentFile(); // non-null because codePath is a file 11802 File tmp; 11803 while ((tmp = parent.getParentFile()) != null) { 11804 f = parent; 11805 parent = tmp; 11806 } 11807 codeRoot = f; 11808 Slog.w(TAG, "Unrecognized code path " 11809 + codePath + " - using " + codeRoot); 11810 } catch (IOException e) { 11811 // Can't canonicalize the code path -- shenanigans? 11812 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11813 return Environment.getRootDirectory().getPath(); 11814 } 11815 } 11816 return codeRoot.getPath(); 11817 } 11818 11819 /** 11820 * Derive and set the location of native libraries for the given package, 11821 * which varies depending on where and how the package was installed. 11822 */ 11823 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11824 final ApplicationInfo info = pkg.applicationInfo; 11825 final String codePath = pkg.codePath; 11826 final File codeFile = new File(codePath); 11827 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11828 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11829 11830 info.nativeLibraryRootDir = null; 11831 info.nativeLibraryRootRequiresIsa = false; 11832 info.nativeLibraryDir = null; 11833 info.secondaryNativeLibraryDir = null; 11834 11835 if (isApkFile(codeFile)) { 11836 // Monolithic install 11837 if (bundledApp) { 11838 // If "/system/lib64/apkname" exists, assume that is the per-package 11839 // native library directory to use; otherwise use "/system/lib/apkname". 11840 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11841 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11842 getPrimaryInstructionSet(info)); 11843 11844 // This is a bundled system app so choose the path based on the ABI. 11845 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11846 // is just the default path. 11847 final String apkName = deriveCodePathName(codePath); 11848 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11849 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11850 apkName).getAbsolutePath(); 11851 11852 if (info.secondaryCpuAbi != null) { 11853 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11854 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11855 secondaryLibDir, apkName).getAbsolutePath(); 11856 } 11857 } else if (asecApp) { 11858 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11859 .getAbsolutePath(); 11860 } else { 11861 final String apkName = deriveCodePathName(codePath); 11862 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11863 .getAbsolutePath(); 11864 } 11865 11866 info.nativeLibraryRootRequiresIsa = false; 11867 info.nativeLibraryDir = info.nativeLibraryRootDir; 11868 } else { 11869 // Cluster install 11870 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11871 info.nativeLibraryRootRequiresIsa = true; 11872 11873 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11874 getPrimaryInstructionSet(info)).getAbsolutePath(); 11875 11876 if (info.secondaryCpuAbi != null) { 11877 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11878 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11879 } 11880 } 11881 } 11882 11883 /** 11884 * Calculate the abis and roots for a bundled app. These can uniquely 11885 * be determined from the contents of the system partition, i.e whether 11886 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11887 * of this information, and instead assume that the system was built 11888 * sensibly. 11889 */ 11890 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11891 PackageSetting pkgSetting) { 11892 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11893 11894 // If "/system/lib64/apkname" exists, assume that is the per-package 11895 // native library directory to use; otherwise use "/system/lib/apkname". 11896 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11897 setBundledAppAbi(pkg, apkRoot, apkName); 11898 // pkgSetting might be null during rescan following uninstall of updates 11899 // to a bundled app, so accommodate that possibility. The settings in 11900 // that case will be established later from the parsed package. 11901 // 11902 // If the settings aren't null, sync them up with what we've just derived. 11903 // note that apkRoot isn't stored in the package settings. 11904 if (pkgSetting != null) { 11905 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11906 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11907 } 11908 } 11909 11910 /** 11911 * Deduces the ABI of a bundled app and sets the relevant fields on the 11912 * parsed pkg object. 11913 * 11914 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11915 * under which system libraries are installed. 11916 * @param apkName the name of the installed package. 11917 */ 11918 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11919 final File codeFile = new File(pkg.codePath); 11920 11921 final boolean has64BitLibs; 11922 final boolean has32BitLibs; 11923 if (isApkFile(codeFile)) { 11924 // Monolithic install 11925 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11926 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11927 } else { 11928 // Cluster install 11929 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11930 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11931 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11932 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11933 has64BitLibs = (new File(rootDir, isa)).exists(); 11934 } else { 11935 has64BitLibs = false; 11936 } 11937 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11938 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11939 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11940 has32BitLibs = (new File(rootDir, isa)).exists(); 11941 } else { 11942 has32BitLibs = false; 11943 } 11944 } 11945 11946 if (has64BitLibs && !has32BitLibs) { 11947 // The package has 64 bit libs, but not 32 bit libs. Its primary 11948 // ABI should be 64 bit. We can safely assume here that the bundled 11949 // native libraries correspond to the most preferred ABI in the list. 11950 11951 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11952 pkg.applicationInfo.secondaryCpuAbi = null; 11953 } else if (has32BitLibs && !has64BitLibs) { 11954 // The package has 32 bit libs but not 64 bit libs. Its primary 11955 // ABI should be 32 bit. 11956 11957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11958 pkg.applicationInfo.secondaryCpuAbi = null; 11959 } else if (has32BitLibs && has64BitLibs) { 11960 // The application has both 64 and 32 bit bundled libraries. We check 11961 // here that the app declares multiArch support, and warn if it doesn't. 11962 // 11963 // We will be lenient here and record both ABIs. The primary will be the 11964 // ABI that's higher on the list, i.e, a device that's configured to prefer 11965 // 64 bit apps will see a 64 bit primary ABI, 11966 11967 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11968 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11969 } 11970 11971 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11973 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11974 } else { 11975 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11976 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11977 } 11978 } else { 11979 pkg.applicationInfo.primaryCpuAbi = null; 11980 pkg.applicationInfo.secondaryCpuAbi = null; 11981 } 11982 } 11983 11984 private void killApplication(String pkgName, int appId, String reason) { 11985 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11986 } 11987 11988 private void killApplication(String pkgName, int appId, int userId, String reason) { 11989 // Request the ActivityManager to kill the process(only for existing packages) 11990 // so that we do not end up in a confused state while the user is still using the older 11991 // version of the application while the new one gets installed. 11992 final long token = Binder.clearCallingIdentity(); 11993 try { 11994 IActivityManager am = ActivityManager.getService(); 11995 if (am != null) { 11996 try { 11997 am.killApplication(pkgName, appId, userId, reason); 11998 } catch (RemoteException e) { 11999 } 12000 } 12001 } finally { 12002 Binder.restoreCallingIdentity(token); 12003 } 12004 } 12005 12006 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12007 // Remove the parent package setting 12008 PackageSetting ps = (PackageSetting) pkg.mExtras; 12009 if (ps != null) { 12010 removePackageLI(ps, chatty); 12011 } 12012 // Remove the child package setting 12013 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12014 for (int i = 0; i < childCount; i++) { 12015 PackageParser.Package childPkg = pkg.childPackages.get(i); 12016 ps = (PackageSetting) childPkg.mExtras; 12017 if (ps != null) { 12018 removePackageLI(ps, chatty); 12019 } 12020 } 12021 } 12022 12023 void removePackageLI(PackageSetting ps, boolean chatty) { 12024 if (DEBUG_INSTALL) { 12025 if (chatty) 12026 Log.d(TAG, "Removing package " + ps.name); 12027 } 12028 12029 // writer 12030 synchronized (mPackages) { 12031 mPackages.remove(ps.name); 12032 final PackageParser.Package pkg = ps.pkg; 12033 if (pkg != null) { 12034 cleanPackageDataStructuresLILPw(pkg, chatty); 12035 } 12036 } 12037 } 12038 12039 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12040 if (DEBUG_INSTALL) { 12041 if (chatty) 12042 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12043 } 12044 12045 // writer 12046 synchronized (mPackages) { 12047 // Remove the parent package 12048 mPackages.remove(pkg.applicationInfo.packageName); 12049 cleanPackageDataStructuresLILPw(pkg, chatty); 12050 12051 // Remove the child packages 12052 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12053 for (int i = 0; i < childCount; i++) { 12054 PackageParser.Package childPkg = pkg.childPackages.get(i); 12055 mPackages.remove(childPkg.applicationInfo.packageName); 12056 cleanPackageDataStructuresLILPw(childPkg, chatty); 12057 } 12058 } 12059 } 12060 12061 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12062 int N = pkg.providers.size(); 12063 StringBuilder r = null; 12064 int i; 12065 for (i=0; i<N; i++) { 12066 PackageParser.Provider p = pkg.providers.get(i); 12067 mProviders.removeProvider(p); 12068 if (p.info.authority == null) { 12069 12070 /* There was another ContentProvider with this authority when 12071 * this app was installed so this authority is null, 12072 * Ignore it as we don't have to unregister the provider. 12073 */ 12074 continue; 12075 } 12076 String names[] = p.info.authority.split(";"); 12077 for (int j = 0; j < names.length; j++) { 12078 if (mProvidersByAuthority.get(names[j]) == p) { 12079 mProvidersByAuthority.remove(names[j]); 12080 if (DEBUG_REMOVE) { 12081 if (chatty) 12082 Log.d(TAG, "Unregistered content provider: " + names[j] 12083 + ", className = " + p.info.name + ", isSyncable = " 12084 + p.info.isSyncable); 12085 } 12086 } 12087 } 12088 if (DEBUG_REMOVE && chatty) { 12089 if (r == null) { 12090 r = new StringBuilder(256); 12091 } else { 12092 r.append(' '); 12093 } 12094 r.append(p.info.name); 12095 } 12096 } 12097 if (r != null) { 12098 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12099 } 12100 12101 N = pkg.services.size(); 12102 r = null; 12103 for (i=0; i<N; i++) { 12104 PackageParser.Service s = pkg.services.get(i); 12105 mServices.removeService(s); 12106 if (chatty) { 12107 if (r == null) { 12108 r = new StringBuilder(256); 12109 } else { 12110 r.append(' '); 12111 } 12112 r.append(s.info.name); 12113 } 12114 } 12115 if (r != null) { 12116 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12117 } 12118 12119 N = pkg.receivers.size(); 12120 r = null; 12121 for (i=0; i<N; i++) { 12122 PackageParser.Activity a = pkg.receivers.get(i); 12123 mReceivers.removeActivity(a, "receiver"); 12124 if (DEBUG_REMOVE && chatty) { 12125 if (r == null) { 12126 r = new StringBuilder(256); 12127 } else { 12128 r.append(' '); 12129 } 12130 r.append(a.info.name); 12131 } 12132 } 12133 if (r != null) { 12134 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12135 } 12136 12137 N = pkg.activities.size(); 12138 r = null; 12139 for (i=0; i<N; i++) { 12140 PackageParser.Activity a = pkg.activities.get(i); 12141 mActivities.removeActivity(a, "activity"); 12142 if (DEBUG_REMOVE && chatty) { 12143 if (r == null) { 12144 r = new StringBuilder(256); 12145 } else { 12146 r.append(' '); 12147 } 12148 r.append(a.info.name); 12149 } 12150 } 12151 if (r != null) { 12152 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12153 } 12154 12155 mPermissionManager.removeAllPermissions(pkg, chatty); 12156 12157 N = pkg.instrumentation.size(); 12158 r = null; 12159 for (i=0; i<N; i++) { 12160 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12161 mInstrumentation.remove(a.getComponentName()); 12162 if (DEBUG_REMOVE && chatty) { 12163 if (r == null) { 12164 r = new StringBuilder(256); 12165 } else { 12166 r.append(' '); 12167 } 12168 r.append(a.info.name); 12169 } 12170 } 12171 if (r != null) { 12172 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12173 } 12174 12175 r = null; 12176 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12177 // Only system apps can hold shared libraries. 12178 if (pkg.libraryNames != null) { 12179 for (i = 0; i < pkg.libraryNames.size(); i++) { 12180 String name = pkg.libraryNames.get(i); 12181 if (removeSharedLibraryLPw(name, 0)) { 12182 if (DEBUG_REMOVE && chatty) { 12183 if (r == null) { 12184 r = new StringBuilder(256); 12185 } else { 12186 r.append(' '); 12187 } 12188 r.append(name); 12189 } 12190 } 12191 } 12192 } 12193 } 12194 12195 r = null; 12196 12197 // Any package can hold static shared libraries. 12198 if (pkg.staticSharedLibName != null) { 12199 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12200 if (DEBUG_REMOVE && chatty) { 12201 if (r == null) { 12202 r = new StringBuilder(256); 12203 } else { 12204 r.append(' '); 12205 } 12206 r.append(pkg.staticSharedLibName); 12207 } 12208 } 12209 } 12210 12211 if (r != null) { 12212 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12213 } 12214 } 12215 12216 12217 final class ActivityIntentResolver 12218 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12220 boolean defaultOnly, int userId) { 12221 if (!sUserManager.exists(userId)) return null; 12222 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12223 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12224 } 12225 12226 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12227 int userId) { 12228 if (!sUserManager.exists(userId)) return null; 12229 mFlags = flags; 12230 return super.queryIntent(intent, resolvedType, 12231 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12232 userId); 12233 } 12234 12235 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12236 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12237 if (!sUserManager.exists(userId)) return null; 12238 if (packageActivities == null) { 12239 return null; 12240 } 12241 mFlags = flags; 12242 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12243 final int N = packageActivities.size(); 12244 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12245 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12246 12247 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12248 for (int i = 0; i < N; ++i) { 12249 intentFilters = packageActivities.get(i).intents; 12250 if (intentFilters != null && intentFilters.size() > 0) { 12251 PackageParser.ActivityIntentInfo[] array = 12252 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12253 intentFilters.toArray(array); 12254 listCut.add(array); 12255 } 12256 } 12257 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12258 } 12259 12260 /** 12261 * Finds a privileged activity that matches the specified activity names. 12262 */ 12263 private PackageParser.Activity findMatchingActivity( 12264 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12265 for (PackageParser.Activity sysActivity : activityList) { 12266 if (sysActivity.info.name.equals(activityInfo.name)) { 12267 return sysActivity; 12268 } 12269 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12270 return sysActivity; 12271 } 12272 if (sysActivity.info.targetActivity != null) { 12273 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12274 return sysActivity; 12275 } 12276 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12277 return sysActivity; 12278 } 12279 } 12280 } 12281 return null; 12282 } 12283 12284 public class IterGenerator<E> { 12285 public Iterator<E> generate(ActivityIntentInfo info) { 12286 return null; 12287 } 12288 } 12289 12290 public class ActionIterGenerator extends IterGenerator<String> { 12291 @Override 12292 public Iterator<String> generate(ActivityIntentInfo info) { 12293 return info.actionsIterator(); 12294 } 12295 } 12296 12297 public class CategoriesIterGenerator extends IterGenerator<String> { 12298 @Override 12299 public Iterator<String> generate(ActivityIntentInfo info) { 12300 return info.categoriesIterator(); 12301 } 12302 } 12303 12304 public class SchemesIterGenerator extends IterGenerator<String> { 12305 @Override 12306 public Iterator<String> generate(ActivityIntentInfo info) { 12307 return info.schemesIterator(); 12308 } 12309 } 12310 12311 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12312 @Override 12313 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12314 return info.authoritiesIterator(); 12315 } 12316 } 12317 12318 /** 12319 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12320 * MODIFIED. Do not pass in a list that should not be changed. 12321 */ 12322 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12323 IterGenerator<T> generator, Iterator<T> searchIterator) { 12324 // loop through the set of actions; every one must be found in the intent filter 12325 while (searchIterator.hasNext()) { 12326 // we must have at least one filter in the list to consider a match 12327 if (intentList.size() == 0) { 12328 break; 12329 } 12330 12331 final T searchAction = searchIterator.next(); 12332 12333 // loop through the set of intent filters 12334 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12335 while (intentIter.hasNext()) { 12336 final ActivityIntentInfo intentInfo = intentIter.next(); 12337 boolean selectionFound = false; 12338 12339 // loop through the intent filter's selection criteria; at least one 12340 // of them must match the searched criteria 12341 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12342 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12343 final T intentSelection = intentSelectionIter.next(); 12344 if (intentSelection != null && intentSelection.equals(searchAction)) { 12345 selectionFound = true; 12346 break; 12347 } 12348 } 12349 12350 // the selection criteria wasn't found in this filter's set; this filter 12351 // is not a potential match 12352 if (!selectionFound) { 12353 intentIter.remove(); 12354 } 12355 } 12356 } 12357 } 12358 12359 private boolean isProtectedAction(ActivityIntentInfo filter) { 12360 final Iterator<String> actionsIter = filter.actionsIterator(); 12361 while (actionsIter != null && actionsIter.hasNext()) { 12362 final String filterAction = actionsIter.next(); 12363 if (PROTECTED_ACTIONS.contains(filterAction)) { 12364 return true; 12365 } 12366 } 12367 return false; 12368 } 12369 12370 /** 12371 * Adjusts the priority of the given intent filter according to policy. 12372 * <p> 12373 * <ul> 12374 * <li>The priority for non privileged applications is capped to '0'</li> 12375 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12376 * <li>The priority for unbundled updates to privileged applications is capped to the 12377 * priority defined on the system partition</li> 12378 * </ul> 12379 * <p> 12380 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12381 * allowed to obtain any priority on any action. 12382 */ 12383 private void adjustPriority( 12384 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12385 // nothing to do; priority is fine as-is 12386 if (intent.getPriority() <= 0) { 12387 return; 12388 } 12389 12390 final ActivityInfo activityInfo = intent.activity.info; 12391 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12392 12393 final boolean privilegedApp = 12394 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12395 if (!privilegedApp) { 12396 // non-privileged applications can never define a priority >0 12397 if (DEBUG_FILTERS) { 12398 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12399 + " package: " + applicationInfo.packageName 12400 + " activity: " + intent.activity.className 12401 + " origPrio: " + intent.getPriority()); 12402 } 12403 intent.setPriority(0); 12404 return; 12405 } 12406 12407 if (systemActivities == null) { 12408 // the system package is not disabled; we're parsing the system partition 12409 if (isProtectedAction(intent)) { 12410 if (mDeferProtectedFilters) { 12411 // We can't deal with these just yet. No component should ever obtain a 12412 // >0 priority for a protected actions, with ONE exception -- the setup 12413 // wizard. The setup wizard, however, cannot be known until we're able to 12414 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12415 // until all intent filters have been processed. Chicken, meet egg. 12416 // Let the filter temporarily have a high priority and rectify the 12417 // priorities after all system packages have been scanned. 12418 mProtectedFilters.add(intent); 12419 if (DEBUG_FILTERS) { 12420 Slog.i(TAG, "Protected action; save for later;" 12421 + " package: " + applicationInfo.packageName 12422 + " activity: " + intent.activity.className 12423 + " origPrio: " + intent.getPriority()); 12424 } 12425 return; 12426 } else { 12427 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12428 Slog.i(TAG, "No setup wizard;" 12429 + " All protected intents capped to priority 0"); 12430 } 12431 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12432 if (DEBUG_FILTERS) { 12433 Slog.i(TAG, "Found setup wizard;" 12434 + " allow priority " + intent.getPriority() + ";" 12435 + " package: " + intent.activity.info.packageName 12436 + " activity: " + intent.activity.className 12437 + " priority: " + intent.getPriority()); 12438 } 12439 // setup wizard gets whatever it wants 12440 return; 12441 } 12442 if (DEBUG_FILTERS) { 12443 Slog.i(TAG, "Protected action; cap priority to 0;" 12444 + " package: " + intent.activity.info.packageName 12445 + " activity: " + intent.activity.className 12446 + " origPrio: " + intent.getPriority()); 12447 } 12448 intent.setPriority(0); 12449 return; 12450 } 12451 } 12452 // privileged apps on the system image get whatever priority they request 12453 return; 12454 } 12455 12456 // privileged app unbundled update ... try to find the same activity 12457 final PackageParser.Activity foundActivity = 12458 findMatchingActivity(systemActivities, activityInfo); 12459 if (foundActivity == null) { 12460 // this is a new activity; it cannot obtain >0 priority 12461 if (DEBUG_FILTERS) { 12462 Slog.i(TAG, "New activity; cap priority to 0;" 12463 + " package: " + applicationInfo.packageName 12464 + " activity: " + intent.activity.className 12465 + " origPrio: " + intent.getPriority()); 12466 } 12467 intent.setPriority(0); 12468 return; 12469 } 12470 12471 // found activity, now check for filter equivalence 12472 12473 // a shallow copy is enough; we modify the list, not its contents 12474 final List<ActivityIntentInfo> intentListCopy = 12475 new ArrayList<>(foundActivity.intents); 12476 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12477 12478 // find matching action subsets 12479 final Iterator<String> actionsIterator = intent.actionsIterator(); 12480 if (actionsIterator != null) { 12481 getIntentListSubset( 12482 intentListCopy, new ActionIterGenerator(), actionsIterator); 12483 if (intentListCopy.size() == 0) { 12484 // no more intents to match; we're not equivalent 12485 if (DEBUG_FILTERS) { 12486 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12487 + " package: " + applicationInfo.packageName 12488 + " activity: " + intent.activity.className 12489 + " origPrio: " + intent.getPriority()); 12490 } 12491 intent.setPriority(0); 12492 return; 12493 } 12494 } 12495 12496 // find matching category subsets 12497 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12498 if (categoriesIterator != null) { 12499 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12500 categoriesIterator); 12501 if (intentListCopy.size() == 0) { 12502 // no more intents to match; we're not equivalent 12503 if (DEBUG_FILTERS) { 12504 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12505 + " package: " + applicationInfo.packageName 12506 + " activity: " + intent.activity.className 12507 + " origPrio: " + intent.getPriority()); 12508 } 12509 intent.setPriority(0); 12510 return; 12511 } 12512 } 12513 12514 // find matching schemes subsets 12515 final Iterator<String> schemesIterator = intent.schemesIterator(); 12516 if (schemesIterator != null) { 12517 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12518 schemesIterator); 12519 if (intentListCopy.size() == 0) { 12520 // no more intents to match; we're not equivalent 12521 if (DEBUG_FILTERS) { 12522 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12523 + " package: " + applicationInfo.packageName 12524 + " activity: " + intent.activity.className 12525 + " origPrio: " + intent.getPriority()); 12526 } 12527 intent.setPriority(0); 12528 return; 12529 } 12530 } 12531 12532 // find matching authorities subsets 12533 final Iterator<IntentFilter.AuthorityEntry> 12534 authoritiesIterator = intent.authoritiesIterator(); 12535 if (authoritiesIterator != null) { 12536 getIntentListSubset(intentListCopy, 12537 new AuthoritiesIterGenerator(), 12538 authoritiesIterator); 12539 if (intentListCopy.size() == 0) { 12540 // no more intents to match; we're not equivalent 12541 if (DEBUG_FILTERS) { 12542 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12543 + " package: " + applicationInfo.packageName 12544 + " activity: " + intent.activity.className 12545 + " origPrio: " + intent.getPriority()); 12546 } 12547 intent.setPriority(0); 12548 return; 12549 } 12550 } 12551 12552 // we found matching filter(s); app gets the max priority of all intents 12553 int cappedPriority = 0; 12554 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12555 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12556 } 12557 if (intent.getPriority() > cappedPriority) { 12558 if (DEBUG_FILTERS) { 12559 Slog.i(TAG, "Found matching filter(s);" 12560 + " cap priority to " + cappedPriority + ";" 12561 + " package: " + applicationInfo.packageName 12562 + " activity: " + intent.activity.className 12563 + " origPrio: " + intent.getPriority()); 12564 } 12565 intent.setPriority(cappedPriority); 12566 return; 12567 } 12568 // all this for nothing; the requested priority was <= what was on the system 12569 } 12570 12571 public final void addActivity(PackageParser.Activity a, String type) { 12572 mActivities.put(a.getComponentName(), a); 12573 if (DEBUG_SHOW_INFO) 12574 Log.v( 12575 TAG, " " + type + " " + 12576 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12577 if (DEBUG_SHOW_INFO) 12578 Log.v(TAG, " Class=" + a.info.name); 12579 final int NI = a.intents.size(); 12580 for (int j=0; j<NI; j++) { 12581 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12582 if ("activity".equals(type)) { 12583 final PackageSetting ps = 12584 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12585 final List<PackageParser.Activity> systemActivities = 12586 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12587 adjustPriority(systemActivities, intent); 12588 } 12589 if (DEBUG_SHOW_INFO) { 12590 Log.v(TAG, " IntentFilter:"); 12591 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12592 } 12593 if (!intent.debugCheck()) { 12594 Log.w(TAG, "==> For Activity " + a.info.name); 12595 } 12596 addFilter(intent); 12597 } 12598 } 12599 12600 public final void removeActivity(PackageParser.Activity a, String type) { 12601 mActivities.remove(a.getComponentName()); 12602 if (DEBUG_SHOW_INFO) { 12603 Log.v(TAG, " " + type + " " 12604 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12605 : a.info.name) + ":"); 12606 Log.v(TAG, " Class=" + a.info.name); 12607 } 12608 final int NI = a.intents.size(); 12609 for (int j=0; j<NI; j++) { 12610 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12611 if (DEBUG_SHOW_INFO) { 12612 Log.v(TAG, " IntentFilter:"); 12613 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12614 } 12615 removeFilter(intent); 12616 } 12617 } 12618 12619 @Override 12620 protected boolean allowFilterResult( 12621 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12622 ActivityInfo filterAi = filter.activity.info; 12623 for (int i=dest.size()-1; i>=0; i--) { 12624 ActivityInfo destAi = dest.get(i).activityInfo; 12625 if (destAi.name == filterAi.name 12626 && destAi.packageName == filterAi.packageName) { 12627 return false; 12628 } 12629 } 12630 return true; 12631 } 12632 12633 @Override 12634 protected ActivityIntentInfo[] newArray(int size) { 12635 return new ActivityIntentInfo[size]; 12636 } 12637 12638 @Override 12639 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12640 if (!sUserManager.exists(userId)) return true; 12641 PackageParser.Package p = filter.activity.owner; 12642 if (p != null) { 12643 PackageSetting ps = (PackageSetting)p.mExtras; 12644 if (ps != null) { 12645 // System apps are never considered stopped for purposes of 12646 // filtering, because there may be no way for the user to 12647 // actually re-launch them. 12648 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12649 && ps.getStopped(userId); 12650 } 12651 } 12652 return false; 12653 } 12654 12655 @Override 12656 protected boolean isPackageForFilter(String packageName, 12657 PackageParser.ActivityIntentInfo info) { 12658 return packageName.equals(info.activity.owner.packageName); 12659 } 12660 12661 @Override 12662 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12663 int match, int userId) { 12664 if (!sUserManager.exists(userId)) return null; 12665 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12666 return null; 12667 } 12668 final PackageParser.Activity activity = info.activity; 12669 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12670 if (ps == null) { 12671 return null; 12672 } 12673 final PackageUserState userState = ps.readUserState(userId); 12674 ActivityInfo ai = 12675 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12676 if (ai == null) { 12677 return null; 12678 } 12679 final boolean matchExplicitlyVisibleOnly = 12680 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12681 final boolean matchVisibleToInstantApp = 12682 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12683 final boolean componentVisible = 12684 matchVisibleToInstantApp 12685 && info.isVisibleToInstantApp() 12686 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12687 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12688 // throw out filters that aren't visible to ephemeral apps 12689 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12690 return null; 12691 } 12692 // throw out instant app filters if we're not explicitly requesting them 12693 if (!matchInstantApp && userState.instantApp) { 12694 return null; 12695 } 12696 // throw out instant app filters if updates are available; will trigger 12697 // instant app resolution 12698 if (userState.instantApp && ps.isUpdateAvailable()) { 12699 return null; 12700 } 12701 final ResolveInfo res = new ResolveInfo(); 12702 res.activityInfo = ai; 12703 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12704 res.filter = info; 12705 } 12706 if (info != null) { 12707 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12708 } 12709 res.priority = info.getPriority(); 12710 res.preferredOrder = activity.owner.mPreferredOrder; 12711 //System.out.println("Result: " + res.activityInfo.className + 12712 // " = " + res.priority); 12713 res.match = match; 12714 res.isDefault = info.hasDefault; 12715 res.labelRes = info.labelRes; 12716 res.nonLocalizedLabel = info.nonLocalizedLabel; 12717 if (userNeedsBadging(userId)) { 12718 res.noResourceId = true; 12719 } else { 12720 res.icon = info.icon; 12721 } 12722 res.iconResourceId = info.icon; 12723 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12724 res.isInstantAppAvailable = userState.instantApp; 12725 return res; 12726 } 12727 12728 @Override 12729 protected void sortResults(List<ResolveInfo> results) { 12730 Collections.sort(results, mResolvePrioritySorter); 12731 } 12732 12733 @Override 12734 protected void dumpFilter(PrintWriter out, String prefix, 12735 PackageParser.ActivityIntentInfo filter) { 12736 out.print(prefix); out.print( 12737 Integer.toHexString(System.identityHashCode(filter.activity))); 12738 out.print(' '); 12739 filter.activity.printComponentShortName(out); 12740 out.print(" filter "); 12741 out.println(Integer.toHexString(System.identityHashCode(filter))); 12742 } 12743 12744 @Override 12745 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12746 return filter.activity; 12747 } 12748 12749 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12750 PackageParser.Activity activity = (PackageParser.Activity)label; 12751 out.print(prefix); out.print( 12752 Integer.toHexString(System.identityHashCode(activity))); 12753 out.print(' '); 12754 activity.printComponentShortName(out); 12755 if (count > 1) { 12756 out.print(" ("); out.print(count); out.print(" filters)"); 12757 } 12758 out.println(); 12759 } 12760 12761 // Keys are String (activity class name), values are Activity. 12762 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12763 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12764 private int mFlags; 12765 } 12766 12767 private final class ServiceIntentResolver 12768 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12769 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12770 boolean defaultOnly, int userId) { 12771 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12772 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12773 } 12774 12775 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12776 int userId) { 12777 if (!sUserManager.exists(userId)) return null; 12778 mFlags = flags; 12779 return super.queryIntent(intent, resolvedType, 12780 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12781 userId); 12782 } 12783 12784 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12785 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12786 if (!sUserManager.exists(userId)) return null; 12787 if (packageServices == null) { 12788 return null; 12789 } 12790 mFlags = flags; 12791 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12792 final int N = packageServices.size(); 12793 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12794 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12795 12796 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12797 for (int i = 0; i < N; ++i) { 12798 intentFilters = packageServices.get(i).intents; 12799 if (intentFilters != null && intentFilters.size() > 0) { 12800 PackageParser.ServiceIntentInfo[] array = 12801 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12802 intentFilters.toArray(array); 12803 listCut.add(array); 12804 } 12805 } 12806 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12807 } 12808 12809 public final void addService(PackageParser.Service s) { 12810 mServices.put(s.getComponentName(), s); 12811 if (DEBUG_SHOW_INFO) { 12812 Log.v(TAG, " " 12813 + (s.info.nonLocalizedLabel != null 12814 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12815 Log.v(TAG, " Class=" + s.info.name); 12816 } 12817 final int NI = s.intents.size(); 12818 int j; 12819 for (j=0; j<NI; j++) { 12820 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12821 if (DEBUG_SHOW_INFO) { 12822 Log.v(TAG, " IntentFilter:"); 12823 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12824 } 12825 if (!intent.debugCheck()) { 12826 Log.w(TAG, "==> For Service " + s.info.name); 12827 } 12828 addFilter(intent); 12829 } 12830 } 12831 12832 public final void removeService(PackageParser.Service s) { 12833 mServices.remove(s.getComponentName()); 12834 if (DEBUG_SHOW_INFO) { 12835 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12836 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12837 Log.v(TAG, " Class=" + s.info.name); 12838 } 12839 final int NI = s.intents.size(); 12840 int j; 12841 for (j=0; j<NI; j++) { 12842 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12843 if (DEBUG_SHOW_INFO) { 12844 Log.v(TAG, " IntentFilter:"); 12845 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12846 } 12847 removeFilter(intent); 12848 } 12849 } 12850 12851 @Override 12852 protected boolean allowFilterResult( 12853 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12854 ServiceInfo filterSi = filter.service.info; 12855 for (int i=dest.size()-1; i>=0; i--) { 12856 ServiceInfo destAi = dest.get(i).serviceInfo; 12857 if (destAi.name == filterSi.name 12858 && destAi.packageName == filterSi.packageName) { 12859 return false; 12860 } 12861 } 12862 return true; 12863 } 12864 12865 @Override 12866 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12867 return new PackageParser.ServiceIntentInfo[size]; 12868 } 12869 12870 @Override 12871 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12872 if (!sUserManager.exists(userId)) return true; 12873 PackageParser.Package p = filter.service.owner; 12874 if (p != null) { 12875 PackageSetting ps = (PackageSetting)p.mExtras; 12876 if (ps != null) { 12877 // System apps are never considered stopped for purposes of 12878 // filtering, because there may be no way for the user to 12879 // actually re-launch them. 12880 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12881 && ps.getStopped(userId); 12882 } 12883 } 12884 return false; 12885 } 12886 12887 @Override 12888 protected boolean isPackageForFilter(String packageName, 12889 PackageParser.ServiceIntentInfo info) { 12890 return packageName.equals(info.service.owner.packageName); 12891 } 12892 12893 @Override 12894 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12895 int match, int userId) { 12896 if (!sUserManager.exists(userId)) return null; 12897 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12898 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12899 return null; 12900 } 12901 final PackageParser.Service service = info.service; 12902 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12903 if (ps == null) { 12904 return null; 12905 } 12906 final PackageUserState userState = ps.readUserState(userId); 12907 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12908 userState, userId); 12909 if (si == null) { 12910 return null; 12911 } 12912 final boolean matchVisibleToInstantApp = 12913 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12914 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12915 // throw out filters that aren't visible to ephemeral apps 12916 if (matchVisibleToInstantApp 12917 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12918 return null; 12919 } 12920 // throw out ephemeral filters if we're not explicitly requesting them 12921 if (!isInstantApp && userState.instantApp) { 12922 return null; 12923 } 12924 // throw out instant app filters if updates are available; will trigger 12925 // instant app resolution 12926 if (userState.instantApp && ps.isUpdateAvailable()) { 12927 return null; 12928 } 12929 final ResolveInfo res = new ResolveInfo(); 12930 res.serviceInfo = si; 12931 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12932 res.filter = filter; 12933 } 12934 res.priority = info.getPriority(); 12935 res.preferredOrder = service.owner.mPreferredOrder; 12936 res.match = match; 12937 res.isDefault = info.hasDefault; 12938 res.labelRes = info.labelRes; 12939 res.nonLocalizedLabel = info.nonLocalizedLabel; 12940 res.icon = info.icon; 12941 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12942 return res; 12943 } 12944 12945 @Override 12946 protected void sortResults(List<ResolveInfo> results) { 12947 Collections.sort(results, mResolvePrioritySorter); 12948 } 12949 12950 @Override 12951 protected void dumpFilter(PrintWriter out, String prefix, 12952 PackageParser.ServiceIntentInfo filter) { 12953 out.print(prefix); out.print( 12954 Integer.toHexString(System.identityHashCode(filter.service))); 12955 out.print(' '); 12956 filter.service.printComponentShortName(out); 12957 out.print(" filter "); 12958 out.print(Integer.toHexString(System.identityHashCode(filter))); 12959 if (filter.service.info.permission != null) { 12960 out.print(" permission "); out.println(filter.service.info.permission); 12961 } else { 12962 out.println(); 12963 } 12964 } 12965 12966 @Override 12967 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12968 return filter.service; 12969 } 12970 12971 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12972 PackageParser.Service service = (PackageParser.Service)label; 12973 out.print(prefix); out.print( 12974 Integer.toHexString(System.identityHashCode(service))); 12975 out.print(' '); 12976 service.printComponentShortName(out); 12977 if (count > 1) { 12978 out.print(" ("); out.print(count); out.print(" filters)"); 12979 } 12980 out.println(); 12981 } 12982 12983// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12984// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12985// final List<ResolveInfo> retList = Lists.newArrayList(); 12986// while (i.hasNext()) { 12987// final ResolveInfo resolveInfo = (ResolveInfo) i; 12988// if (isEnabledLP(resolveInfo.serviceInfo)) { 12989// retList.add(resolveInfo); 12990// } 12991// } 12992// return retList; 12993// } 12994 12995 // Keys are String (activity class name), values are Activity. 12996 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12997 = new ArrayMap<ComponentName, PackageParser.Service>(); 12998 private int mFlags; 12999 } 13000 13001 private final class ProviderIntentResolver 13002 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13003 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13004 boolean defaultOnly, int userId) { 13005 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13006 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13007 } 13008 13009 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13010 int userId) { 13011 if (!sUserManager.exists(userId)) 13012 return null; 13013 mFlags = flags; 13014 return super.queryIntent(intent, resolvedType, 13015 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13016 userId); 13017 } 13018 13019 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13020 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13021 if (!sUserManager.exists(userId)) 13022 return null; 13023 if (packageProviders == null) { 13024 return null; 13025 } 13026 mFlags = flags; 13027 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13028 final int N = packageProviders.size(); 13029 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13030 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13031 13032 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13033 for (int i = 0; i < N; ++i) { 13034 intentFilters = packageProviders.get(i).intents; 13035 if (intentFilters != null && intentFilters.size() > 0) { 13036 PackageParser.ProviderIntentInfo[] array = 13037 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13038 intentFilters.toArray(array); 13039 listCut.add(array); 13040 } 13041 } 13042 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13043 } 13044 13045 public final void addProvider(PackageParser.Provider p) { 13046 if (mProviders.containsKey(p.getComponentName())) { 13047 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13048 return; 13049 } 13050 13051 mProviders.put(p.getComponentName(), p); 13052 if (DEBUG_SHOW_INFO) { 13053 Log.v(TAG, " " 13054 + (p.info.nonLocalizedLabel != null 13055 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13056 Log.v(TAG, " Class=" + p.info.name); 13057 } 13058 final int NI = p.intents.size(); 13059 int j; 13060 for (j = 0; j < NI; j++) { 13061 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13062 if (DEBUG_SHOW_INFO) { 13063 Log.v(TAG, " IntentFilter:"); 13064 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13065 } 13066 if (!intent.debugCheck()) { 13067 Log.w(TAG, "==> For Provider " + p.info.name); 13068 } 13069 addFilter(intent); 13070 } 13071 } 13072 13073 public final void removeProvider(PackageParser.Provider p) { 13074 mProviders.remove(p.getComponentName()); 13075 if (DEBUG_SHOW_INFO) { 13076 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13077 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13078 Log.v(TAG, " Class=" + p.info.name); 13079 } 13080 final int NI = p.intents.size(); 13081 int j; 13082 for (j = 0; j < NI; j++) { 13083 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13084 if (DEBUG_SHOW_INFO) { 13085 Log.v(TAG, " IntentFilter:"); 13086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13087 } 13088 removeFilter(intent); 13089 } 13090 } 13091 13092 @Override 13093 protected boolean allowFilterResult( 13094 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13095 ProviderInfo filterPi = filter.provider.info; 13096 for (int i = dest.size() - 1; i >= 0; i--) { 13097 ProviderInfo destPi = dest.get(i).providerInfo; 13098 if (destPi.name == filterPi.name 13099 && destPi.packageName == filterPi.packageName) { 13100 return false; 13101 } 13102 } 13103 return true; 13104 } 13105 13106 @Override 13107 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13108 return new PackageParser.ProviderIntentInfo[size]; 13109 } 13110 13111 @Override 13112 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13113 if (!sUserManager.exists(userId)) 13114 return true; 13115 PackageParser.Package p = filter.provider.owner; 13116 if (p != null) { 13117 PackageSetting ps = (PackageSetting) p.mExtras; 13118 if (ps != null) { 13119 // System apps are never considered stopped for purposes of 13120 // filtering, because there may be no way for the user to 13121 // actually re-launch them. 13122 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13123 && ps.getStopped(userId); 13124 } 13125 } 13126 return false; 13127 } 13128 13129 @Override 13130 protected boolean isPackageForFilter(String packageName, 13131 PackageParser.ProviderIntentInfo info) { 13132 return packageName.equals(info.provider.owner.packageName); 13133 } 13134 13135 @Override 13136 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13137 int match, int userId) { 13138 if (!sUserManager.exists(userId)) 13139 return null; 13140 final PackageParser.ProviderIntentInfo info = filter; 13141 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13142 return null; 13143 } 13144 final PackageParser.Provider provider = info.provider; 13145 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13146 if (ps == null) { 13147 return null; 13148 } 13149 final PackageUserState userState = ps.readUserState(userId); 13150 final boolean matchVisibleToInstantApp = 13151 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13152 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13153 // throw out filters that aren't visible to instant applications 13154 if (matchVisibleToInstantApp 13155 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13156 return null; 13157 } 13158 // throw out instant application filters if we're not explicitly requesting them 13159 if (!isInstantApp && userState.instantApp) { 13160 return null; 13161 } 13162 // throw out instant application filters if updates are available; will trigger 13163 // instant application resolution 13164 if (userState.instantApp && ps.isUpdateAvailable()) { 13165 return null; 13166 } 13167 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13168 userState, userId); 13169 if (pi == null) { 13170 return null; 13171 } 13172 final ResolveInfo res = new ResolveInfo(); 13173 res.providerInfo = pi; 13174 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13175 res.filter = filter; 13176 } 13177 res.priority = info.getPriority(); 13178 res.preferredOrder = provider.owner.mPreferredOrder; 13179 res.match = match; 13180 res.isDefault = info.hasDefault; 13181 res.labelRes = info.labelRes; 13182 res.nonLocalizedLabel = info.nonLocalizedLabel; 13183 res.icon = info.icon; 13184 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13185 return res; 13186 } 13187 13188 @Override 13189 protected void sortResults(List<ResolveInfo> results) { 13190 Collections.sort(results, mResolvePrioritySorter); 13191 } 13192 13193 @Override 13194 protected void dumpFilter(PrintWriter out, String prefix, 13195 PackageParser.ProviderIntentInfo filter) { 13196 out.print(prefix); 13197 out.print( 13198 Integer.toHexString(System.identityHashCode(filter.provider))); 13199 out.print(' '); 13200 filter.provider.printComponentShortName(out); 13201 out.print(" filter "); 13202 out.println(Integer.toHexString(System.identityHashCode(filter))); 13203 } 13204 13205 @Override 13206 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13207 return filter.provider; 13208 } 13209 13210 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13211 PackageParser.Provider provider = (PackageParser.Provider)label; 13212 out.print(prefix); out.print( 13213 Integer.toHexString(System.identityHashCode(provider))); 13214 out.print(' '); 13215 provider.printComponentShortName(out); 13216 if (count > 1) { 13217 out.print(" ("); out.print(count); out.print(" filters)"); 13218 } 13219 out.println(); 13220 } 13221 13222 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13223 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13224 private int mFlags; 13225 } 13226 13227 static final class EphemeralIntentResolver 13228 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13229 AuxiliaryResolveInfo.AuxiliaryFilter> { 13230 /** 13231 * The result that has the highest defined order. Ordering applies on a 13232 * per-package basis. Mapping is from package name to Pair of order and 13233 * EphemeralResolveInfo. 13234 * <p> 13235 * NOTE: This is implemented as a field variable for convenience and efficiency. 13236 * By having a field variable, we're able to track filter ordering as soon as 13237 * a non-zero order is defined. Otherwise, multiple loops across the result set 13238 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13239 * this needs to be contained entirely within {@link #filterResults}. 13240 */ 13241 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13242 13243 @Override 13244 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13245 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13246 } 13247 13248 @Override 13249 protected boolean isPackageForFilter(String packageName, 13250 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13251 return true; 13252 } 13253 13254 @Override 13255 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13256 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13257 if (!sUserManager.exists(userId)) { 13258 return null; 13259 } 13260 final String packageName = responseObj.resolveInfo.getPackageName(); 13261 final Integer order = responseObj.getOrder(); 13262 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13263 mOrderResult.get(packageName); 13264 // ordering is enabled and this item's order isn't high enough 13265 if (lastOrderResult != null && lastOrderResult.first >= order) { 13266 return null; 13267 } 13268 final InstantAppResolveInfo res = responseObj.resolveInfo; 13269 if (order > 0) { 13270 // non-zero order, enable ordering 13271 mOrderResult.put(packageName, new Pair<>(order, res)); 13272 } 13273 return responseObj; 13274 } 13275 13276 @Override 13277 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13278 // only do work if ordering is enabled [most of the time it won't be] 13279 if (mOrderResult.size() == 0) { 13280 return; 13281 } 13282 int resultSize = results.size(); 13283 for (int i = 0; i < resultSize; i++) { 13284 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13285 final String packageName = info.getPackageName(); 13286 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13287 if (savedInfo == null) { 13288 // package doesn't having ordering 13289 continue; 13290 } 13291 if (savedInfo.second == info) { 13292 // circled back to the highest ordered item; remove from order list 13293 mOrderResult.remove(packageName); 13294 if (mOrderResult.size() == 0) { 13295 // no more ordered items 13296 break; 13297 } 13298 continue; 13299 } 13300 // item has a worse order, remove it from the result list 13301 results.remove(i); 13302 resultSize--; 13303 i--; 13304 } 13305 } 13306 } 13307 13308 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13309 new Comparator<ResolveInfo>() { 13310 public int compare(ResolveInfo r1, ResolveInfo r2) { 13311 int v1 = r1.priority; 13312 int v2 = r2.priority; 13313 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13314 if (v1 != v2) { 13315 return (v1 > v2) ? -1 : 1; 13316 } 13317 v1 = r1.preferredOrder; 13318 v2 = r2.preferredOrder; 13319 if (v1 != v2) { 13320 return (v1 > v2) ? -1 : 1; 13321 } 13322 if (r1.isDefault != r2.isDefault) { 13323 return r1.isDefault ? -1 : 1; 13324 } 13325 v1 = r1.match; 13326 v2 = r2.match; 13327 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13328 if (v1 != v2) { 13329 return (v1 > v2) ? -1 : 1; 13330 } 13331 if (r1.system != r2.system) { 13332 return r1.system ? -1 : 1; 13333 } 13334 if (r1.activityInfo != null) { 13335 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13336 } 13337 if (r1.serviceInfo != null) { 13338 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13339 } 13340 if (r1.providerInfo != null) { 13341 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13342 } 13343 return 0; 13344 } 13345 }; 13346 13347 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13348 new Comparator<ProviderInfo>() { 13349 public int compare(ProviderInfo p1, ProviderInfo p2) { 13350 final int v1 = p1.initOrder; 13351 final int v2 = p2.initOrder; 13352 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13353 } 13354 }; 13355 13356 @Override 13357 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13358 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13359 final int[] userIds, int[] instantUserIds) { 13360 mHandler.post(new Runnable() { 13361 @Override 13362 public void run() { 13363 try { 13364 final IActivityManager am = ActivityManager.getService(); 13365 if (am == null) return; 13366 final int[] resolvedUserIds; 13367 if (userIds == null) { 13368 resolvedUserIds = am.getRunningUserIds(); 13369 } else { 13370 resolvedUserIds = userIds; 13371 } 13372 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13373 resolvedUserIds, false); 13374 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13375 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13376 instantUserIds, true); 13377 } 13378 } catch (RemoteException ex) { 13379 } 13380 } 13381 }); 13382 } 13383 13384 @Override 13385 public void notifyPackageAdded(String packageName) { 13386 final PackageListObserver[] observers; 13387 synchronized (mPackages) { 13388 if (mPackageListObservers.size() == 0) { 13389 return; 13390 } 13391 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13392 } 13393 for (int i = observers.length - 1; i >= 0; --i) { 13394 observers[i].onPackageAdded(packageName); 13395 } 13396 } 13397 13398 @Override 13399 public void notifyPackageRemoved(String packageName) { 13400 final PackageListObserver[] observers; 13401 synchronized (mPackages) { 13402 if (mPackageListObservers.size() == 0) { 13403 return; 13404 } 13405 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13406 } 13407 for (int i = observers.length - 1; i >= 0; --i) { 13408 observers[i].onPackageRemoved(packageName); 13409 } 13410 } 13411 13412 /** 13413 * Sends a broadcast for the given action. 13414 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13415 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13416 * the system and applications allowed to see instant applications to receive package 13417 * lifecycle events for instant applications. 13418 */ 13419 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13420 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13421 int[] userIds, boolean isInstantApp) 13422 throws RemoteException { 13423 for (int id : userIds) { 13424 final Intent intent = new Intent(action, 13425 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13426 final String[] requiredPermissions = 13427 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13428 if (extras != null) { 13429 intent.putExtras(extras); 13430 } 13431 if (targetPkg != null) { 13432 intent.setPackage(targetPkg); 13433 } 13434 // Modify the UID when posting to other users 13435 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13436 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13437 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13438 intent.putExtra(Intent.EXTRA_UID, uid); 13439 } 13440 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13441 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13442 if (DEBUG_BROADCASTS) { 13443 RuntimeException here = new RuntimeException("here"); 13444 here.fillInStackTrace(); 13445 Slog.d(TAG, "Sending to user " + id + ": " 13446 + intent.toShortString(false, true, false, false) 13447 + " " + intent.getExtras(), here); 13448 } 13449 am.broadcastIntent(null, intent, null, finishedReceiver, 13450 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13451 null, finishedReceiver != null, false, id); 13452 } 13453 } 13454 13455 /** 13456 * Check if the external storage media is available. This is true if there 13457 * is a mounted external storage medium or if the external storage is 13458 * emulated. 13459 */ 13460 private boolean isExternalMediaAvailable() { 13461 return mMediaMounted || Environment.isExternalStorageEmulated(); 13462 } 13463 13464 @Override 13465 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13466 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13467 return null; 13468 } 13469 if (!isExternalMediaAvailable()) { 13470 // If the external storage is no longer mounted at this point, 13471 // the caller may not have been able to delete all of this 13472 // packages files and can not delete any more. Bail. 13473 return null; 13474 } 13475 synchronized (mPackages) { 13476 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13477 if (lastPackage != null) { 13478 pkgs.remove(lastPackage); 13479 } 13480 if (pkgs.size() > 0) { 13481 return pkgs.get(0); 13482 } 13483 } 13484 return null; 13485 } 13486 13487 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13488 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13489 userId, andCode ? 1 : 0, packageName); 13490 if (mSystemReady) { 13491 msg.sendToTarget(); 13492 } else { 13493 if (mPostSystemReadyMessages == null) { 13494 mPostSystemReadyMessages = new ArrayList<>(); 13495 } 13496 mPostSystemReadyMessages.add(msg); 13497 } 13498 } 13499 13500 void startCleaningPackages() { 13501 // reader 13502 if (!isExternalMediaAvailable()) { 13503 return; 13504 } 13505 synchronized (mPackages) { 13506 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13507 return; 13508 } 13509 } 13510 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13511 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13512 IActivityManager am = ActivityManager.getService(); 13513 if (am != null) { 13514 int dcsUid = -1; 13515 synchronized (mPackages) { 13516 if (!mDefaultContainerWhitelisted) { 13517 mDefaultContainerWhitelisted = true; 13518 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13519 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13520 } 13521 } 13522 try { 13523 if (dcsUid > 0) { 13524 am.backgroundWhitelistUid(dcsUid); 13525 } 13526 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13527 UserHandle.USER_SYSTEM); 13528 } catch (RemoteException e) { 13529 } 13530 } 13531 } 13532 13533 /** 13534 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13535 * it is acting on behalf on an enterprise or the user). 13536 * 13537 * Note that the ordering of the conditionals in this method is important. The checks we perform 13538 * are as follows, in this order: 13539 * 13540 * 1) If the install is being performed by a system app, we can trust the app to have set the 13541 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13542 * what it is. 13543 * 2) If the install is being performed by a device or profile owner app, the install reason 13544 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13545 * set the install reason correctly. If the app targets an older SDK version where install 13546 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13547 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13548 * 3) In all other cases, the install is being performed by a regular app that is neither part 13549 * of the system nor a device or profile owner. We have no reason to believe that this app is 13550 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13551 * set to enterprise policy and if so, change it to unknown instead. 13552 */ 13553 private int fixUpInstallReason(String installerPackageName, int installerUid, 13554 int installReason) { 13555 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13556 == PERMISSION_GRANTED) { 13557 // If the install is being performed by a system app, we trust that app to have set the 13558 // install reason correctly. 13559 return installReason; 13560 } 13561 13562 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13563 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13564 if (dpm != null) { 13565 ComponentName owner = null; 13566 try { 13567 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13568 if (owner == null) { 13569 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13570 } 13571 } catch (RemoteException e) { 13572 } 13573 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13574 // If the install is being performed by a device or profile owner, the install 13575 // reason should be enterprise policy. 13576 return PackageManager.INSTALL_REASON_POLICY; 13577 } 13578 } 13579 13580 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13581 // If the install is being performed by a regular app (i.e. neither system app nor 13582 // device or profile owner), we have no reason to believe that the app is acting on 13583 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13584 // change it to unknown instead. 13585 return PackageManager.INSTALL_REASON_UNKNOWN; 13586 } 13587 13588 // If the install is being performed by a regular app and the install reason was set to any 13589 // value but enterprise policy, leave the install reason unchanged. 13590 return installReason; 13591 } 13592 13593 void installStage(String packageName, File stagedDir, 13594 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13595 String installerPackageName, int installerUid, UserHandle user, 13596 PackageParser.SigningDetails signingDetails) { 13597 if (DEBUG_EPHEMERAL) { 13598 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13599 Slog.d(TAG, "Ephemeral install of " + packageName); 13600 } 13601 } 13602 final VerificationInfo verificationInfo = new VerificationInfo( 13603 sessionParams.originatingUri, sessionParams.referrerUri, 13604 sessionParams.originatingUid, installerUid); 13605 13606 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13607 13608 final Message msg = mHandler.obtainMessage(INIT_COPY); 13609 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13610 sessionParams.installReason); 13611 final InstallParams params = new InstallParams(origin, null, observer, 13612 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13613 verificationInfo, user, sessionParams.abiOverride, 13614 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13615 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13616 msg.obj = params; 13617 13618 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13619 System.identityHashCode(msg.obj)); 13620 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13621 System.identityHashCode(msg.obj)); 13622 13623 mHandler.sendMessage(msg); 13624 } 13625 13626 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13627 int userId) { 13628 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13629 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13630 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13631 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13632 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13633 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13634 13635 // Send a session commit broadcast 13636 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13637 info.installReason = pkgSetting.getInstallReason(userId); 13638 info.appPackageName = packageName; 13639 sendSessionCommitBroadcast(info, userId); 13640 } 13641 13642 @Override 13643 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13644 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13645 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13646 return; 13647 } 13648 Bundle extras = new Bundle(1); 13649 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13650 final int uid = UserHandle.getUid( 13651 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13652 extras.putInt(Intent.EXTRA_UID, uid); 13653 13654 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13655 packageName, extras, 0, null, null, userIds, instantUserIds); 13656 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13657 mHandler.post(() -> { 13658 for (int userId : userIds) { 13659 sendBootCompletedBroadcastToSystemApp( 13660 packageName, includeStopped, userId); 13661 } 13662 } 13663 ); 13664 } 13665 } 13666 13667 /** 13668 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13669 * automatically without needing an explicit launch. 13670 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13671 */ 13672 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13673 int userId) { 13674 // If user is not running, the app didn't miss any broadcast 13675 if (!mUserManagerInternal.isUserRunning(userId)) { 13676 return; 13677 } 13678 final IActivityManager am = ActivityManager.getService(); 13679 try { 13680 // Deliver LOCKED_BOOT_COMPLETED first 13681 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13682 .setPackage(packageName); 13683 if (includeStopped) { 13684 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13685 } 13686 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13687 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13688 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13689 13690 // Deliver BOOT_COMPLETED only if user is unlocked 13691 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13692 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13693 if (includeStopped) { 13694 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13695 } 13696 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13697 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13698 } 13699 } catch (RemoteException e) { 13700 throw e.rethrowFromSystemServer(); 13701 } 13702 } 13703 13704 @Override 13705 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13706 int userId) { 13707 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13708 PackageSetting pkgSetting; 13709 final int callingUid = Binder.getCallingUid(); 13710 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13711 true /* requireFullPermission */, true /* checkShell */, 13712 "setApplicationHiddenSetting for user " + userId); 13713 13714 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13715 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13716 return false; 13717 } 13718 13719 long callingId = Binder.clearCallingIdentity(); 13720 try { 13721 boolean sendAdded = false; 13722 boolean sendRemoved = false; 13723 // writer 13724 synchronized (mPackages) { 13725 pkgSetting = mSettings.mPackages.get(packageName); 13726 if (pkgSetting == null) { 13727 return false; 13728 } 13729 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13730 return false; 13731 } 13732 // Do not allow "android" is being disabled 13733 if ("android".equals(packageName)) { 13734 Slog.w(TAG, "Cannot hide package: android"); 13735 return false; 13736 } 13737 // Cannot hide static shared libs as they are considered 13738 // a part of the using app (emulating static linking). Also 13739 // static libs are installed always on internal storage. 13740 PackageParser.Package pkg = mPackages.get(packageName); 13741 if (pkg != null && pkg.staticSharedLibName != null) { 13742 Slog.w(TAG, "Cannot hide package: " + packageName 13743 + " providing static shared library: " 13744 + pkg.staticSharedLibName); 13745 return false; 13746 } 13747 // Only allow protected packages to hide themselves. 13748 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13749 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13750 Slog.w(TAG, "Not hiding protected package: " + packageName); 13751 return false; 13752 } 13753 13754 if (pkgSetting.getHidden(userId) != hidden) { 13755 pkgSetting.setHidden(hidden, userId); 13756 mSettings.writePackageRestrictionsLPr(userId); 13757 if (hidden) { 13758 sendRemoved = true; 13759 } else { 13760 sendAdded = true; 13761 } 13762 } 13763 } 13764 if (sendAdded) { 13765 sendPackageAddedForUser(packageName, pkgSetting, userId); 13766 return true; 13767 } 13768 if (sendRemoved) { 13769 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13770 "hiding pkg"); 13771 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13772 return true; 13773 } 13774 } finally { 13775 Binder.restoreCallingIdentity(callingId); 13776 } 13777 return false; 13778 } 13779 13780 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13781 int userId) { 13782 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13783 info.removedPackage = packageName; 13784 info.installerPackageName = pkgSetting.installerPackageName; 13785 info.removedUsers = new int[] {userId}; 13786 info.broadcastUsers = new int[] {userId}; 13787 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13788 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13789 } 13790 13791 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13792 if (pkgList.length > 0) { 13793 Bundle extras = new Bundle(1); 13794 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13795 13796 sendPackageBroadcast( 13797 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13798 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13799 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13800 new int[] {userId}, null); 13801 } 13802 } 13803 13804 /** 13805 * Returns true if application is not found or there was an error. Otherwise it returns 13806 * the hidden state of the package for the given user. 13807 */ 13808 @Override 13809 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13811 final int callingUid = Binder.getCallingUid(); 13812 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13813 true /* requireFullPermission */, false /* checkShell */, 13814 "getApplicationHidden for user " + userId); 13815 PackageSetting ps; 13816 long callingId = Binder.clearCallingIdentity(); 13817 try { 13818 // writer 13819 synchronized (mPackages) { 13820 ps = mSettings.mPackages.get(packageName); 13821 if (ps == null) { 13822 return true; 13823 } 13824 if (filterAppAccessLPr(ps, callingUid, userId)) { 13825 return true; 13826 } 13827 return ps.getHidden(userId); 13828 } 13829 } finally { 13830 Binder.restoreCallingIdentity(callingId); 13831 } 13832 } 13833 13834 /** 13835 * @hide 13836 */ 13837 @Override 13838 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13839 int installReason) { 13840 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13841 null); 13842 PackageSetting pkgSetting; 13843 final int callingUid = Binder.getCallingUid(); 13844 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13845 true /* requireFullPermission */, true /* checkShell */, 13846 "installExistingPackage for user " + userId); 13847 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13848 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13849 } 13850 13851 long callingId = Binder.clearCallingIdentity(); 13852 try { 13853 boolean installed = false; 13854 final boolean instantApp = 13855 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13856 final boolean fullApp = 13857 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13858 13859 // writer 13860 synchronized (mPackages) { 13861 pkgSetting = mSettings.mPackages.get(packageName); 13862 if (pkgSetting == null) { 13863 return PackageManager.INSTALL_FAILED_INVALID_URI; 13864 } 13865 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13866 // only allow the existing package to be used if it's installed as a full 13867 // application for at least one user 13868 boolean installAllowed = false; 13869 for (int checkUserId : sUserManager.getUserIds()) { 13870 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13871 if (installAllowed) { 13872 break; 13873 } 13874 } 13875 if (!installAllowed) { 13876 return PackageManager.INSTALL_FAILED_INVALID_URI; 13877 } 13878 } 13879 if (!pkgSetting.getInstalled(userId)) { 13880 pkgSetting.setInstalled(true, userId); 13881 pkgSetting.setHidden(false, userId); 13882 pkgSetting.setInstallReason(installReason, userId); 13883 mSettings.writePackageRestrictionsLPr(userId); 13884 mSettings.writeKernelMappingLPr(pkgSetting); 13885 installed = true; 13886 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13887 // upgrade app from instant to full; we don't allow app downgrade 13888 installed = true; 13889 } 13890 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13891 } 13892 13893 if (installed) { 13894 if (pkgSetting.pkg != null) { 13895 synchronized (mInstallLock) { 13896 // We don't need to freeze for a brand new install 13897 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13898 } 13899 } 13900 sendPackageAddedForUser(packageName, pkgSetting, userId); 13901 synchronized (mPackages) { 13902 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13903 } 13904 } 13905 } finally { 13906 Binder.restoreCallingIdentity(callingId); 13907 } 13908 13909 return PackageManager.INSTALL_SUCCEEDED; 13910 } 13911 13912 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13913 boolean instantApp, boolean fullApp) { 13914 // no state specified; do nothing 13915 if (!instantApp && !fullApp) { 13916 return; 13917 } 13918 if (userId != UserHandle.USER_ALL) { 13919 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13920 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13921 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13922 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13923 } 13924 } else { 13925 for (int currentUserId : sUserManager.getUserIds()) { 13926 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13927 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13928 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13929 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13930 } 13931 } 13932 } 13933 } 13934 13935 boolean isUserRestricted(int userId, String restrictionKey) { 13936 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13937 if (restrictions.getBoolean(restrictionKey, false)) { 13938 Log.w(TAG, "User is restricted: " + restrictionKey); 13939 return true; 13940 } 13941 return false; 13942 } 13943 13944 @Override 13945 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13946 int userId) { 13947 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13948 final int callingUid = Binder.getCallingUid(); 13949 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13950 true /* requireFullPermission */, true /* checkShell */, 13951 "setPackagesSuspended for user " + userId); 13952 13953 if (ArrayUtils.isEmpty(packageNames)) { 13954 return packageNames; 13955 } 13956 13957 // List of package names for whom the suspended state has changed. 13958 List<String> changedPackages = new ArrayList<>(packageNames.length); 13959 // List of package names for whom the suspended state is not set as requested in this 13960 // method. 13961 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13962 long callingId = Binder.clearCallingIdentity(); 13963 try { 13964 for (int i = 0; i < packageNames.length; i++) { 13965 String packageName = packageNames[i]; 13966 boolean changed = false; 13967 final int appId; 13968 synchronized (mPackages) { 13969 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13970 if (pkgSetting == null 13971 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13972 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13973 + "\". Skipping suspending/un-suspending."); 13974 unactionedPackages.add(packageName); 13975 continue; 13976 } 13977 appId = pkgSetting.appId; 13978 if (pkgSetting.getSuspended(userId) != suspended) { 13979 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13980 unactionedPackages.add(packageName); 13981 continue; 13982 } 13983 pkgSetting.setSuspended(suspended, userId); 13984 mSettings.writePackageRestrictionsLPr(userId); 13985 changed = true; 13986 changedPackages.add(packageName); 13987 } 13988 } 13989 13990 if (changed && suspended) { 13991 killApplication(packageName, UserHandle.getUid(userId, appId), 13992 "suspending package"); 13993 } 13994 } 13995 } finally { 13996 Binder.restoreCallingIdentity(callingId); 13997 } 13998 13999 if (!changedPackages.isEmpty()) { 14000 sendPackagesSuspendedForUser(changedPackages.toArray( 14001 new String[changedPackages.size()]), userId, suspended); 14002 } 14003 14004 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14005 } 14006 14007 @Override 14008 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14009 final int callingUid = Binder.getCallingUid(); 14010 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14011 true /* requireFullPermission */, false /* checkShell */, 14012 "isPackageSuspendedForUser for user " + userId); 14013 synchronized (mPackages) { 14014 final PackageSetting ps = mSettings.mPackages.get(packageName); 14015 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14016 throw new IllegalArgumentException("Unknown target package: " + packageName); 14017 } 14018 return ps.getSuspended(userId); 14019 } 14020 } 14021 14022 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14023 if (isPackageDeviceAdmin(packageName, userId)) { 14024 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14025 + "\": has an active device admin"); 14026 return false; 14027 } 14028 14029 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14030 if (packageName.equals(activeLauncherPackageName)) { 14031 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14032 + "\": contains the active launcher"); 14033 return false; 14034 } 14035 14036 if (packageName.equals(mRequiredInstallerPackage)) { 14037 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14038 + "\": required for package installation"); 14039 return false; 14040 } 14041 14042 if (packageName.equals(mRequiredUninstallerPackage)) { 14043 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14044 + "\": required for package uninstallation"); 14045 return false; 14046 } 14047 14048 if (packageName.equals(mRequiredVerifierPackage)) { 14049 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14050 + "\": required for package verification"); 14051 return false; 14052 } 14053 14054 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14055 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14056 + "\": is the default dialer"); 14057 return false; 14058 } 14059 14060 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14061 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14062 + "\": protected package"); 14063 return false; 14064 } 14065 14066 // Cannot suspend static shared libs as they are considered 14067 // a part of the using app (emulating static linking). Also 14068 // static libs are installed always on internal storage. 14069 PackageParser.Package pkg = mPackages.get(packageName); 14070 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14071 Slog.w(TAG, "Cannot suspend package: " + packageName 14072 + " providing static shared library: " 14073 + pkg.staticSharedLibName); 14074 return false; 14075 } 14076 14077 return true; 14078 } 14079 14080 private String getActiveLauncherPackageName(int userId) { 14081 Intent intent = new Intent(Intent.ACTION_MAIN); 14082 intent.addCategory(Intent.CATEGORY_HOME); 14083 ResolveInfo resolveInfo = resolveIntent( 14084 intent, 14085 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14086 PackageManager.MATCH_DEFAULT_ONLY, 14087 userId); 14088 14089 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14090 } 14091 14092 private String getDefaultDialerPackageName(int userId) { 14093 synchronized (mPackages) { 14094 return mSettings.getDefaultDialerPackageNameLPw(userId); 14095 } 14096 } 14097 14098 @Override 14099 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14100 mContext.enforceCallingOrSelfPermission( 14101 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14102 "Only package verification agents can verify applications"); 14103 14104 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14105 final PackageVerificationResponse response = new PackageVerificationResponse( 14106 verificationCode, Binder.getCallingUid()); 14107 msg.arg1 = id; 14108 msg.obj = response; 14109 mHandler.sendMessage(msg); 14110 } 14111 14112 @Override 14113 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14114 long millisecondsToDelay) { 14115 mContext.enforceCallingOrSelfPermission( 14116 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14117 "Only package verification agents can extend verification timeouts"); 14118 14119 final PackageVerificationState state = mPendingVerification.get(id); 14120 final PackageVerificationResponse response = new PackageVerificationResponse( 14121 verificationCodeAtTimeout, Binder.getCallingUid()); 14122 14123 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14124 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14125 } 14126 if (millisecondsToDelay < 0) { 14127 millisecondsToDelay = 0; 14128 } 14129 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14130 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14131 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14132 } 14133 14134 if ((state != null) && !state.timeoutExtended()) { 14135 state.extendTimeout(); 14136 14137 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14138 msg.arg1 = id; 14139 msg.obj = response; 14140 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14141 } 14142 } 14143 14144 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14145 int verificationCode, UserHandle user) { 14146 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14147 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14148 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14149 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14150 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14151 14152 mContext.sendBroadcastAsUser(intent, user, 14153 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14154 } 14155 14156 private ComponentName matchComponentForVerifier(String packageName, 14157 List<ResolveInfo> receivers) { 14158 ActivityInfo targetReceiver = null; 14159 14160 final int NR = receivers.size(); 14161 for (int i = 0; i < NR; i++) { 14162 final ResolveInfo info = receivers.get(i); 14163 if (info.activityInfo == null) { 14164 continue; 14165 } 14166 14167 if (packageName.equals(info.activityInfo.packageName)) { 14168 targetReceiver = info.activityInfo; 14169 break; 14170 } 14171 } 14172 14173 if (targetReceiver == null) { 14174 return null; 14175 } 14176 14177 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14178 } 14179 14180 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14181 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14182 if (pkgInfo.verifiers.length == 0) { 14183 return null; 14184 } 14185 14186 final int N = pkgInfo.verifiers.length; 14187 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14188 for (int i = 0; i < N; i++) { 14189 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14190 14191 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14192 receivers); 14193 if (comp == null) { 14194 continue; 14195 } 14196 14197 final int verifierUid = getUidForVerifier(verifierInfo); 14198 if (verifierUid == -1) { 14199 continue; 14200 } 14201 14202 if (DEBUG_VERIFY) { 14203 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14204 + " with the correct signature"); 14205 } 14206 sufficientVerifiers.add(comp); 14207 verificationState.addSufficientVerifier(verifierUid); 14208 } 14209 14210 return sufficientVerifiers; 14211 } 14212 14213 private int getUidForVerifier(VerifierInfo verifierInfo) { 14214 synchronized (mPackages) { 14215 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14216 if (pkg == null) { 14217 return -1; 14218 } else if (pkg.mSigningDetails.signatures.length != 1) { 14219 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14220 + " has more than one signature; ignoring"); 14221 return -1; 14222 } 14223 14224 /* 14225 * If the public key of the package's signature does not match 14226 * our expected public key, then this is a different package and 14227 * we should skip. 14228 */ 14229 14230 final byte[] expectedPublicKey; 14231 try { 14232 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14233 final PublicKey publicKey = verifierSig.getPublicKey(); 14234 expectedPublicKey = publicKey.getEncoded(); 14235 } catch (CertificateException e) { 14236 return -1; 14237 } 14238 14239 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14240 14241 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14242 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14243 + " does not have the expected public key; ignoring"); 14244 return -1; 14245 } 14246 14247 return pkg.applicationInfo.uid; 14248 } 14249 } 14250 14251 @Override 14252 public void finishPackageInstall(int token, boolean didLaunch) { 14253 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14254 14255 if (DEBUG_INSTALL) { 14256 Slog.v(TAG, "BM finishing package install for " + token); 14257 } 14258 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14259 14260 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14261 mHandler.sendMessage(msg); 14262 } 14263 14264 /** 14265 * Get the verification agent timeout. Used for both the APK verifier and the 14266 * intent filter verifier. 14267 * 14268 * @return verification timeout in milliseconds 14269 */ 14270 private long getVerificationTimeout() { 14271 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14272 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14273 DEFAULT_VERIFICATION_TIMEOUT); 14274 } 14275 14276 /** 14277 * Get the default verification agent response code. 14278 * 14279 * @return default verification response code 14280 */ 14281 private int getDefaultVerificationResponse(UserHandle user) { 14282 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14283 return PackageManager.VERIFICATION_REJECT; 14284 } 14285 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14286 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14287 DEFAULT_VERIFICATION_RESPONSE); 14288 } 14289 14290 /** 14291 * Check whether or not package verification has been enabled. 14292 * 14293 * @return true if verification should be performed 14294 */ 14295 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14296 if (!DEFAULT_VERIFY_ENABLE) { 14297 return false; 14298 } 14299 14300 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14301 14302 // Check if installing from ADB 14303 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14304 // Do not run verification in a test harness environment 14305 if (ActivityManager.isRunningInTestHarness()) { 14306 return false; 14307 } 14308 if (ensureVerifyAppsEnabled) { 14309 return true; 14310 } 14311 // Check if the developer does not want package verification for ADB installs 14312 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14313 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14314 return false; 14315 } 14316 } else { 14317 // only when not installed from ADB, skip verification for instant apps when 14318 // the installer and verifier are the same. 14319 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14320 if (mInstantAppInstallerActivity != null 14321 && mInstantAppInstallerActivity.packageName.equals( 14322 mRequiredVerifierPackage)) { 14323 try { 14324 mContext.getSystemService(AppOpsManager.class) 14325 .checkPackage(installerUid, mRequiredVerifierPackage); 14326 if (DEBUG_VERIFY) { 14327 Slog.i(TAG, "disable verification for instant app"); 14328 } 14329 return false; 14330 } catch (SecurityException ignore) { } 14331 } 14332 } 14333 } 14334 14335 if (ensureVerifyAppsEnabled) { 14336 return true; 14337 } 14338 14339 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14340 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14341 } 14342 14343 @Override 14344 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14345 throws RemoteException { 14346 mContext.enforceCallingOrSelfPermission( 14347 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14348 "Only intentfilter verification agents can verify applications"); 14349 14350 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14351 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14352 Binder.getCallingUid(), verificationCode, failedDomains); 14353 msg.arg1 = id; 14354 msg.obj = response; 14355 mHandler.sendMessage(msg); 14356 } 14357 14358 @Override 14359 public int getIntentVerificationStatus(String packageName, int userId) { 14360 final int callingUid = Binder.getCallingUid(); 14361 if (UserHandle.getUserId(callingUid) != userId) { 14362 mContext.enforceCallingOrSelfPermission( 14363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14364 "getIntentVerificationStatus" + userId); 14365 } 14366 if (getInstantAppPackageName(callingUid) != null) { 14367 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14368 } 14369 synchronized (mPackages) { 14370 final PackageSetting ps = mSettings.mPackages.get(packageName); 14371 if (ps == null 14372 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14373 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14374 } 14375 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14376 } 14377 } 14378 14379 @Override 14380 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14381 mContext.enforceCallingOrSelfPermission( 14382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14383 14384 boolean result = false; 14385 synchronized (mPackages) { 14386 final PackageSetting ps = mSettings.mPackages.get(packageName); 14387 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14388 return false; 14389 } 14390 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14391 } 14392 if (result) { 14393 scheduleWritePackageRestrictionsLocked(userId); 14394 } 14395 return result; 14396 } 14397 14398 @Override 14399 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14400 String packageName) { 14401 final int callingUid = Binder.getCallingUid(); 14402 if (getInstantAppPackageName(callingUid) != null) { 14403 return ParceledListSlice.emptyList(); 14404 } 14405 synchronized (mPackages) { 14406 final PackageSetting ps = mSettings.mPackages.get(packageName); 14407 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14408 return ParceledListSlice.emptyList(); 14409 } 14410 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14411 } 14412 } 14413 14414 @Override 14415 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14416 if (TextUtils.isEmpty(packageName)) { 14417 return ParceledListSlice.emptyList(); 14418 } 14419 final int callingUid = Binder.getCallingUid(); 14420 final int callingUserId = UserHandle.getUserId(callingUid); 14421 synchronized (mPackages) { 14422 PackageParser.Package pkg = mPackages.get(packageName); 14423 if (pkg == null || pkg.activities == null) { 14424 return ParceledListSlice.emptyList(); 14425 } 14426 if (pkg.mExtras == null) { 14427 return ParceledListSlice.emptyList(); 14428 } 14429 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14430 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14431 return ParceledListSlice.emptyList(); 14432 } 14433 final int count = pkg.activities.size(); 14434 ArrayList<IntentFilter> result = new ArrayList<>(); 14435 for (int n=0; n<count; n++) { 14436 PackageParser.Activity activity = pkg.activities.get(n); 14437 if (activity.intents != null && activity.intents.size() > 0) { 14438 result.addAll(activity.intents); 14439 } 14440 } 14441 return new ParceledListSlice<>(result); 14442 } 14443 } 14444 14445 @Override 14446 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14447 mContext.enforceCallingOrSelfPermission( 14448 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14449 if (UserHandle.getCallingUserId() != userId) { 14450 mContext.enforceCallingOrSelfPermission( 14451 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14452 } 14453 14454 synchronized (mPackages) { 14455 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14456 if (packageName != null) { 14457 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14458 packageName, userId); 14459 } 14460 return result; 14461 } 14462 } 14463 14464 @Override 14465 public String getDefaultBrowserPackageName(int userId) { 14466 if (UserHandle.getCallingUserId() != userId) { 14467 mContext.enforceCallingOrSelfPermission( 14468 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14469 } 14470 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14471 return null; 14472 } 14473 synchronized (mPackages) { 14474 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14475 } 14476 } 14477 14478 /** 14479 * Get the "allow unknown sources" setting. 14480 * 14481 * @return the current "allow unknown sources" setting 14482 */ 14483 private int getUnknownSourcesSettings() { 14484 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14485 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14486 -1); 14487 } 14488 14489 @Override 14490 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14491 final int callingUid = Binder.getCallingUid(); 14492 if (getInstantAppPackageName(callingUid) != null) { 14493 return; 14494 } 14495 // writer 14496 synchronized (mPackages) { 14497 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14498 if (targetPackageSetting == null 14499 || filterAppAccessLPr( 14500 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14501 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14502 } 14503 14504 PackageSetting installerPackageSetting; 14505 if (installerPackageName != null) { 14506 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14507 if (installerPackageSetting == null) { 14508 throw new IllegalArgumentException("Unknown installer package: " 14509 + installerPackageName); 14510 } 14511 } else { 14512 installerPackageSetting = null; 14513 } 14514 14515 Signature[] callerSignature; 14516 Object obj = mSettings.getUserIdLPr(callingUid); 14517 if (obj != null) { 14518 if (obj instanceof SharedUserSetting) { 14519 callerSignature = 14520 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14521 } else if (obj instanceof PackageSetting) { 14522 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14523 } else { 14524 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14525 } 14526 } else { 14527 throw new SecurityException("Unknown calling UID: " + callingUid); 14528 } 14529 14530 // Verify: can't set installerPackageName to a package that is 14531 // not signed with the same cert as the caller. 14532 if (installerPackageSetting != null) { 14533 if (compareSignatures(callerSignature, 14534 installerPackageSetting.signatures.mSigningDetails.signatures) 14535 != PackageManager.SIGNATURE_MATCH) { 14536 throw new SecurityException( 14537 "Caller does not have same cert as new installer package " 14538 + installerPackageName); 14539 } 14540 } 14541 14542 // Verify: if target already has an installer package, it must 14543 // be signed with the same cert as the caller. 14544 if (targetPackageSetting.installerPackageName != null) { 14545 PackageSetting setting = mSettings.mPackages.get( 14546 targetPackageSetting.installerPackageName); 14547 // If the currently set package isn't valid, then it's always 14548 // okay to change it. 14549 if (setting != null) { 14550 if (compareSignatures(callerSignature, 14551 setting.signatures.mSigningDetails.signatures) 14552 != PackageManager.SIGNATURE_MATCH) { 14553 throw new SecurityException( 14554 "Caller does not have same cert as old installer package " 14555 + targetPackageSetting.installerPackageName); 14556 } 14557 } 14558 } 14559 14560 // Okay! 14561 targetPackageSetting.installerPackageName = installerPackageName; 14562 if (installerPackageName != null) { 14563 mSettings.mInstallerPackages.add(installerPackageName); 14564 } 14565 scheduleWriteSettingsLocked(); 14566 } 14567 } 14568 14569 @Override 14570 public void setApplicationCategoryHint(String packageName, int categoryHint, 14571 String callerPackageName) { 14572 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14573 throw new SecurityException("Instant applications don't have access to this method"); 14574 } 14575 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14576 callerPackageName); 14577 synchronized (mPackages) { 14578 PackageSetting ps = mSettings.mPackages.get(packageName); 14579 if (ps == null) { 14580 throw new IllegalArgumentException("Unknown target package " + packageName); 14581 } 14582 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14583 throw new IllegalArgumentException("Unknown target package " + packageName); 14584 } 14585 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14586 throw new IllegalArgumentException("Calling package " + callerPackageName 14587 + " is not installer for " + packageName); 14588 } 14589 14590 if (ps.categoryHint != categoryHint) { 14591 ps.categoryHint = categoryHint; 14592 scheduleWriteSettingsLocked(); 14593 } 14594 } 14595 } 14596 14597 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14598 // Queue up an async operation since the package installation may take a little while. 14599 mHandler.post(new Runnable() { 14600 public void run() { 14601 mHandler.removeCallbacks(this); 14602 // Result object to be returned 14603 PackageInstalledInfo res = new PackageInstalledInfo(); 14604 res.setReturnCode(currentStatus); 14605 res.uid = -1; 14606 res.pkg = null; 14607 res.removedInfo = null; 14608 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14609 args.doPreInstall(res.returnCode); 14610 synchronized (mInstallLock) { 14611 installPackageTracedLI(args, res); 14612 } 14613 args.doPostInstall(res.returnCode, res.uid); 14614 } 14615 14616 // A restore should be performed at this point if (a) the install 14617 // succeeded, (b) the operation is not an update, and (c) the new 14618 // package has not opted out of backup participation. 14619 final boolean update = res.removedInfo != null 14620 && res.removedInfo.removedPackage != null; 14621 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14622 boolean doRestore = !update 14623 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14624 14625 // Set up the post-install work request bookkeeping. This will be used 14626 // and cleaned up by the post-install event handling regardless of whether 14627 // there's a restore pass performed. Token values are >= 1. 14628 int token; 14629 if (mNextInstallToken < 0) mNextInstallToken = 1; 14630 token = mNextInstallToken++; 14631 14632 PostInstallData data = new PostInstallData(args, res); 14633 mRunningInstalls.put(token, data); 14634 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14635 14636 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14637 // Pass responsibility to the Backup Manager. It will perform a 14638 // restore if appropriate, then pass responsibility back to the 14639 // Package Manager to run the post-install observer callbacks 14640 // and broadcasts. 14641 IBackupManager bm = IBackupManager.Stub.asInterface( 14642 ServiceManager.getService(Context.BACKUP_SERVICE)); 14643 if (bm != null) { 14644 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14645 + " to BM for possible restore"); 14646 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14647 try { 14648 // TODO: http://b/22388012 14649 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14650 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14651 } else { 14652 doRestore = false; 14653 } 14654 } catch (RemoteException e) { 14655 // can't happen; the backup manager is local 14656 } catch (Exception e) { 14657 Slog.e(TAG, "Exception trying to enqueue restore", e); 14658 doRestore = false; 14659 } 14660 } else { 14661 Slog.e(TAG, "Backup Manager not found!"); 14662 doRestore = false; 14663 } 14664 } 14665 14666 if (!doRestore) { 14667 // No restore possible, or the Backup Manager was mysteriously not 14668 // available -- just fire the post-install work request directly. 14669 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14670 14671 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14672 14673 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14674 mHandler.sendMessage(msg); 14675 } 14676 } 14677 }); 14678 } 14679 14680 /** 14681 * Callback from PackageSettings whenever an app is first transitioned out of the 14682 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14683 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14684 * here whether the app is the target of an ongoing install, and only send the 14685 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14686 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14687 * handling. 14688 */ 14689 void notifyFirstLaunch(final String packageName, final String installerPackage, 14690 final int userId) { 14691 // Serialize this with the rest of the install-process message chain. In the 14692 // restore-at-install case, this Runnable will necessarily run before the 14693 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14694 // are coherent. In the non-restore case, the app has already completed install 14695 // and been launched through some other means, so it is not in a problematic 14696 // state for observers to see the FIRST_LAUNCH signal. 14697 mHandler.post(new Runnable() { 14698 @Override 14699 public void run() { 14700 for (int i = 0; i < mRunningInstalls.size(); i++) { 14701 final PostInstallData data = mRunningInstalls.valueAt(i); 14702 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14703 continue; 14704 } 14705 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14706 // right package; but is it for the right user? 14707 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14708 if (userId == data.res.newUsers[uIndex]) { 14709 if (DEBUG_BACKUP) { 14710 Slog.i(TAG, "Package " + packageName 14711 + " being restored so deferring FIRST_LAUNCH"); 14712 } 14713 return; 14714 } 14715 } 14716 } 14717 } 14718 // didn't find it, so not being restored 14719 if (DEBUG_BACKUP) { 14720 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14721 } 14722 final boolean isInstantApp = isInstantApp(packageName, userId); 14723 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14724 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14725 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14726 } 14727 }); 14728 } 14729 14730 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14731 int[] userIds, int[] instantUserIds) { 14732 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14733 installerPkg, null, userIds, instantUserIds); 14734 } 14735 14736 private abstract class HandlerParams { 14737 private static final int MAX_RETRIES = 4; 14738 14739 /** 14740 * Number of times startCopy() has been attempted and had a non-fatal 14741 * error. 14742 */ 14743 private int mRetries = 0; 14744 14745 /** User handle for the user requesting the information or installation. */ 14746 private final UserHandle mUser; 14747 String traceMethod; 14748 int traceCookie; 14749 14750 HandlerParams(UserHandle user) { 14751 mUser = user; 14752 } 14753 14754 UserHandle getUser() { 14755 return mUser; 14756 } 14757 14758 HandlerParams setTraceMethod(String traceMethod) { 14759 this.traceMethod = traceMethod; 14760 return this; 14761 } 14762 14763 HandlerParams setTraceCookie(int traceCookie) { 14764 this.traceCookie = traceCookie; 14765 return this; 14766 } 14767 14768 final boolean startCopy() { 14769 boolean res; 14770 try { 14771 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14772 14773 if (++mRetries > MAX_RETRIES) { 14774 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14775 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14776 handleServiceError(); 14777 return false; 14778 } else { 14779 handleStartCopy(); 14780 res = true; 14781 } 14782 } catch (RemoteException e) { 14783 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14784 mHandler.sendEmptyMessage(MCS_RECONNECT); 14785 res = false; 14786 } 14787 handleReturnCode(); 14788 return res; 14789 } 14790 14791 final void serviceError() { 14792 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14793 handleServiceError(); 14794 handleReturnCode(); 14795 } 14796 14797 abstract void handleStartCopy() throws RemoteException; 14798 abstract void handleServiceError(); 14799 abstract void handleReturnCode(); 14800 } 14801 14802 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14803 for (File path : paths) { 14804 try { 14805 mcs.clearDirectory(path.getAbsolutePath()); 14806 } catch (RemoteException e) { 14807 } 14808 } 14809 } 14810 14811 static class OriginInfo { 14812 /** 14813 * Location where install is coming from, before it has been 14814 * copied/renamed into place. This could be a single monolithic APK 14815 * file, or a cluster directory. This location may be untrusted. 14816 */ 14817 final File file; 14818 14819 /** 14820 * Flag indicating that {@link #file} or {@link #cid} has already been 14821 * staged, meaning downstream users don't need to defensively copy the 14822 * contents. 14823 */ 14824 final boolean staged; 14825 14826 /** 14827 * Flag indicating that {@link #file} or {@link #cid} is an already 14828 * installed app that is being moved. 14829 */ 14830 final boolean existing; 14831 14832 final String resolvedPath; 14833 final File resolvedFile; 14834 14835 static OriginInfo fromNothing() { 14836 return new OriginInfo(null, false, false); 14837 } 14838 14839 static OriginInfo fromUntrustedFile(File file) { 14840 return new OriginInfo(file, false, false); 14841 } 14842 14843 static OriginInfo fromExistingFile(File file) { 14844 return new OriginInfo(file, false, true); 14845 } 14846 14847 static OriginInfo fromStagedFile(File file) { 14848 return new OriginInfo(file, true, false); 14849 } 14850 14851 private OriginInfo(File file, boolean staged, boolean existing) { 14852 this.file = file; 14853 this.staged = staged; 14854 this.existing = existing; 14855 14856 if (file != null) { 14857 resolvedPath = file.getAbsolutePath(); 14858 resolvedFile = file; 14859 } else { 14860 resolvedPath = null; 14861 resolvedFile = null; 14862 } 14863 } 14864 } 14865 14866 static class MoveInfo { 14867 final int moveId; 14868 final String fromUuid; 14869 final String toUuid; 14870 final String packageName; 14871 final String dataAppName; 14872 final int appId; 14873 final String seinfo; 14874 final int targetSdkVersion; 14875 14876 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14877 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14878 this.moveId = moveId; 14879 this.fromUuid = fromUuid; 14880 this.toUuid = toUuid; 14881 this.packageName = packageName; 14882 this.dataAppName = dataAppName; 14883 this.appId = appId; 14884 this.seinfo = seinfo; 14885 this.targetSdkVersion = targetSdkVersion; 14886 } 14887 } 14888 14889 static class VerificationInfo { 14890 /** A constant used to indicate that a uid value is not present. */ 14891 public static final int NO_UID = -1; 14892 14893 /** URI referencing where the package was downloaded from. */ 14894 final Uri originatingUri; 14895 14896 /** HTTP referrer URI associated with the originatingURI. */ 14897 final Uri referrer; 14898 14899 /** UID of the application that the install request originated from. */ 14900 final int originatingUid; 14901 14902 /** UID of application requesting the install */ 14903 final int installerUid; 14904 14905 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14906 this.originatingUri = originatingUri; 14907 this.referrer = referrer; 14908 this.originatingUid = originatingUid; 14909 this.installerUid = installerUid; 14910 } 14911 } 14912 14913 class InstallParams extends HandlerParams { 14914 final OriginInfo origin; 14915 final MoveInfo move; 14916 final IPackageInstallObserver2 observer; 14917 int installFlags; 14918 final String installerPackageName; 14919 final String volumeUuid; 14920 private InstallArgs mArgs; 14921 private int mRet; 14922 final String packageAbiOverride; 14923 final String[] grantedRuntimePermissions; 14924 final VerificationInfo verificationInfo; 14925 final PackageParser.SigningDetails signingDetails; 14926 final int installReason; 14927 14928 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14929 int installFlags, String installerPackageName, String volumeUuid, 14930 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14931 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14932 super(user); 14933 this.origin = origin; 14934 this.move = move; 14935 this.observer = observer; 14936 this.installFlags = installFlags; 14937 this.installerPackageName = installerPackageName; 14938 this.volumeUuid = volumeUuid; 14939 this.verificationInfo = verificationInfo; 14940 this.packageAbiOverride = packageAbiOverride; 14941 this.grantedRuntimePermissions = grantedPermissions; 14942 this.signingDetails = signingDetails; 14943 this.installReason = installReason; 14944 } 14945 14946 @Override 14947 public String toString() { 14948 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14949 + " file=" + origin.file + "}"; 14950 } 14951 14952 private int installLocationPolicy(PackageInfoLite pkgLite) { 14953 String packageName = pkgLite.packageName; 14954 int installLocation = pkgLite.installLocation; 14955 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14956 // reader 14957 synchronized (mPackages) { 14958 // Currently installed package which the new package is attempting to replace or 14959 // null if no such package is installed. 14960 PackageParser.Package installedPkg = mPackages.get(packageName); 14961 // Package which currently owns the data which the new package will own if installed. 14962 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14963 // will be null whereas dataOwnerPkg will contain information about the package 14964 // which was uninstalled while keeping its data. 14965 PackageParser.Package dataOwnerPkg = installedPkg; 14966 if (dataOwnerPkg == null) { 14967 PackageSetting ps = mSettings.mPackages.get(packageName); 14968 if (ps != null) { 14969 dataOwnerPkg = ps.pkg; 14970 } 14971 } 14972 14973 if (dataOwnerPkg != null) { 14974 // If installed, the package will get access to data left on the device by its 14975 // predecessor. As a security measure, this is permited only if this is not a 14976 // version downgrade or if the predecessor package is marked as debuggable and 14977 // a downgrade is explicitly requested. 14978 // 14979 // On debuggable platform builds, downgrades are permitted even for 14980 // non-debuggable packages to make testing easier. Debuggable platform builds do 14981 // not offer security guarantees and thus it's OK to disable some security 14982 // mechanisms to make debugging/testing easier on those builds. However, even on 14983 // debuggable builds downgrades of packages are permitted only if requested via 14984 // installFlags. This is because we aim to keep the behavior of debuggable 14985 // platform builds as close as possible to the behavior of non-debuggable 14986 // platform builds. 14987 final boolean downgradeRequested = 14988 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14989 final boolean packageDebuggable = 14990 (dataOwnerPkg.applicationInfo.flags 14991 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14992 final boolean downgradePermitted = 14993 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14994 if (!downgradePermitted) { 14995 try { 14996 checkDowngrade(dataOwnerPkg, pkgLite); 14997 } catch (PackageManagerException e) { 14998 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14999 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15000 } 15001 } 15002 } 15003 15004 if (installedPkg != null) { 15005 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15006 // Check for updated system application. 15007 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15008 if (onSd) { 15009 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15010 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15011 } 15012 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15013 } else { 15014 if (onSd) { 15015 // Install flag overrides everything. 15016 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15017 } 15018 // If current upgrade specifies particular preference 15019 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15020 // Application explicitly specified internal. 15021 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15022 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15023 // App explictly prefers external. Let policy decide 15024 } else { 15025 // Prefer previous location 15026 if (isExternal(installedPkg)) { 15027 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15028 } 15029 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15030 } 15031 } 15032 } else { 15033 // Invalid install. Return error code 15034 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15035 } 15036 } 15037 } 15038 // All the special cases have been taken care of. 15039 // Return result based on recommended install location. 15040 if (onSd) { 15041 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15042 } 15043 return pkgLite.recommendedInstallLocation; 15044 } 15045 15046 /* 15047 * Invoke remote method to get package information and install 15048 * location values. Override install location based on default 15049 * policy if needed and then create install arguments based 15050 * on the install location. 15051 */ 15052 public void handleStartCopy() throws RemoteException { 15053 int ret = PackageManager.INSTALL_SUCCEEDED; 15054 15055 // If we're already staged, we've firmly committed to an install location 15056 if (origin.staged) { 15057 if (origin.file != null) { 15058 installFlags |= PackageManager.INSTALL_INTERNAL; 15059 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15060 } else { 15061 throw new IllegalStateException("Invalid stage location"); 15062 } 15063 } 15064 15065 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15066 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15067 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15068 PackageInfoLite pkgLite = null; 15069 15070 if (onInt && onSd) { 15071 // Check if both bits are set. 15072 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15073 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15074 } else if (onSd && ephemeral) { 15075 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15076 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15077 } else { 15078 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15079 packageAbiOverride); 15080 15081 if (DEBUG_EPHEMERAL && ephemeral) { 15082 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15083 } 15084 15085 /* 15086 * If we have too little free space, try to free cache 15087 * before giving up. 15088 */ 15089 if (!origin.staged && pkgLite.recommendedInstallLocation 15090 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15091 // TODO: focus freeing disk space on the target device 15092 final StorageManager storage = StorageManager.from(mContext); 15093 final long lowThreshold = storage.getStorageLowBytes( 15094 Environment.getDataDirectory()); 15095 15096 final long sizeBytes = mContainerService.calculateInstalledSize( 15097 origin.resolvedPath, packageAbiOverride); 15098 15099 try { 15100 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15101 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15102 installFlags, packageAbiOverride); 15103 } catch (InstallerException e) { 15104 Slog.w(TAG, "Failed to free cache", e); 15105 } 15106 15107 /* 15108 * The cache free must have deleted the file we 15109 * downloaded to install. 15110 * 15111 * TODO: fix the "freeCache" call to not delete 15112 * the file we care about. 15113 */ 15114 if (pkgLite.recommendedInstallLocation 15115 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15116 pkgLite.recommendedInstallLocation 15117 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15118 } 15119 } 15120 } 15121 15122 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15123 int loc = pkgLite.recommendedInstallLocation; 15124 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15125 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15126 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15127 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15128 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15129 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15130 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15131 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15132 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15133 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15134 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15135 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15136 } else { 15137 // Override with defaults if needed. 15138 loc = installLocationPolicy(pkgLite); 15139 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15140 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15141 } else if (!onSd && !onInt) { 15142 // Override install location with flags 15143 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15144 // Set the flag to install on external media. 15145 installFlags |= PackageManager.INSTALL_EXTERNAL; 15146 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15147 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15148 if (DEBUG_EPHEMERAL) { 15149 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15150 } 15151 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15152 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15153 |PackageManager.INSTALL_INTERNAL); 15154 } else { 15155 // Make sure the flag for installing on external 15156 // media is unset 15157 installFlags |= PackageManager.INSTALL_INTERNAL; 15158 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15159 } 15160 } 15161 } 15162 } 15163 15164 final InstallArgs args = createInstallArgs(this); 15165 mArgs = args; 15166 15167 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15168 // TODO: http://b/22976637 15169 // Apps installed for "all" users use the device owner to verify the app 15170 UserHandle verifierUser = getUser(); 15171 if (verifierUser == UserHandle.ALL) { 15172 verifierUser = UserHandle.SYSTEM; 15173 } 15174 15175 /* 15176 * Determine if we have any installed package verifiers. If we 15177 * do, then we'll defer to them to verify the packages. 15178 */ 15179 final int requiredUid = mRequiredVerifierPackage == null ? -1 15180 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15181 verifierUser.getIdentifier()); 15182 final int installerUid = 15183 verificationInfo == null ? -1 : verificationInfo.installerUid; 15184 if (!origin.existing && requiredUid != -1 15185 && isVerificationEnabled( 15186 verifierUser.getIdentifier(), installFlags, installerUid)) { 15187 final Intent verification = new Intent( 15188 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15189 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15190 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15191 PACKAGE_MIME_TYPE); 15192 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15193 15194 // Query all live verifiers based on current user state 15195 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15196 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15197 false /*allowDynamicSplits*/); 15198 15199 if (DEBUG_VERIFY) { 15200 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15201 + verification.toString() + " with " + pkgLite.verifiers.length 15202 + " optional verifiers"); 15203 } 15204 15205 final int verificationId = mPendingVerificationToken++; 15206 15207 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15208 15209 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15210 installerPackageName); 15211 15212 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15213 installFlags); 15214 15215 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15216 pkgLite.packageName); 15217 15218 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15219 pkgLite.versionCode); 15220 15221 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15222 pkgLite.getLongVersionCode()); 15223 15224 if (verificationInfo != null) { 15225 if (verificationInfo.originatingUri != null) { 15226 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15227 verificationInfo.originatingUri); 15228 } 15229 if (verificationInfo.referrer != null) { 15230 verification.putExtra(Intent.EXTRA_REFERRER, 15231 verificationInfo.referrer); 15232 } 15233 if (verificationInfo.originatingUid >= 0) { 15234 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15235 verificationInfo.originatingUid); 15236 } 15237 if (verificationInfo.installerUid >= 0) { 15238 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15239 verificationInfo.installerUid); 15240 } 15241 } 15242 15243 final PackageVerificationState verificationState = new PackageVerificationState( 15244 requiredUid, args); 15245 15246 mPendingVerification.append(verificationId, verificationState); 15247 15248 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15249 receivers, verificationState); 15250 15251 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15252 final long idleDuration = getVerificationTimeout(); 15253 15254 /* 15255 * If any sufficient verifiers were listed in the package 15256 * manifest, attempt to ask them. 15257 */ 15258 if (sufficientVerifiers != null) { 15259 final int N = sufficientVerifiers.size(); 15260 if (N == 0) { 15261 Slog.i(TAG, "Additional verifiers required, but none installed."); 15262 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15263 } else { 15264 for (int i = 0; i < N; i++) { 15265 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15266 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15267 verifierComponent.getPackageName(), idleDuration, 15268 verifierUser.getIdentifier(), false, "package verifier"); 15269 15270 final Intent sufficientIntent = new Intent(verification); 15271 sufficientIntent.setComponent(verifierComponent); 15272 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15273 } 15274 } 15275 } 15276 15277 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15278 mRequiredVerifierPackage, receivers); 15279 if (ret == PackageManager.INSTALL_SUCCEEDED 15280 && mRequiredVerifierPackage != null) { 15281 Trace.asyncTraceBegin( 15282 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15283 /* 15284 * Send the intent to the required verification agent, 15285 * but only start the verification timeout after the 15286 * target BroadcastReceivers have run. 15287 */ 15288 verification.setComponent(requiredVerifierComponent); 15289 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15290 mRequiredVerifierPackage, idleDuration, 15291 verifierUser.getIdentifier(), false, "package verifier"); 15292 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15293 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15294 new BroadcastReceiver() { 15295 @Override 15296 public void onReceive(Context context, Intent intent) { 15297 final Message msg = mHandler 15298 .obtainMessage(CHECK_PENDING_VERIFICATION); 15299 msg.arg1 = verificationId; 15300 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15301 } 15302 }, null, 0, null, null); 15303 15304 /* 15305 * We don't want the copy to proceed until verification 15306 * succeeds, so null out this field. 15307 */ 15308 mArgs = null; 15309 } 15310 } else { 15311 /* 15312 * No package verification is enabled, so immediately start 15313 * the remote call to initiate copy using temporary file. 15314 */ 15315 ret = args.copyApk(mContainerService, true); 15316 } 15317 } 15318 15319 mRet = ret; 15320 } 15321 15322 @Override 15323 void handleReturnCode() { 15324 // If mArgs is null, then MCS couldn't be reached. When it 15325 // reconnects, it will try again to install. At that point, this 15326 // will succeed. 15327 if (mArgs != null) { 15328 processPendingInstall(mArgs, mRet); 15329 } 15330 } 15331 15332 @Override 15333 void handleServiceError() { 15334 mArgs = createInstallArgs(this); 15335 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15336 } 15337 } 15338 15339 private InstallArgs createInstallArgs(InstallParams params) { 15340 if (params.move != null) { 15341 return new MoveInstallArgs(params); 15342 } else { 15343 return new FileInstallArgs(params); 15344 } 15345 } 15346 15347 /** 15348 * Create args that describe an existing installed package. Typically used 15349 * when cleaning up old installs, or used as a move source. 15350 */ 15351 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15352 String resourcePath, String[] instructionSets) { 15353 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15354 } 15355 15356 static abstract class InstallArgs { 15357 /** @see InstallParams#origin */ 15358 final OriginInfo origin; 15359 /** @see InstallParams#move */ 15360 final MoveInfo move; 15361 15362 final IPackageInstallObserver2 observer; 15363 // Always refers to PackageManager flags only 15364 final int installFlags; 15365 final String installerPackageName; 15366 final String volumeUuid; 15367 final UserHandle user; 15368 final String abiOverride; 15369 final String[] installGrantPermissions; 15370 /** If non-null, drop an async trace when the install completes */ 15371 final String traceMethod; 15372 final int traceCookie; 15373 final PackageParser.SigningDetails signingDetails; 15374 final int installReason; 15375 15376 // The list of instruction sets supported by this app. This is currently 15377 // only used during the rmdex() phase to clean up resources. We can get rid of this 15378 // if we move dex files under the common app path. 15379 /* nullable */ String[] instructionSets; 15380 15381 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15382 int installFlags, String installerPackageName, String volumeUuid, 15383 UserHandle user, String[] instructionSets, 15384 String abiOverride, String[] installGrantPermissions, 15385 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15386 int installReason) { 15387 this.origin = origin; 15388 this.move = move; 15389 this.installFlags = installFlags; 15390 this.observer = observer; 15391 this.installerPackageName = installerPackageName; 15392 this.volumeUuid = volumeUuid; 15393 this.user = user; 15394 this.instructionSets = instructionSets; 15395 this.abiOverride = abiOverride; 15396 this.installGrantPermissions = installGrantPermissions; 15397 this.traceMethod = traceMethod; 15398 this.traceCookie = traceCookie; 15399 this.signingDetails = signingDetails; 15400 this.installReason = installReason; 15401 } 15402 15403 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15404 abstract int doPreInstall(int status); 15405 15406 /** 15407 * Rename package into final resting place. All paths on the given 15408 * scanned package should be updated to reflect the rename. 15409 */ 15410 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15411 abstract int doPostInstall(int status, int uid); 15412 15413 /** @see PackageSettingBase#codePathString */ 15414 abstract String getCodePath(); 15415 /** @see PackageSettingBase#resourcePathString */ 15416 abstract String getResourcePath(); 15417 15418 // Need installer lock especially for dex file removal. 15419 abstract void cleanUpResourcesLI(); 15420 abstract boolean doPostDeleteLI(boolean delete); 15421 15422 /** 15423 * Called before the source arguments are copied. This is used mostly 15424 * for MoveParams when it needs to read the source file to put it in the 15425 * destination. 15426 */ 15427 int doPreCopy() { 15428 return PackageManager.INSTALL_SUCCEEDED; 15429 } 15430 15431 /** 15432 * Called after the source arguments are copied. This is used mostly for 15433 * MoveParams when it needs to read the source file to put it in the 15434 * destination. 15435 */ 15436 int doPostCopy(int uid) { 15437 return PackageManager.INSTALL_SUCCEEDED; 15438 } 15439 15440 protected boolean isFwdLocked() { 15441 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15442 } 15443 15444 protected boolean isExternalAsec() { 15445 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15446 } 15447 15448 protected boolean isEphemeral() { 15449 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15450 } 15451 15452 UserHandle getUser() { 15453 return user; 15454 } 15455 } 15456 15457 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15458 if (!allCodePaths.isEmpty()) { 15459 if (instructionSets == null) { 15460 throw new IllegalStateException("instructionSet == null"); 15461 } 15462 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15463 for (String codePath : allCodePaths) { 15464 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15465 try { 15466 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15467 } catch (InstallerException ignored) { 15468 } 15469 } 15470 } 15471 } 15472 } 15473 15474 /** 15475 * Logic to handle installation of non-ASEC applications, including copying 15476 * and renaming logic. 15477 */ 15478 class FileInstallArgs extends InstallArgs { 15479 private File codeFile; 15480 private File resourceFile; 15481 15482 // Example topology: 15483 // /data/app/com.example/base.apk 15484 // /data/app/com.example/split_foo.apk 15485 // /data/app/com.example/lib/arm/libfoo.so 15486 // /data/app/com.example/lib/arm64/libfoo.so 15487 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15488 15489 /** New install */ 15490 FileInstallArgs(InstallParams params) { 15491 super(params.origin, params.move, params.observer, params.installFlags, 15492 params.installerPackageName, params.volumeUuid, 15493 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15494 params.grantedRuntimePermissions, 15495 params.traceMethod, params.traceCookie, params.signingDetails, 15496 params.installReason); 15497 if (isFwdLocked()) { 15498 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15499 } 15500 } 15501 15502 /** Existing install */ 15503 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15504 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15505 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15506 PackageManager.INSTALL_REASON_UNKNOWN); 15507 this.codeFile = (codePath != null) ? new File(codePath) : null; 15508 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15509 } 15510 15511 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15513 try { 15514 return doCopyApk(imcs, temp); 15515 } finally { 15516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15517 } 15518 } 15519 15520 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15521 if (origin.staged) { 15522 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15523 codeFile = origin.file; 15524 resourceFile = origin.file; 15525 return PackageManager.INSTALL_SUCCEEDED; 15526 } 15527 15528 try { 15529 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15530 final File tempDir = 15531 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15532 codeFile = tempDir; 15533 resourceFile = tempDir; 15534 } catch (IOException e) { 15535 Slog.w(TAG, "Failed to create copy file: " + e); 15536 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15537 } 15538 15539 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15540 @Override 15541 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15542 if (!FileUtils.isValidExtFilename(name)) { 15543 throw new IllegalArgumentException("Invalid filename: " + name); 15544 } 15545 try { 15546 final File file = new File(codeFile, name); 15547 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15548 O_RDWR | O_CREAT, 0644); 15549 Os.chmod(file.getAbsolutePath(), 0644); 15550 return new ParcelFileDescriptor(fd); 15551 } catch (ErrnoException e) { 15552 throw new RemoteException("Failed to open: " + e.getMessage()); 15553 } 15554 } 15555 }; 15556 15557 int ret = PackageManager.INSTALL_SUCCEEDED; 15558 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15559 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15560 Slog.e(TAG, "Failed to copy package"); 15561 return ret; 15562 } 15563 15564 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15565 NativeLibraryHelper.Handle handle = null; 15566 try { 15567 handle = NativeLibraryHelper.Handle.create(codeFile); 15568 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15569 abiOverride); 15570 } catch (IOException e) { 15571 Slog.e(TAG, "Copying native libraries failed", e); 15572 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15573 } finally { 15574 IoUtils.closeQuietly(handle); 15575 } 15576 15577 return ret; 15578 } 15579 15580 int doPreInstall(int status) { 15581 if (status != PackageManager.INSTALL_SUCCEEDED) { 15582 cleanUp(); 15583 } 15584 return status; 15585 } 15586 15587 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15588 if (status != PackageManager.INSTALL_SUCCEEDED) { 15589 cleanUp(); 15590 return false; 15591 } 15592 15593 final File targetDir = codeFile.getParentFile(); 15594 final File beforeCodeFile = codeFile; 15595 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15596 15597 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15598 try { 15599 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15600 } catch (ErrnoException e) { 15601 Slog.w(TAG, "Failed to rename", e); 15602 return false; 15603 } 15604 15605 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15606 Slog.w(TAG, "Failed to restorecon"); 15607 return false; 15608 } 15609 15610 // Reflect the rename internally 15611 codeFile = afterCodeFile; 15612 resourceFile = afterCodeFile; 15613 15614 // Reflect the rename in scanned details 15615 try { 15616 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15617 } catch (IOException e) { 15618 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15619 return false; 15620 } 15621 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15622 afterCodeFile, pkg.baseCodePath)); 15623 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15624 afterCodeFile, pkg.splitCodePaths)); 15625 15626 // Reflect the rename in app info 15627 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15628 pkg.setApplicationInfoCodePath(pkg.codePath); 15629 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15630 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15631 pkg.setApplicationInfoResourcePath(pkg.codePath); 15632 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15633 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15634 15635 return true; 15636 } 15637 15638 int doPostInstall(int status, int uid) { 15639 if (status != PackageManager.INSTALL_SUCCEEDED) { 15640 cleanUp(); 15641 } 15642 return status; 15643 } 15644 15645 @Override 15646 String getCodePath() { 15647 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15648 } 15649 15650 @Override 15651 String getResourcePath() { 15652 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15653 } 15654 15655 private boolean cleanUp() { 15656 if (codeFile == null || !codeFile.exists()) { 15657 return false; 15658 } 15659 15660 removeCodePathLI(codeFile); 15661 15662 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15663 resourceFile.delete(); 15664 } 15665 15666 return true; 15667 } 15668 15669 void cleanUpResourcesLI() { 15670 // Try enumerating all code paths before deleting 15671 List<String> allCodePaths = Collections.EMPTY_LIST; 15672 if (codeFile != null && codeFile.exists()) { 15673 try { 15674 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15675 allCodePaths = pkg.getAllCodePaths(); 15676 } catch (PackageParserException e) { 15677 // Ignored; we tried our best 15678 } 15679 } 15680 15681 cleanUp(); 15682 removeDexFiles(allCodePaths, instructionSets); 15683 } 15684 15685 boolean doPostDeleteLI(boolean delete) { 15686 // XXX err, shouldn't we respect the delete flag? 15687 cleanUpResourcesLI(); 15688 return true; 15689 } 15690 } 15691 15692 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15693 PackageManagerException { 15694 if (copyRet < 0) { 15695 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15696 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15697 throw new PackageManagerException(copyRet, message); 15698 } 15699 } 15700 } 15701 15702 /** 15703 * Extract the StorageManagerService "container ID" from the full code path of an 15704 * .apk. 15705 */ 15706 static String cidFromCodePath(String fullCodePath) { 15707 int eidx = fullCodePath.lastIndexOf("/"); 15708 String subStr1 = fullCodePath.substring(0, eidx); 15709 int sidx = subStr1.lastIndexOf("/"); 15710 return subStr1.substring(sidx+1, eidx); 15711 } 15712 15713 /** 15714 * Logic to handle movement of existing installed applications. 15715 */ 15716 class MoveInstallArgs extends InstallArgs { 15717 private File codeFile; 15718 private File resourceFile; 15719 15720 /** New install */ 15721 MoveInstallArgs(InstallParams params) { 15722 super(params.origin, params.move, params.observer, params.installFlags, 15723 params.installerPackageName, params.volumeUuid, 15724 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15725 params.grantedRuntimePermissions, 15726 params.traceMethod, params.traceCookie, params.signingDetails, 15727 params.installReason); 15728 } 15729 15730 int copyApk(IMediaContainerService imcs, boolean temp) { 15731 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15732 + move.fromUuid + " to " + move.toUuid); 15733 synchronized (mInstaller) { 15734 try { 15735 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15736 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15737 } catch (InstallerException e) { 15738 Slog.w(TAG, "Failed to move app", e); 15739 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15740 } 15741 } 15742 15743 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15744 resourceFile = codeFile; 15745 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15746 15747 return PackageManager.INSTALL_SUCCEEDED; 15748 } 15749 15750 int doPreInstall(int status) { 15751 if (status != PackageManager.INSTALL_SUCCEEDED) { 15752 cleanUp(move.toUuid); 15753 } 15754 return status; 15755 } 15756 15757 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15758 if (status != PackageManager.INSTALL_SUCCEEDED) { 15759 cleanUp(move.toUuid); 15760 return false; 15761 } 15762 15763 // Reflect the move in app info 15764 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15765 pkg.setApplicationInfoCodePath(pkg.codePath); 15766 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15767 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15768 pkg.setApplicationInfoResourcePath(pkg.codePath); 15769 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15770 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15771 15772 return true; 15773 } 15774 15775 int doPostInstall(int status, int uid) { 15776 if (status == PackageManager.INSTALL_SUCCEEDED) { 15777 cleanUp(move.fromUuid); 15778 } else { 15779 cleanUp(move.toUuid); 15780 } 15781 return status; 15782 } 15783 15784 @Override 15785 String getCodePath() { 15786 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15787 } 15788 15789 @Override 15790 String getResourcePath() { 15791 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15792 } 15793 15794 private boolean cleanUp(String volumeUuid) { 15795 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15796 move.dataAppName); 15797 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15798 final int[] userIds = sUserManager.getUserIds(); 15799 synchronized (mInstallLock) { 15800 // Clean up both app data and code 15801 // All package moves are frozen until finished 15802 for (int userId : userIds) { 15803 try { 15804 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15805 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15806 } catch (InstallerException e) { 15807 Slog.w(TAG, String.valueOf(e)); 15808 } 15809 } 15810 removeCodePathLI(codeFile); 15811 } 15812 return true; 15813 } 15814 15815 void cleanUpResourcesLI() { 15816 throw new UnsupportedOperationException(); 15817 } 15818 15819 boolean doPostDeleteLI(boolean delete) { 15820 throw new UnsupportedOperationException(); 15821 } 15822 } 15823 15824 static String getAsecPackageName(String packageCid) { 15825 int idx = packageCid.lastIndexOf("-"); 15826 if (idx == -1) { 15827 return packageCid; 15828 } 15829 return packageCid.substring(0, idx); 15830 } 15831 15832 // Utility method used to create code paths based on package name and available index. 15833 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15834 String idxStr = ""; 15835 int idx = 1; 15836 // Fall back to default value of idx=1 if prefix is not 15837 // part of oldCodePath 15838 if (oldCodePath != null) { 15839 String subStr = oldCodePath; 15840 // Drop the suffix right away 15841 if (suffix != null && subStr.endsWith(suffix)) { 15842 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15843 } 15844 // If oldCodePath already contains prefix find out the 15845 // ending index to either increment or decrement. 15846 int sidx = subStr.lastIndexOf(prefix); 15847 if (sidx != -1) { 15848 subStr = subStr.substring(sidx + prefix.length()); 15849 if (subStr != null) { 15850 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15851 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15852 } 15853 try { 15854 idx = Integer.parseInt(subStr); 15855 if (idx <= 1) { 15856 idx++; 15857 } else { 15858 idx--; 15859 } 15860 } catch(NumberFormatException e) { 15861 } 15862 } 15863 } 15864 } 15865 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15866 return prefix + idxStr; 15867 } 15868 15869 private File getNextCodePath(File targetDir, String packageName) { 15870 File result; 15871 SecureRandom random = new SecureRandom(); 15872 byte[] bytes = new byte[16]; 15873 do { 15874 random.nextBytes(bytes); 15875 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15876 result = new File(targetDir, packageName + "-" + suffix); 15877 } while (result.exists()); 15878 return result; 15879 } 15880 15881 // Utility method that returns the relative package path with respect 15882 // to the installation directory. Like say for /data/data/com.test-1.apk 15883 // string com.test-1 is returned. 15884 static String deriveCodePathName(String codePath) { 15885 if (codePath == null) { 15886 return null; 15887 } 15888 final File codeFile = new File(codePath); 15889 final String name = codeFile.getName(); 15890 if (codeFile.isDirectory()) { 15891 return name; 15892 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15893 final int lastDot = name.lastIndexOf('.'); 15894 return name.substring(0, lastDot); 15895 } else { 15896 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15897 return null; 15898 } 15899 } 15900 15901 static class PackageInstalledInfo { 15902 String name; 15903 int uid; 15904 // The set of users that originally had this package installed. 15905 int[] origUsers; 15906 // The set of users that now have this package installed. 15907 int[] newUsers; 15908 PackageParser.Package pkg; 15909 int returnCode; 15910 String returnMsg; 15911 String installerPackageName; 15912 PackageRemovedInfo removedInfo; 15913 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15914 15915 public void setError(int code, String msg) { 15916 setReturnCode(code); 15917 setReturnMessage(msg); 15918 Slog.w(TAG, msg); 15919 } 15920 15921 public void setError(String msg, PackageParserException e) { 15922 setReturnCode(e.error); 15923 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15924 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15925 for (int i = 0; i < childCount; i++) { 15926 addedChildPackages.valueAt(i).setError(msg, e); 15927 } 15928 Slog.w(TAG, msg, e); 15929 } 15930 15931 public void setError(String msg, PackageManagerException e) { 15932 returnCode = e.error; 15933 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15934 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15935 for (int i = 0; i < childCount; i++) { 15936 addedChildPackages.valueAt(i).setError(msg, e); 15937 } 15938 Slog.w(TAG, msg, e); 15939 } 15940 15941 public void setReturnCode(int returnCode) { 15942 this.returnCode = returnCode; 15943 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15944 for (int i = 0; i < childCount; i++) { 15945 addedChildPackages.valueAt(i).returnCode = returnCode; 15946 } 15947 } 15948 15949 private void setReturnMessage(String returnMsg) { 15950 this.returnMsg = returnMsg; 15951 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15952 for (int i = 0; i < childCount; i++) { 15953 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15954 } 15955 } 15956 15957 // In some error cases we want to convey more info back to the observer 15958 String origPackage; 15959 String origPermission; 15960 } 15961 15962 /* 15963 * Install a non-existing package. 15964 */ 15965 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15966 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15967 String volumeUuid, PackageInstalledInfo res, int installReason) { 15968 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15969 15970 // Remember this for later, in case we need to rollback this install 15971 String pkgName = pkg.packageName; 15972 15973 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15974 15975 synchronized(mPackages) { 15976 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15977 if (renamedPackage != null) { 15978 // A package with the same name is already installed, though 15979 // it has been renamed to an older name. The package we 15980 // are trying to install should be installed as an update to 15981 // the existing one, but that has not been requested, so bail. 15982 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15983 + " without first uninstalling package running as " 15984 + renamedPackage); 15985 return; 15986 } 15987 if (mPackages.containsKey(pkgName)) { 15988 // Don't allow installation over an existing package with the same name. 15989 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15990 + " without first uninstalling."); 15991 return; 15992 } 15993 } 15994 15995 try { 15996 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15997 System.currentTimeMillis(), user); 15998 15999 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16000 16001 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16002 prepareAppDataAfterInstallLIF(newPackage); 16003 16004 } else { 16005 // Remove package from internal structures, but keep around any 16006 // data that might have already existed 16007 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16008 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16009 } 16010 } catch (PackageManagerException e) { 16011 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16012 } 16013 16014 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16015 } 16016 16017 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16018 try (DigestInputStream digestStream = 16019 new DigestInputStream(new FileInputStream(file), digest)) { 16020 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16021 } 16022 } 16023 16024 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16025 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16026 PackageInstalledInfo res, int installReason) { 16027 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16028 16029 final PackageParser.Package oldPackage; 16030 final PackageSetting ps; 16031 final String pkgName = pkg.packageName; 16032 final int[] allUsers; 16033 final int[] installedUsers; 16034 16035 synchronized(mPackages) { 16036 oldPackage = mPackages.get(pkgName); 16037 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16038 16039 // don't allow upgrade to target a release SDK from a pre-release SDK 16040 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16041 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16042 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16043 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16044 if (oldTargetsPreRelease 16045 && !newTargetsPreRelease 16046 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16047 Slog.w(TAG, "Can't install package targeting released sdk"); 16048 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16049 return; 16050 } 16051 16052 ps = mSettings.mPackages.get(pkgName); 16053 16054 // verify signatures are valid 16055 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16056 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16057 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16058 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16059 "New package not signed by keys specified by upgrade-keysets: " 16060 + pkgName); 16061 return; 16062 } 16063 } else { 16064 // default to original signature matching 16065 if (compareSignatures(oldPackage.mSigningDetails.signatures, 16066 pkg.mSigningDetails.signatures) 16067 != PackageManager.SIGNATURE_MATCH) { 16068 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16069 "New package has a different signature: " + pkgName); 16070 return; 16071 } 16072 } 16073 16074 // don't allow a system upgrade unless the upgrade hash matches 16075 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16076 byte[] digestBytes = null; 16077 try { 16078 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16079 updateDigest(digest, new File(pkg.baseCodePath)); 16080 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16081 for (String path : pkg.splitCodePaths) { 16082 updateDigest(digest, new File(path)); 16083 } 16084 } 16085 digestBytes = digest.digest(); 16086 } catch (NoSuchAlgorithmException | IOException e) { 16087 res.setError(INSTALL_FAILED_INVALID_APK, 16088 "Could not compute hash: " + pkgName); 16089 return; 16090 } 16091 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16092 res.setError(INSTALL_FAILED_INVALID_APK, 16093 "New package fails restrict-update check: " + pkgName); 16094 return; 16095 } 16096 // retain upgrade restriction 16097 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16098 } 16099 16100 // Check for shared user id changes 16101 String invalidPackageName = 16102 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16103 if (invalidPackageName != null) { 16104 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16105 "Package " + invalidPackageName + " tried to change user " 16106 + oldPackage.mSharedUserId); 16107 return; 16108 } 16109 16110 // check if the new package supports all of the abis which the old package supports 16111 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16112 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16113 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16114 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16115 "Update to package " + pkgName + " doesn't support multi arch"); 16116 return; 16117 } 16118 16119 // In case of rollback, remember per-user/profile install state 16120 allUsers = sUserManager.getUserIds(); 16121 installedUsers = ps.queryInstalledUsers(allUsers, true); 16122 16123 // don't allow an upgrade from full to ephemeral 16124 if (isInstantApp) { 16125 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16126 for (int currentUser : allUsers) { 16127 if (!ps.getInstantApp(currentUser)) { 16128 // can't downgrade from full to instant 16129 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16130 + " for user: " + currentUser); 16131 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16132 return; 16133 } 16134 } 16135 } else if (!ps.getInstantApp(user.getIdentifier())) { 16136 // can't downgrade from full to instant 16137 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16138 + " for user: " + user.getIdentifier()); 16139 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16140 return; 16141 } 16142 } 16143 } 16144 16145 // Update what is removed 16146 res.removedInfo = new PackageRemovedInfo(this); 16147 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16148 res.removedInfo.removedPackage = oldPackage.packageName; 16149 res.removedInfo.installerPackageName = ps.installerPackageName; 16150 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16151 res.removedInfo.isUpdate = true; 16152 res.removedInfo.origUsers = installedUsers; 16153 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16154 for (int i = 0; i < installedUsers.length; i++) { 16155 final int userId = installedUsers[i]; 16156 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16157 } 16158 16159 final int childCount = (oldPackage.childPackages != null) 16160 ? oldPackage.childPackages.size() : 0; 16161 for (int i = 0; i < childCount; i++) { 16162 boolean childPackageUpdated = false; 16163 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16164 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16165 if (res.addedChildPackages != null) { 16166 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16167 if (childRes != null) { 16168 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16169 childRes.removedInfo.removedPackage = childPkg.packageName; 16170 if (childPs != null) { 16171 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16172 } 16173 childRes.removedInfo.isUpdate = true; 16174 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16175 childPackageUpdated = true; 16176 } 16177 } 16178 if (!childPackageUpdated) { 16179 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16180 childRemovedRes.removedPackage = childPkg.packageName; 16181 if (childPs != null) { 16182 childRemovedRes.installerPackageName = childPs.installerPackageName; 16183 } 16184 childRemovedRes.isUpdate = false; 16185 childRemovedRes.dataRemoved = true; 16186 synchronized (mPackages) { 16187 if (childPs != null) { 16188 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16189 } 16190 } 16191 if (res.removedInfo.removedChildPackages == null) { 16192 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16193 } 16194 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16195 } 16196 } 16197 16198 boolean sysPkg = (isSystemApp(oldPackage)); 16199 if (sysPkg) { 16200 // Set the system/privileged/oem/vendor/product flags as needed 16201 final boolean privileged = 16202 (oldPackage.applicationInfo.privateFlags 16203 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16204 final boolean oem = 16205 (oldPackage.applicationInfo.privateFlags 16206 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16207 final boolean vendor = 16208 (oldPackage.applicationInfo.privateFlags 16209 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16210 final boolean product = 16211 (oldPackage.applicationInfo.privateFlags 16212 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16213 final @ParseFlags int systemParseFlags = parseFlags; 16214 final @ScanFlags int systemScanFlags = scanFlags 16215 | SCAN_AS_SYSTEM 16216 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16217 | (oem ? SCAN_AS_OEM : 0) 16218 | (vendor ? SCAN_AS_VENDOR : 0) 16219 | (product ? SCAN_AS_PRODUCT : 0); 16220 16221 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16222 user, allUsers, installerPackageName, res, installReason); 16223 } else { 16224 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16225 user, allUsers, installerPackageName, res, installReason); 16226 } 16227 } 16228 16229 @Override 16230 public List<String> getPreviousCodePaths(String packageName) { 16231 final int callingUid = Binder.getCallingUid(); 16232 final List<String> result = new ArrayList<>(); 16233 if (getInstantAppPackageName(callingUid) != null) { 16234 return result; 16235 } 16236 final PackageSetting ps = mSettings.mPackages.get(packageName); 16237 if (ps != null 16238 && ps.oldCodePaths != null 16239 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16240 result.addAll(ps.oldCodePaths); 16241 } 16242 return result; 16243 } 16244 16245 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16246 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16247 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16248 String installerPackageName, PackageInstalledInfo res, int installReason) { 16249 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16250 + deletedPackage); 16251 16252 String pkgName = deletedPackage.packageName; 16253 boolean deletedPkg = true; 16254 boolean addedPkg = false; 16255 boolean updatedSettings = false; 16256 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16257 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16258 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16259 16260 final long origUpdateTime = (pkg.mExtras != null) 16261 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16262 16263 // First delete the existing package while retaining the data directory 16264 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16265 res.removedInfo, true, pkg)) { 16266 // If the existing package wasn't successfully deleted 16267 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16268 deletedPkg = false; 16269 } else { 16270 // Successfully deleted the old package; proceed with replace. 16271 16272 // If deleted package lived in a container, give users a chance to 16273 // relinquish resources before killing. 16274 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16275 if (DEBUG_INSTALL) { 16276 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16277 } 16278 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16279 final ArrayList<String> pkgList = new ArrayList<String>(1); 16280 pkgList.add(deletedPackage.applicationInfo.packageName); 16281 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16282 } 16283 16284 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16285 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16286 16287 try { 16288 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16289 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16290 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16291 installReason); 16292 16293 // Update the in-memory copy of the previous code paths. 16294 PackageSetting ps = mSettings.mPackages.get(pkgName); 16295 if (!killApp) { 16296 if (ps.oldCodePaths == null) { 16297 ps.oldCodePaths = new ArraySet<>(); 16298 } 16299 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16300 if (deletedPackage.splitCodePaths != null) { 16301 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16302 } 16303 } else { 16304 ps.oldCodePaths = null; 16305 } 16306 if (ps.childPackageNames != null) { 16307 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16308 final String childPkgName = ps.childPackageNames.get(i); 16309 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16310 childPs.oldCodePaths = ps.oldCodePaths; 16311 } 16312 } 16313 // set instant app status, but, only if it's explicitly specified 16314 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16315 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16316 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16317 prepareAppDataAfterInstallLIF(newPackage); 16318 addedPkg = true; 16319 mDexManager.notifyPackageUpdated(newPackage.packageName, 16320 newPackage.baseCodePath, newPackage.splitCodePaths); 16321 } catch (PackageManagerException e) { 16322 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16323 } 16324 } 16325 16326 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16327 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16328 16329 // Revert all internal state mutations and added folders for the failed install 16330 if (addedPkg) { 16331 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16332 res.removedInfo, true, null); 16333 } 16334 16335 // Restore the old package 16336 if (deletedPkg) { 16337 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16338 File restoreFile = new File(deletedPackage.codePath); 16339 // Parse old package 16340 boolean oldExternal = isExternal(deletedPackage); 16341 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16342 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16343 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16344 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16345 try { 16346 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16347 null); 16348 } catch (PackageManagerException e) { 16349 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16350 + e.getMessage()); 16351 return; 16352 } 16353 16354 synchronized (mPackages) { 16355 // Ensure the installer package name up to date 16356 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16357 16358 // Update permissions for restored package 16359 mPermissionManager.updatePermissions( 16360 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16361 mPermissionCallback); 16362 16363 mSettings.writeLPr(); 16364 } 16365 16366 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16367 } 16368 } else { 16369 synchronized (mPackages) { 16370 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16371 if (ps != null) { 16372 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16373 if (res.removedInfo.removedChildPackages != null) { 16374 final int childCount = res.removedInfo.removedChildPackages.size(); 16375 // Iterate in reverse as we may modify the collection 16376 for (int i = childCount - 1; i >= 0; i--) { 16377 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16378 if (res.addedChildPackages.containsKey(childPackageName)) { 16379 res.removedInfo.removedChildPackages.removeAt(i); 16380 } else { 16381 PackageRemovedInfo childInfo = res.removedInfo 16382 .removedChildPackages.valueAt(i); 16383 childInfo.removedForAllUsers = mPackages.get( 16384 childInfo.removedPackage) == null; 16385 } 16386 } 16387 } 16388 } 16389 } 16390 } 16391 } 16392 16393 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16394 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16395 final @ScanFlags int scanFlags, UserHandle user, 16396 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16397 int installReason) { 16398 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16399 + ", old=" + deletedPackage); 16400 16401 final boolean disabledSystem; 16402 16403 // Remove existing system package 16404 removePackageLI(deletedPackage, true); 16405 16406 synchronized (mPackages) { 16407 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16408 } 16409 if (!disabledSystem) { 16410 // We didn't need to disable the .apk as a current system package, 16411 // which means we are replacing another update that is already 16412 // installed. We need to make sure to delete the older one's .apk. 16413 res.removedInfo.args = createInstallArgsForExisting(0, 16414 deletedPackage.applicationInfo.getCodePath(), 16415 deletedPackage.applicationInfo.getResourcePath(), 16416 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16417 } else { 16418 res.removedInfo.args = null; 16419 } 16420 16421 // Successfully disabled the old package. Now proceed with re-installation 16422 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16423 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16424 16425 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16426 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16427 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16428 16429 PackageParser.Package newPackage = null; 16430 try { 16431 // Add the package to the internal data structures 16432 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16433 16434 // Set the update and install times 16435 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16436 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16437 System.currentTimeMillis()); 16438 16439 // Update the package dynamic state if succeeded 16440 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16441 // Now that the install succeeded make sure we remove data 16442 // directories for any child package the update removed. 16443 final int deletedChildCount = (deletedPackage.childPackages != null) 16444 ? deletedPackage.childPackages.size() : 0; 16445 final int newChildCount = (newPackage.childPackages != null) 16446 ? newPackage.childPackages.size() : 0; 16447 for (int i = 0; i < deletedChildCount; i++) { 16448 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16449 boolean childPackageDeleted = true; 16450 for (int j = 0; j < newChildCount; j++) { 16451 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16452 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16453 childPackageDeleted = false; 16454 break; 16455 } 16456 } 16457 if (childPackageDeleted) { 16458 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16459 deletedChildPkg.packageName); 16460 if (ps != null && res.removedInfo.removedChildPackages != null) { 16461 PackageRemovedInfo removedChildRes = res.removedInfo 16462 .removedChildPackages.get(deletedChildPkg.packageName); 16463 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16464 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16465 } 16466 } 16467 } 16468 16469 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16470 installReason); 16471 prepareAppDataAfterInstallLIF(newPackage); 16472 16473 mDexManager.notifyPackageUpdated(newPackage.packageName, 16474 newPackage.baseCodePath, newPackage.splitCodePaths); 16475 } 16476 } catch (PackageManagerException e) { 16477 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16478 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16479 } 16480 16481 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16482 // Re installation failed. Restore old information 16483 // Remove new pkg information 16484 if (newPackage != null) { 16485 removeInstalledPackageLI(newPackage, true); 16486 } 16487 // Add back the old system package 16488 try { 16489 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16490 } catch (PackageManagerException e) { 16491 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16492 } 16493 16494 synchronized (mPackages) { 16495 if (disabledSystem) { 16496 enableSystemPackageLPw(deletedPackage); 16497 } 16498 16499 // Ensure the installer package name up to date 16500 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16501 16502 // Update permissions for restored package 16503 mPermissionManager.updatePermissions( 16504 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16505 mPermissionCallback); 16506 16507 mSettings.writeLPr(); 16508 } 16509 16510 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16511 + " after failed upgrade"); 16512 } 16513 } 16514 16515 /** 16516 * Checks whether the parent or any of the child packages have a change shared 16517 * user. For a package to be a valid update the shred users of the parent and 16518 * the children should match. We may later support changing child shared users. 16519 * @param oldPkg The updated package. 16520 * @param newPkg The update package. 16521 * @return The shared user that change between the versions. 16522 */ 16523 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16524 PackageParser.Package newPkg) { 16525 // Check parent shared user 16526 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16527 return newPkg.packageName; 16528 } 16529 // Check child shared users 16530 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16531 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16532 for (int i = 0; i < newChildCount; i++) { 16533 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16534 // If this child was present, did it have the same shared user? 16535 for (int j = 0; j < oldChildCount; j++) { 16536 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16537 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16538 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16539 return newChildPkg.packageName; 16540 } 16541 } 16542 } 16543 return null; 16544 } 16545 16546 private void removeNativeBinariesLI(PackageSetting ps) { 16547 // Remove the lib path for the parent package 16548 if (ps != null) { 16549 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16550 // Remove the lib path for the child packages 16551 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16552 for (int i = 0; i < childCount; i++) { 16553 PackageSetting childPs = null; 16554 synchronized (mPackages) { 16555 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16556 } 16557 if (childPs != null) { 16558 NativeLibraryHelper.removeNativeBinariesLI(childPs 16559 .legacyNativeLibraryPathString); 16560 } 16561 } 16562 } 16563 } 16564 16565 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16566 // Enable the parent package 16567 mSettings.enableSystemPackageLPw(pkg.packageName); 16568 // Enable the child packages 16569 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16570 for (int i = 0; i < childCount; i++) { 16571 PackageParser.Package childPkg = pkg.childPackages.get(i); 16572 mSettings.enableSystemPackageLPw(childPkg.packageName); 16573 } 16574 } 16575 16576 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16577 PackageParser.Package newPkg) { 16578 // Disable the parent package (parent always replaced) 16579 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16580 // Disable the child packages 16581 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16582 for (int i = 0; i < childCount; i++) { 16583 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16584 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16585 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16586 } 16587 return disabled; 16588 } 16589 16590 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16591 String installerPackageName) { 16592 // Enable the parent package 16593 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16594 // Enable the child packages 16595 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16596 for (int i = 0; i < childCount; i++) { 16597 PackageParser.Package childPkg = pkg.childPackages.get(i); 16598 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16599 } 16600 } 16601 16602 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16603 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16604 // Update the parent package setting 16605 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16606 res, user, installReason); 16607 // Update the child packages setting 16608 final int childCount = (newPackage.childPackages != null) 16609 ? newPackage.childPackages.size() : 0; 16610 for (int i = 0; i < childCount; i++) { 16611 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16612 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16613 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16614 childRes.origUsers, childRes, user, installReason); 16615 } 16616 } 16617 16618 private void updateSettingsInternalLI(PackageParser.Package pkg, 16619 String installerPackageName, int[] allUsers, int[] installedForUsers, 16620 PackageInstalledInfo res, UserHandle user, int installReason) { 16621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16622 16623 String pkgName = pkg.packageName; 16624 synchronized (mPackages) { 16625 //write settings. the installStatus will be incomplete at this stage. 16626 //note that the new package setting would have already been 16627 //added to mPackages. It hasn't been persisted yet. 16628 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16629 // TODO: Remove this write? It's also written at the end of this method 16630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16631 mSettings.writeLPr(); 16632 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16633 } 16634 16635 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16636 synchronized (mPackages) { 16637// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16638 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16639 mPermissionCallback); 16640 // For system-bundled packages, we assume that installing an upgraded version 16641 // of the package implies that the user actually wants to run that new code, 16642 // so we enable the package. 16643 PackageSetting ps = mSettings.mPackages.get(pkgName); 16644 final int userId = user.getIdentifier(); 16645 if (ps != null) { 16646 if (isSystemApp(pkg)) { 16647 if (DEBUG_INSTALL) { 16648 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16649 } 16650 // Enable system package for requested users 16651 if (res.origUsers != null) { 16652 for (int origUserId : res.origUsers) { 16653 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16654 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16655 origUserId, installerPackageName); 16656 } 16657 } 16658 } 16659 // Also convey the prior install/uninstall state 16660 if (allUsers != null && installedForUsers != null) { 16661 for (int currentUserId : allUsers) { 16662 final boolean installed = ArrayUtils.contains( 16663 installedForUsers, currentUserId); 16664 if (DEBUG_INSTALL) { 16665 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16666 } 16667 ps.setInstalled(installed, currentUserId); 16668 } 16669 // these install state changes will be persisted in the 16670 // upcoming call to mSettings.writeLPr(). 16671 } 16672 } 16673 // It's implied that when a user requests installation, they want the app to be 16674 // installed and enabled. 16675 if (userId != UserHandle.USER_ALL) { 16676 ps.setInstalled(true, userId); 16677 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16678 } 16679 16680 // When replacing an existing package, preserve the original install reason for all 16681 // users that had the package installed before. 16682 final Set<Integer> previousUserIds = new ArraySet<>(); 16683 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16684 final int installReasonCount = res.removedInfo.installReasons.size(); 16685 for (int i = 0; i < installReasonCount; i++) { 16686 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16687 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16688 ps.setInstallReason(previousInstallReason, previousUserId); 16689 previousUserIds.add(previousUserId); 16690 } 16691 } 16692 16693 // Set install reason for users that are having the package newly installed. 16694 if (userId == UserHandle.USER_ALL) { 16695 for (int currentUserId : sUserManager.getUserIds()) { 16696 if (!previousUserIds.contains(currentUserId)) { 16697 ps.setInstallReason(installReason, currentUserId); 16698 } 16699 } 16700 } else if (!previousUserIds.contains(userId)) { 16701 ps.setInstallReason(installReason, userId); 16702 } 16703 mSettings.writeKernelMappingLPr(ps); 16704 } 16705 res.name = pkgName; 16706 res.uid = pkg.applicationInfo.uid; 16707 res.pkg = pkg; 16708 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16709 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16710 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16711 //to update install status 16712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16713 mSettings.writeLPr(); 16714 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16715 } 16716 16717 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16718 } 16719 16720 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16721 try { 16722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16723 installPackageLI(args, res); 16724 } finally { 16725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16726 } 16727 } 16728 16729 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16730 final int installFlags = args.installFlags; 16731 final String installerPackageName = args.installerPackageName; 16732 final String volumeUuid = args.volumeUuid; 16733 final File tmpPackageFile = new File(args.getCodePath()); 16734 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16735 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16736 || (args.volumeUuid != null)); 16737 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16738 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16739 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16740 final boolean virtualPreload = 16741 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16742 boolean replace = false; 16743 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16744 if (args.move != null) { 16745 // moving a complete application; perform an initial scan on the new install location 16746 scanFlags |= SCAN_INITIAL; 16747 } 16748 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16749 scanFlags |= SCAN_DONT_KILL_APP; 16750 } 16751 if (instantApp) { 16752 scanFlags |= SCAN_AS_INSTANT_APP; 16753 } 16754 if (fullApp) { 16755 scanFlags |= SCAN_AS_FULL_APP; 16756 } 16757 if (virtualPreload) { 16758 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16759 } 16760 16761 // Result object to be returned 16762 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16763 res.installerPackageName = installerPackageName; 16764 16765 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16766 16767 // Sanity check 16768 if (instantApp && (forwardLocked || onExternal)) { 16769 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16770 + " external=" + onExternal); 16771 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16772 return; 16773 } 16774 16775 // Retrieve PackageSettings and parse package 16776 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16777 | PackageParser.PARSE_ENFORCE_CODE 16778 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16779 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16780 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16781 PackageParser pp = new PackageParser(); 16782 pp.setSeparateProcesses(mSeparateProcesses); 16783 pp.setDisplayMetrics(mMetrics); 16784 pp.setCallback(mPackageParserCallback); 16785 16786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16787 final PackageParser.Package pkg; 16788 try { 16789 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16790 DexMetadataHelper.validatePackageDexMetadata(pkg); 16791 } catch (PackageParserException e) { 16792 res.setError("Failed parse during installPackageLI", e); 16793 return; 16794 } finally { 16795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16796 } 16797 16798 // Instant apps have several additional install-time checks. 16799 if (instantApp) { 16800 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16801 Slog.w(TAG, 16802 "Instant app package " + pkg.packageName + " does not target at least O"); 16803 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16804 "Instant app package must target at least O"); 16805 return; 16806 } 16807 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16808 Slog.w(TAG, "Instant app package " + pkg.packageName 16809 + " does not target targetSandboxVersion 2"); 16810 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16811 "Instant app package must use targetSandboxVersion 2"); 16812 return; 16813 } 16814 if (pkg.mSharedUserId != null) { 16815 Slog.w(TAG, "Instant app package " + pkg.packageName 16816 + " may not declare sharedUserId."); 16817 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16818 "Instant app package may not declare a sharedUserId"); 16819 return; 16820 } 16821 } 16822 16823 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16824 // Static shared libraries have synthetic package names 16825 renameStaticSharedLibraryPackage(pkg); 16826 16827 // No static shared libs on external storage 16828 if (onExternal) { 16829 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16830 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16831 "Packages declaring static-shared libs cannot be updated"); 16832 return; 16833 } 16834 } 16835 16836 // If we are installing a clustered package add results for the children 16837 if (pkg.childPackages != null) { 16838 synchronized (mPackages) { 16839 final int childCount = pkg.childPackages.size(); 16840 for (int i = 0; i < childCount; i++) { 16841 PackageParser.Package childPkg = pkg.childPackages.get(i); 16842 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16843 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16844 childRes.pkg = childPkg; 16845 childRes.name = childPkg.packageName; 16846 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16847 if (childPs != null) { 16848 childRes.origUsers = childPs.queryInstalledUsers( 16849 sUserManager.getUserIds(), true); 16850 } 16851 if ((mPackages.containsKey(childPkg.packageName))) { 16852 childRes.removedInfo = new PackageRemovedInfo(this); 16853 childRes.removedInfo.removedPackage = childPkg.packageName; 16854 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16855 } 16856 if (res.addedChildPackages == null) { 16857 res.addedChildPackages = new ArrayMap<>(); 16858 } 16859 res.addedChildPackages.put(childPkg.packageName, childRes); 16860 } 16861 } 16862 } 16863 16864 // If package doesn't declare API override, mark that we have an install 16865 // time CPU ABI override. 16866 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16867 pkg.cpuAbiOverride = args.abiOverride; 16868 } 16869 16870 String pkgName = res.name = pkg.packageName; 16871 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16872 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16873 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16874 return; 16875 } 16876 } 16877 16878 try { 16879 // either use what we've been given or parse directly from the APK 16880 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16881 pkg.setSigningDetails(args.signingDetails); 16882 } else { 16883 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16884 } 16885 } catch (PackageParserException e) { 16886 res.setError("Failed collect during installPackageLI", e); 16887 return; 16888 } 16889 16890 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16891 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16892 Slog.w(TAG, "Instant app package " + pkg.packageName 16893 + " is not signed with at least APK Signature Scheme v2"); 16894 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16895 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16896 return; 16897 } 16898 16899 // Get rid of all references to package scan path via parser. 16900 pp = null; 16901 String oldCodePath = null; 16902 boolean systemApp = false; 16903 synchronized (mPackages) { 16904 // Check if installing already existing package 16905 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16906 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16907 if (pkg.mOriginalPackages != null 16908 && pkg.mOriginalPackages.contains(oldName) 16909 && mPackages.containsKey(oldName)) { 16910 // This package is derived from an original package, 16911 // and this device has been updating from that original 16912 // name. We must continue using the original name, so 16913 // rename the new package here. 16914 pkg.setPackageName(oldName); 16915 pkgName = pkg.packageName; 16916 replace = true; 16917 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16918 + oldName + " pkgName=" + pkgName); 16919 } else if (mPackages.containsKey(pkgName)) { 16920 // This package, under its official name, already exists 16921 // on the device; we should replace it. 16922 replace = true; 16923 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16924 } 16925 16926 // Child packages are installed through the parent package 16927 if (pkg.parentPackage != null) { 16928 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16929 "Package " + pkg.packageName + " is child of package " 16930 + pkg.parentPackage.parentPackage + ". Child packages " 16931 + "can be updated only through the parent package."); 16932 return; 16933 } 16934 16935 if (replace) { 16936 // Prevent apps opting out from runtime permissions 16937 PackageParser.Package oldPackage = mPackages.get(pkgName); 16938 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16939 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16940 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16941 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16942 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16943 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16944 + " doesn't support runtime permissions but the old" 16945 + " target SDK " + oldTargetSdk + " does."); 16946 return; 16947 } 16948 // Prevent persistent apps from being updated 16949 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16950 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16951 "Package " + oldPackage.packageName + " is a persistent app. " 16952 + "Persistent apps are not updateable."); 16953 return; 16954 } 16955 // Prevent apps from downgrading their targetSandbox. 16956 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16957 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16958 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16959 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16960 "Package " + pkg.packageName + " new target sandbox " 16961 + newTargetSandbox + " is incompatible with the previous value of" 16962 + oldTargetSandbox + "."); 16963 return; 16964 } 16965 16966 // Prevent installing of child packages 16967 if (oldPackage.parentPackage != null) { 16968 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16969 "Package " + pkg.packageName + " is child of package " 16970 + oldPackage.parentPackage + ". Child packages " 16971 + "can be updated only through the parent package."); 16972 return; 16973 } 16974 } 16975 } 16976 16977 PackageSetting ps = mSettings.mPackages.get(pkgName); 16978 if (ps != null) { 16979 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16980 16981 // Static shared libs have same package with different versions where 16982 // we internally use a synthetic package name to allow multiple versions 16983 // of the same package, therefore we need to compare signatures against 16984 // the package setting for the latest library version. 16985 PackageSetting signatureCheckPs = ps; 16986 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16987 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16988 if (libraryEntry != null) { 16989 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16990 } 16991 } 16992 16993 // Quick sanity check that we're signed correctly if updating; 16994 // we'll check this again later when scanning, but we want to 16995 // bail early here before tripping over redefined permissions. 16996 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16997 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16998 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16999 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17000 + pkg.packageName + " upgrade keys do not match the " 17001 + "previously installed version"); 17002 return; 17003 } 17004 } else { 17005 try { 17006 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17007 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17008 // We don't care about disabledPkgSetting on install for now. 17009 final boolean compatMatch = verifySignatures( 17010 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17011 compareRecover); 17012 // The new KeySets will be re-added later in the scanning process. 17013 if (compatMatch) { 17014 synchronized (mPackages) { 17015 ksms.removeAppKeySetDataLPw(pkg.packageName); 17016 } 17017 } 17018 } catch (PackageManagerException e) { 17019 res.setError(e.error, e.getMessage()); 17020 return; 17021 } 17022 } 17023 17024 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17025 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17026 systemApp = (ps.pkg.applicationInfo.flags & 17027 ApplicationInfo.FLAG_SYSTEM) != 0; 17028 } 17029 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17030 } 17031 17032 int N = pkg.permissions.size(); 17033 for (int i = N-1; i >= 0; i--) { 17034 final PackageParser.Permission perm = pkg.permissions.get(i); 17035 final BasePermission bp = 17036 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17037 17038 // Don't allow anyone but the system to define ephemeral permissions. 17039 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17040 && !systemApp) { 17041 Slog.w(TAG, "Non-System package " + pkg.packageName 17042 + " attempting to delcare ephemeral permission " 17043 + perm.info.name + "; Removing ephemeral."); 17044 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17045 } 17046 17047 // Check whether the newly-scanned package wants to define an already-defined perm 17048 if (bp != null) { 17049 // If the defining package is signed with our cert, it's okay. This 17050 // also includes the "updating the same package" case, of course. 17051 // "updating same package" could also involve key-rotation. 17052 final boolean sigsOk; 17053 final String sourcePackageName = bp.getSourcePackageName(); 17054 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17055 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17056 if (sourcePackageName.equals(pkg.packageName) 17057 && (ksms.shouldCheckUpgradeKeySetLocked( 17058 sourcePackageSetting, scanFlags))) { 17059 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17060 } else { 17061 sigsOk = compareSignatures( 17062 sourcePackageSetting.signatures.mSigningDetails.signatures, 17063 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 17064 } 17065 if (!sigsOk) { 17066 // If the owning package is the system itself, we log but allow 17067 // install to proceed; we fail the install on all other permission 17068 // redefinitions. 17069 if (!sourcePackageName.equals("android")) { 17070 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17071 + pkg.packageName + " attempting to redeclare permission " 17072 + perm.info.name + " already owned by " + sourcePackageName); 17073 res.origPermission = perm.info.name; 17074 res.origPackage = sourcePackageName; 17075 return; 17076 } else { 17077 Slog.w(TAG, "Package " + pkg.packageName 17078 + " attempting to redeclare system permission " 17079 + perm.info.name + "; ignoring new declaration"); 17080 pkg.permissions.remove(i); 17081 } 17082 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17083 // Prevent apps to change protection level to dangerous from any other 17084 // type as this would allow a privilege escalation where an app adds a 17085 // normal/signature permission in other app's group and later redefines 17086 // it as dangerous leading to the group auto-grant. 17087 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17088 == PermissionInfo.PROTECTION_DANGEROUS) { 17089 if (bp != null && !bp.isRuntime()) { 17090 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17091 + "non-runtime permission " + perm.info.name 17092 + " to runtime; keeping old protection level"); 17093 perm.info.protectionLevel = bp.getProtectionLevel(); 17094 } 17095 } 17096 } 17097 } 17098 } 17099 } 17100 17101 if (systemApp) { 17102 if (onExternal) { 17103 // Abort update; system app can't be replaced with app on sdcard 17104 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17105 "Cannot install updates to system apps on sdcard"); 17106 return; 17107 } else if (instantApp) { 17108 // Abort update; system app can't be replaced with an instant app 17109 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17110 "Cannot update a system app with an instant app"); 17111 return; 17112 } 17113 } 17114 17115 if (args.move != null) { 17116 // We did an in-place move, so dex is ready to roll 17117 scanFlags |= SCAN_NO_DEX; 17118 scanFlags |= SCAN_MOVE; 17119 17120 synchronized (mPackages) { 17121 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17122 if (ps == null) { 17123 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17124 "Missing settings for moved package " + pkgName); 17125 } 17126 17127 // We moved the entire application as-is, so bring over the 17128 // previously derived ABI information. 17129 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17130 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17131 } 17132 17133 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17134 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17135 scanFlags |= SCAN_NO_DEX; 17136 17137 try { 17138 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17139 args.abiOverride : pkg.cpuAbiOverride); 17140 final boolean extractNativeLibs = !pkg.isLibrary(); 17141 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17142 } catch (PackageManagerException pme) { 17143 Slog.e(TAG, "Error deriving application ABI", pme); 17144 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17145 return; 17146 } 17147 17148 // Shared libraries for the package need to be updated. 17149 synchronized (mPackages) { 17150 try { 17151 updateSharedLibrariesLPr(pkg, null); 17152 } catch (PackageManagerException e) { 17153 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17154 } 17155 } 17156 } 17157 17158 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17159 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17160 return; 17161 } 17162 17163 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17164 String apkPath = null; 17165 synchronized (mPackages) { 17166 // Note that if the attacker managed to skip verify setup, for example by tampering 17167 // with the package settings, upon reboot we will do full apk verification when 17168 // verity is not detected. 17169 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17170 if (ps != null && ps.isPrivileged()) { 17171 apkPath = pkg.baseCodePath; 17172 } 17173 } 17174 17175 if (apkPath != null) { 17176 final VerityUtils.SetupResult result = 17177 VerityUtils.generateApkVeritySetupData(apkPath); 17178 if (result.isOk()) { 17179 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17180 FileDescriptor fd = result.getUnownedFileDescriptor(); 17181 try { 17182 mInstaller.installApkVerity(apkPath, fd); 17183 } catch (InstallerException e) { 17184 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17185 "Failed to set up verity: " + e); 17186 return; 17187 } finally { 17188 IoUtils.closeQuietly(fd); 17189 } 17190 } else if (result.isFailed()) { 17191 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17192 return; 17193 } else { 17194 // Do nothing if verity is skipped. Will fall back to full apk verification on 17195 // reboot. 17196 } 17197 } 17198 } 17199 17200 if (!instantApp) { 17201 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17202 } else { 17203 if (DEBUG_DOMAIN_VERIFICATION) { 17204 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17205 } 17206 } 17207 17208 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17209 "installPackageLI")) { 17210 if (replace) { 17211 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17212 // Static libs have a synthetic package name containing the version 17213 // and cannot be updated as an update would get a new package name, 17214 // unless this is the exact same version code which is useful for 17215 // development. 17216 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17217 if (existingPkg != null && 17218 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17219 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17220 + "static-shared libs cannot be updated"); 17221 return; 17222 } 17223 } 17224 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17225 installerPackageName, res, args.installReason); 17226 } else { 17227 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17228 args.user, installerPackageName, volumeUuid, res, args.installReason); 17229 } 17230 } 17231 17232 // Prepare the application profiles for the new code paths. 17233 // This needs to be done before invoking dexopt so that any install-time profile 17234 // can be used for optimizations. 17235 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17236 17237 // Check whether we need to dexopt the app. 17238 // 17239 // NOTE: it is IMPORTANT to call dexopt: 17240 // - after doRename which will sync the package data from PackageParser.Package and its 17241 // corresponding ApplicationInfo. 17242 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17243 // uid of the application (pkg.applicationInfo.uid). 17244 // This update happens in place! 17245 // 17246 // We only need to dexopt if the package meets ALL of the following conditions: 17247 // 1) it is not forward locked. 17248 // 2) it is not on on an external ASEC container. 17249 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17250 // 17251 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17252 // complete, so we skip this step during installation. Instead, we'll take extra time 17253 // the first time the instant app starts. It's preferred to do it this way to provide 17254 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17255 // middle of running an instant app. The default behaviour can be overridden 17256 // via gservices. 17257 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17258 && !forwardLocked 17259 && !pkg.applicationInfo.isExternalAsec() 17260 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17261 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17262 17263 if (performDexopt) { 17264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17265 // Do not run PackageDexOptimizer through the local performDexOpt 17266 // method because `pkg` may not be in `mPackages` yet. 17267 // 17268 // Also, don't fail application installs if the dexopt step fails. 17269 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17270 REASON_INSTALL, 17271 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17272 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17273 null /* instructionSets */, 17274 getOrCreateCompilerPackageStats(pkg), 17275 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17276 dexoptOptions); 17277 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17278 } 17279 17280 // Notify BackgroundDexOptService that the package has been changed. 17281 // If this is an update of a package which used to fail to compile, 17282 // BackgroundDexOptService will remove it from its blacklist. 17283 // TODO: Layering violation 17284 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17285 17286 synchronized (mPackages) { 17287 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17288 if (ps != null) { 17289 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17290 ps.setUpdateAvailable(false /*updateAvailable*/); 17291 } 17292 17293 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17294 for (int i = 0; i < childCount; i++) { 17295 PackageParser.Package childPkg = pkg.childPackages.get(i); 17296 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17297 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17298 if (childPs != null) { 17299 childRes.newUsers = childPs.queryInstalledUsers( 17300 sUserManager.getUserIds(), true); 17301 } 17302 } 17303 17304 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17305 updateSequenceNumberLP(ps, res.newUsers); 17306 updateInstantAppInstallerLocked(pkgName); 17307 } 17308 } 17309 } 17310 17311 private void startIntentFilterVerifications(int userId, boolean replacing, 17312 PackageParser.Package pkg) { 17313 if (mIntentFilterVerifierComponent == null) { 17314 Slog.w(TAG, "No IntentFilter verification will not be done as " 17315 + "there is no IntentFilterVerifier available!"); 17316 return; 17317 } 17318 17319 final int verifierUid = getPackageUid( 17320 mIntentFilterVerifierComponent.getPackageName(), 17321 MATCH_DEBUG_TRIAGED_MISSING, 17322 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17323 17324 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17325 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17326 mHandler.sendMessage(msg); 17327 17328 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17329 for (int i = 0; i < childCount; i++) { 17330 PackageParser.Package childPkg = pkg.childPackages.get(i); 17331 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17332 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17333 mHandler.sendMessage(msg); 17334 } 17335 } 17336 17337 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17338 PackageParser.Package pkg) { 17339 int size = pkg.activities.size(); 17340 if (size == 0) { 17341 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17342 "No activity, so no need to verify any IntentFilter!"); 17343 return; 17344 } 17345 17346 final boolean hasDomainURLs = hasDomainURLs(pkg); 17347 if (!hasDomainURLs) { 17348 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17349 "No domain URLs, so no need to verify any IntentFilter!"); 17350 return; 17351 } 17352 17353 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17354 + " if any IntentFilter from the " + size 17355 + " Activities needs verification ..."); 17356 17357 int count = 0; 17358 final String packageName = pkg.packageName; 17359 17360 synchronized (mPackages) { 17361 // If this is a new install and we see that we've already run verification for this 17362 // package, we have nothing to do: it means the state was restored from backup. 17363 if (!replacing) { 17364 IntentFilterVerificationInfo ivi = 17365 mSettings.getIntentFilterVerificationLPr(packageName); 17366 if (ivi != null) { 17367 if (DEBUG_DOMAIN_VERIFICATION) { 17368 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17369 + ivi.getStatusString()); 17370 } 17371 return; 17372 } 17373 } 17374 17375 // If any filters need to be verified, then all need to be. 17376 boolean needToVerify = false; 17377 for (PackageParser.Activity a : pkg.activities) { 17378 for (ActivityIntentInfo filter : a.intents) { 17379 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17380 if (DEBUG_DOMAIN_VERIFICATION) { 17381 Slog.d(TAG, 17382 "Intent filter needs verification, so processing all filters"); 17383 } 17384 needToVerify = true; 17385 break; 17386 } 17387 } 17388 } 17389 17390 if (needToVerify) { 17391 final int verificationId = mIntentFilterVerificationToken++; 17392 for (PackageParser.Activity a : pkg.activities) { 17393 for (ActivityIntentInfo filter : a.intents) { 17394 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17395 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17396 "Verification needed for IntentFilter:" + filter.toString()); 17397 mIntentFilterVerifier.addOneIntentFilterVerification( 17398 verifierUid, userId, verificationId, filter, packageName); 17399 count++; 17400 } 17401 } 17402 } 17403 } 17404 } 17405 17406 if (count > 0) { 17407 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17408 + " IntentFilter verification" + (count > 1 ? "s" : "") 17409 + " for userId:" + userId); 17410 mIntentFilterVerifier.startVerifications(userId); 17411 } else { 17412 if (DEBUG_DOMAIN_VERIFICATION) { 17413 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17414 } 17415 } 17416 } 17417 17418 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17419 final ComponentName cn = filter.activity.getComponentName(); 17420 final String packageName = cn.getPackageName(); 17421 17422 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17423 packageName); 17424 if (ivi == null) { 17425 return true; 17426 } 17427 int status = ivi.getStatus(); 17428 switch (status) { 17429 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17430 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17431 return true; 17432 17433 default: 17434 // Nothing to do 17435 return false; 17436 } 17437 } 17438 17439 private static boolean isMultiArch(ApplicationInfo info) { 17440 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17441 } 17442 17443 private static boolean isExternal(PackageParser.Package pkg) { 17444 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17445 } 17446 17447 private static boolean isExternal(PackageSetting ps) { 17448 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17449 } 17450 17451 private static boolean isSystemApp(PackageParser.Package pkg) { 17452 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17453 } 17454 17455 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17456 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17457 } 17458 17459 private static boolean isOemApp(PackageParser.Package pkg) { 17460 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17461 } 17462 17463 private static boolean isVendorApp(PackageParser.Package pkg) { 17464 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17465 } 17466 17467 private static boolean isProductApp(PackageParser.Package pkg) { 17468 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17469 } 17470 17471 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17472 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17473 } 17474 17475 private static boolean isSystemApp(PackageSetting ps) { 17476 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17477 } 17478 17479 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17480 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17481 } 17482 17483 private int packageFlagsToInstallFlags(PackageSetting ps) { 17484 int installFlags = 0; 17485 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17486 // This existing package was an external ASEC install when we have 17487 // the external flag without a UUID 17488 installFlags |= PackageManager.INSTALL_EXTERNAL; 17489 } 17490 if (ps.isForwardLocked()) { 17491 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17492 } 17493 return installFlags; 17494 } 17495 17496 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17497 if (isExternal(pkg)) { 17498 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17499 return mSettings.getExternalVersion(); 17500 } else { 17501 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17502 } 17503 } else { 17504 return mSettings.getInternalVersion(); 17505 } 17506 } 17507 17508 private void deleteTempPackageFiles() { 17509 final FilenameFilter filter = new FilenameFilter() { 17510 public boolean accept(File dir, String name) { 17511 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17512 } 17513 }; 17514 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17515 file.delete(); 17516 } 17517 } 17518 17519 @Override 17520 public void deletePackageAsUser(String packageName, int versionCode, 17521 IPackageDeleteObserver observer, int userId, int flags) { 17522 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17523 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17524 } 17525 17526 @Override 17527 public void deletePackageVersioned(VersionedPackage versionedPackage, 17528 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17529 final int callingUid = Binder.getCallingUid(); 17530 mContext.enforceCallingOrSelfPermission( 17531 android.Manifest.permission.DELETE_PACKAGES, null); 17532 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17533 Preconditions.checkNotNull(versionedPackage); 17534 Preconditions.checkNotNull(observer); 17535 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17536 PackageManager.VERSION_CODE_HIGHEST, 17537 Long.MAX_VALUE, "versionCode must be >= -1"); 17538 17539 final String packageName = versionedPackage.getPackageName(); 17540 final long versionCode = versionedPackage.getLongVersionCode(); 17541 final String internalPackageName; 17542 synchronized (mPackages) { 17543 // Normalize package name to handle renamed packages and static libs 17544 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17545 } 17546 17547 final int uid = Binder.getCallingUid(); 17548 if (!isOrphaned(internalPackageName) 17549 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17550 try { 17551 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17552 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17553 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17554 observer.onUserActionRequired(intent); 17555 } catch (RemoteException re) { 17556 } 17557 return; 17558 } 17559 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17560 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17561 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17562 mContext.enforceCallingOrSelfPermission( 17563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17564 "deletePackage for user " + userId); 17565 } 17566 17567 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17568 try { 17569 observer.onPackageDeleted(packageName, 17570 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17571 } catch (RemoteException re) { 17572 } 17573 return; 17574 } 17575 17576 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17577 try { 17578 observer.onPackageDeleted(packageName, 17579 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17580 } catch (RemoteException re) { 17581 } 17582 return; 17583 } 17584 17585 if (DEBUG_REMOVE) { 17586 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17587 + " deleteAllUsers: " + deleteAllUsers + " version=" 17588 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17589 ? "VERSION_CODE_HIGHEST" : versionCode)); 17590 } 17591 // Queue up an async operation since the package deletion may take a little while. 17592 mHandler.post(new Runnable() { 17593 public void run() { 17594 mHandler.removeCallbacks(this); 17595 int returnCode; 17596 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17597 boolean doDeletePackage = true; 17598 if (ps != null) { 17599 final boolean targetIsInstantApp = 17600 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17601 doDeletePackage = !targetIsInstantApp 17602 || canViewInstantApps; 17603 } 17604 if (doDeletePackage) { 17605 if (!deleteAllUsers) { 17606 returnCode = deletePackageX(internalPackageName, versionCode, 17607 userId, deleteFlags); 17608 } else { 17609 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17610 internalPackageName, users); 17611 // If nobody is blocking uninstall, proceed with delete for all users 17612 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17613 returnCode = deletePackageX(internalPackageName, versionCode, 17614 userId, deleteFlags); 17615 } else { 17616 // Otherwise uninstall individually for users with blockUninstalls=false 17617 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17618 for (int userId : users) { 17619 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17620 returnCode = deletePackageX(internalPackageName, versionCode, 17621 userId, userFlags); 17622 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17623 Slog.w(TAG, "Package delete failed for user " + userId 17624 + ", returnCode " + returnCode); 17625 } 17626 } 17627 } 17628 // The app has only been marked uninstalled for certain users. 17629 // We still need to report that delete was blocked 17630 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17631 } 17632 } 17633 } else { 17634 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17635 } 17636 try { 17637 observer.onPackageDeleted(packageName, returnCode, null); 17638 } catch (RemoteException e) { 17639 Log.i(TAG, "Observer no longer exists."); 17640 } //end catch 17641 } //end run 17642 }); 17643 } 17644 17645 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17646 if (pkg.staticSharedLibName != null) { 17647 return pkg.manifestPackageName; 17648 } 17649 return pkg.packageName; 17650 } 17651 17652 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17653 // Handle renamed packages 17654 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17655 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17656 17657 // Is this a static library? 17658 LongSparseArray<SharedLibraryEntry> versionedLib = 17659 mStaticLibsByDeclaringPackage.get(packageName); 17660 if (versionedLib == null || versionedLib.size() <= 0) { 17661 return packageName; 17662 } 17663 17664 // Figure out which lib versions the caller can see 17665 LongSparseLongArray versionsCallerCanSee = null; 17666 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17667 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17668 && callingAppId != Process.ROOT_UID) { 17669 versionsCallerCanSee = new LongSparseLongArray(); 17670 String libName = versionedLib.valueAt(0).info.getName(); 17671 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17672 if (uidPackages != null) { 17673 for (String uidPackage : uidPackages) { 17674 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17675 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17676 if (libIdx >= 0) { 17677 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17678 versionsCallerCanSee.append(libVersion, libVersion); 17679 } 17680 } 17681 } 17682 } 17683 17684 // Caller can see nothing - done 17685 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17686 return packageName; 17687 } 17688 17689 // Find the version the caller can see and the app version code 17690 SharedLibraryEntry highestVersion = null; 17691 final int versionCount = versionedLib.size(); 17692 for (int i = 0; i < versionCount; i++) { 17693 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17694 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17695 libEntry.info.getLongVersion()) < 0) { 17696 continue; 17697 } 17698 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17699 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17700 if (libVersionCode == versionCode) { 17701 return libEntry.apk; 17702 } 17703 } else if (highestVersion == null) { 17704 highestVersion = libEntry; 17705 } else if (libVersionCode > highestVersion.info 17706 .getDeclaringPackage().getLongVersionCode()) { 17707 highestVersion = libEntry; 17708 } 17709 } 17710 17711 if (highestVersion != null) { 17712 return highestVersion.apk; 17713 } 17714 17715 return packageName; 17716 } 17717 17718 boolean isCallerVerifier(int callingUid) { 17719 final int callingUserId = UserHandle.getUserId(callingUid); 17720 return mRequiredVerifierPackage != null && 17721 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17722 } 17723 17724 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17725 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17726 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17727 return true; 17728 } 17729 final int callingUserId = UserHandle.getUserId(callingUid); 17730 // If the caller installed the pkgName, then allow it to silently uninstall. 17731 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17732 return true; 17733 } 17734 17735 // Allow package verifier to silently uninstall. 17736 if (mRequiredVerifierPackage != null && 17737 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17738 return true; 17739 } 17740 17741 // Allow package uninstaller to silently uninstall. 17742 if (mRequiredUninstallerPackage != null && 17743 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17744 return true; 17745 } 17746 17747 // Allow storage manager to silently uninstall. 17748 if (mStorageManagerPackage != null && 17749 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17750 return true; 17751 } 17752 17753 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17754 // uninstall for device owner provisioning. 17755 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17756 == PERMISSION_GRANTED) { 17757 return true; 17758 } 17759 17760 return false; 17761 } 17762 17763 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17764 int[] result = EMPTY_INT_ARRAY; 17765 for (int userId : userIds) { 17766 if (getBlockUninstallForUser(packageName, userId)) { 17767 result = ArrayUtils.appendInt(result, userId); 17768 } 17769 } 17770 return result; 17771 } 17772 17773 @Override 17774 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17775 final int callingUid = Binder.getCallingUid(); 17776 if (getInstantAppPackageName(callingUid) != null 17777 && !isCallerSameApp(packageName, callingUid)) { 17778 return false; 17779 } 17780 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17781 } 17782 17783 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17784 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17785 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17786 try { 17787 if (dpm != null) { 17788 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17789 /* callingUserOnly =*/ false); 17790 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17791 : deviceOwnerComponentName.getPackageName(); 17792 // Does the package contains the device owner? 17793 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17794 // this check is probably not needed, since DO should be registered as a device 17795 // admin on some user too. (Original bug for this: b/17657954) 17796 if (packageName.equals(deviceOwnerPackageName)) { 17797 return true; 17798 } 17799 // Does it contain a device admin for any user? 17800 int[] users; 17801 if (userId == UserHandle.USER_ALL) { 17802 users = sUserManager.getUserIds(); 17803 } else { 17804 users = new int[]{userId}; 17805 } 17806 for (int i = 0; i < users.length; ++i) { 17807 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17808 return true; 17809 } 17810 } 17811 } 17812 } catch (RemoteException e) { 17813 } 17814 return false; 17815 } 17816 17817 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17818 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17819 } 17820 17821 /** 17822 * This method is an internal method that could be get invoked either 17823 * to delete an installed package or to clean up a failed installation. 17824 * After deleting an installed package, a broadcast is sent to notify any 17825 * listeners that the package has been removed. For cleaning up a failed 17826 * installation, the broadcast is not necessary since the package's 17827 * installation wouldn't have sent the initial broadcast either 17828 * The key steps in deleting a package are 17829 * deleting the package information in internal structures like mPackages, 17830 * deleting the packages base directories through installd 17831 * updating mSettings to reflect current status 17832 * persisting settings for later use 17833 * sending a broadcast if necessary 17834 */ 17835 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17836 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17837 final boolean res; 17838 17839 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17840 ? UserHandle.USER_ALL : userId; 17841 17842 if (isPackageDeviceAdmin(packageName, removeUser)) { 17843 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17844 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17845 } 17846 17847 PackageSetting uninstalledPs = null; 17848 PackageParser.Package pkg = null; 17849 17850 // for the uninstall-updates case and restricted profiles, remember the per- 17851 // user handle installed state 17852 int[] allUsers; 17853 synchronized (mPackages) { 17854 uninstalledPs = mSettings.mPackages.get(packageName); 17855 if (uninstalledPs == null) { 17856 Slog.w(TAG, "Not removing non-existent package " + packageName); 17857 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17858 } 17859 17860 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17861 && uninstalledPs.versionCode != versionCode) { 17862 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17863 + uninstalledPs.versionCode + " != " + versionCode); 17864 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17865 } 17866 17867 // Static shared libs can be declared by any package, so let us not 17868 // allow removing a package if it provides a lib others depend on. 17869 pkg = mPackages.get(packageName); 17870 17871 allUsers = sUserManager.getUserIds(); 17872 17873 if (pkg != null && pkg.staticSharedLibName != null) { 17874 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17875 pkg.staticSharedLibVersion); 17876 if (libEntry != null) { 17877 for (int currUserId : allUsers) { 17878 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17879 continue; 17880 } 17881 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17882 libEntry.info, 0, currUserId); 17883 if (!ArrayUtils.isEmpty(libClientPackages)) { 17884 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17885 + " hosting lib " + libEntry.info.getName() + " version " 17886 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17887 + " for user " + currUserId); 17888 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17889 } 17890 } 17891 } 17892 } 17893 17894 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17895 } 17896 17897 final int freezeUser; 17898 if (isUpdatedSystemApp(uninstalledPs) 17899 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17900 // We're downgrading a system app, which will apply to all users, so 17901 // freeze them all during the downgrade 17902 freezeUser = UserHandle.USER_ALL; 17903 } else { 17904 freezeUser = removeUser; 17905 } 17906 17907 synchronized (mInstallLock) { 17908 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17909 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17910 deleteFlags, "deletePackageX")) { 17911 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17912 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17913 } 17914 synchronized (mPackages) { 17915 if (res) { 17916 if (pkg != null) { 17917 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17918 } 17919 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17920 updateInstantAppInstallerLocked(packageName); 17921 } 17922 } 17923 } 17924 17925 if (res) { 17926 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17927 info.sendPackageRemovedBroadcasts(killApp); 17928 info.sendSystemPackageUpdatedBroadcasts(); 17929 info.sendSystemPackageAppearedBroadcasts(); 17930 } 17931 // Force a gc here. 17932 Runtime.getRuntime().gc(); 17933 // Delete the resources here after sending the broadcast to let 17934 // other processes clean up before deleting resources. 17935 if (info.args != null) { 17936 synchronized (mInstallLock) { 17937 info.args.doPostDeleteLI(true); 17938 } 17939 } 17940 17941 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17942 } 17943 17944 static class PackageRemovedInfo { 17945 final PackageSender packageSender; 17946 String removedPackage; 17947 String installerPackageName; 17948 int uid = -1; 17949 int removedAppId = -1; 17950 int[] origUsers; 17951 int[] removedUsers = null; 17952 int[] broadcastUsers = null; 17953 int[] instantUserIds = null; 17954 SparseArray<Integer> installReasons; 17955 boolean isRemovedPackageSystemUpdate = false; 17956 boolean isUpdate; 17957 boolean dataRemoved; 17958 boolean removedForAllUsers; 17959 boolean isStaticSharedLib; 17960 // Clean up resources deleted packages. 17961 InstallArgs args = null; 17962 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17963 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17964 17965 PackageRemovedInfo(PackageSender packageSender) { 17966 this.packageSender = packageSender; 17967 } 17968 17969 void sendPackageRemovedBroadcasts(boolean killApp) { 17970 sendPackageRemovedBroadcastInternal(killApp); 17971 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17972 for (int i = 0; i < childCount; i++) { 17973 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17974 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17975 } 17976 } 17977 17978 void sendSystemPackageUpdatedBroadcasts() { 17979 if (isRemovedPackageSystemUpdate) { 17980 sendSystemPackageUpdatedBroadcastsInternal(); 17981 final int childCount = (removedChildPackages != null) 17982 ? removedChildPackages.size() : 0; 17983 for (int i = 0; i < childCount; i++) { 17984 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17985 if (childInfo.isRemovedPackageSystemUpdate) { 17986 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17987 } 17988 } 17989 } 17990 } 17991 17992 void sendSystemPackageAppearedBroadcasts() { 17993 final int packageCount = (appearedChildPackages != null) 17994 ? appearedChildPackages.size() : 0; 17995 for (int i = 0; i < packageCount; i++) { 17996 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17997 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17998 true /*sendBootCompleted*/, false /*startReceiver*/, 17999 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18000 } 18001 } 18002 18003 private void sendSystemPackageUpdatedBroadcastsInternal() { 18004 Bundle extras = new Bundle(2); 18005 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18006 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18007 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18008 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18009 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18010 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18011 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18012 null, null, 0, removedPackage, null, null, null); 18013 if (installerPackageName != null) { 18014 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18015 removedPackage, extras, 0 /*flags*/, 18016 installerPackageName, null, null, null); 18017 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18018 removedPackage, extras, 0 /*flags*/, 18019 installerPackageName, null, null, null); 18020 } 18021 } 18022 18023 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18024 // Don't send static shared library removal broadcasts as these 18025 // libs are visible only the the apps that depend on them an one 18026 // cannot remove the library if it has a dependency. 18027 if (isStaticSharedLib) { 18028 return; 18029 } 18030 Bundle extras = new Bundle(2); 18031 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18032 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18033 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18034 if (isUpdate || isRemovedPackageSystemUpdate) { 18035 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18036 } 18037 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18038 if (removedPackage != null) { 18039 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18040 removedPackage, extras, 0, null /*targetPackage*/, null, 18041 broadcastUsers, instantUserIds); 18042 if (installerPackageName != null) { 18043 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18044 removedPackage, extras, 0 /*flags*/, 18045 installerPackageName, null, broadcastUsers, instantUserIds); 18046 } 18047 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18048 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18049 removedPackage, extras, 18050 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18051 null, null, broadcastUsers, instantUserIds); 18052 packageSender.notifyPackageRemoved(removedPackage); 18053 } 18054 } 18055 if (removedAppId >= 0) { 18056 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18057 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18058 null, null, broadcastUsers, instantUserIds); 18059 } 18060 } 18061 18062 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18063 removedUsers = userIds; 18064 if (removedUsers == null) { 18065 broadcastUsers = null; 18066 return; 18067 } 18068 18069 broadcastUsers = EMPTY_INT_ARRAY; 18070 instantUserIds = EMPTY_INT_ARRAY; 18071 for (int i = userIds.length - 1; i >= 0; --i) { 18072 final int userId = userIds[i]; 18073 if (deletedPackageSetting.getInstantApp(userId)) { 18074 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18075 } else { 18076 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18077 } 18078 } 18079 } 18080 } 18081 18082 /* 18083 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18084 * flag is not set, the data directory is removed as well. 18085 * make sure this flag is set for partially installed apps. If not its meaningless to 18086 * delete a partially installed application. 18087 */ 18088 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18089 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18090 String packageName = ps.name; 18091 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18092 // Retrieve object to delete permissions for shared user later on 18093 final PackageParser.Package deletedPkg; 18094 final PackageSetting deletedPs; 18095 // reader 18096 synchronized (mPackages) { 18097 deletedPkg = mPackages.get(packageName); 18098 deletedPs = mSettings.mPackages.get(packageName); 18099 if (outInfo != null) { 18100 outInfo.removedPackage = packageName; 18101 outInfo.installerPackageName = ps.installerPackageName; 18102 outInfo.isStaticSharedLib = deletedPkg != null 18103 && deletedPkg.staticSharedLibName != null; 18104 outInfo.populateUsers(deletedPs == null ? null 18105 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18106 } 18107 } 18108 18109 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18110 18111 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18112 final PackageParser.Package resolvedPkg; 18113 if (deletedPkg != null) { 18114 resolvedPkg = deletedPkg; 18115 } else { 18116 // We don't have a parsed package when it lives on an ejected 18117 // adopted storage device, so fake something together 18118 resolvedPkg = new PackageParser.Package(ps.name); 18119 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18120 } 18121 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18122 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18123 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18124 if (outInfo != null) { 18125 outInfo.dataRemoved = true; 18126 } 18127 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18128 } 18129 18130 int removedAppId = -1; 18131 18132 // writer 18133 synchronized (mPackages) { 18134 boolean installedStateChanged = false; 18135 if (deletedPs != null) { 18136 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18137 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18138 clearDefaultBrowserIfNeeded(packageName); 18139 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18140 removedAppId = mSettings.removePackageLPw(packageName); 18141 if (outInfo != null) { 18142 outInfo.removedAppId = removedAppId; 18143 } 18144 mPermissionManager.updatePermissions( 18145 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18146 if (deletedPs.sharedUser != null) { 18147 // Remove permissions associated with package. Since runtime 18148 // permissions are per user we have to kill the removed package 18149 // or packages running under the shared user of the removed 18150 // package if revoking the permissions requested only by the removed 18151 // package is successful and this causes a change in gids. 18152 for (int userId : UserManagerService.getInstance().getUserIds()) { 18153 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18154 userId); 18155 if (userIdToKill == UserHandle.USER_ALL 18156 || userIdToKill >= UserHandle.USER_SYSTEM) { 18157 // If gids changed for this user, kill all affected packages. 18158 mHandler.post(new Runnable() { 18159 @Override 18160 public void run() { 18161 // This has to happen with no lock held. 18162 killApplication(deletedPs.name, deletedPs.appId, 18163 KILL_APP_REASON_GIDS_CHANGED); 18164 } 18165 }); 18166 break; 18167 } 18168 } 18169 } 18170 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18171 } 18172 // make sure to preserve per-user disabled state if this removal was just 18173 // a downgrade of a system app to the factory package 18174 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18175 if (DEBUG_REMOVE) { 18176 Slog.d(TAG, "Propagating install state across downgrade"); 18177 } 18178 for (int userId : allUserHandles) { 18179 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18180 if (DEBUG_REMOVE) { 18181 Slog.d(TAG, " user " + userId + " => " + installed); 18182 } 18183 if (installed != ps.getInstalled(userId)) { 18184 installedStateChanged = true; 18185 } 18186 ps.setInstalled(installed, userId); 18187 } 18188 } 18189 } 18190 // can downgrade to reader 18191 if (writeSettings) { 18192 // Save settings now 18193 mSettings.writeLPr(); 18194 } 18195 if (installedStateChanged) { 18196 mSettings.writeKernelMappingLPr(ps); 18197 } 18198 } 18199 if (removedAppId != -1) { 18200 // A user ID was deleted here. Go through all users and remove it 18201 // from KeyStore. 18202 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18203 } 18204 } 18205 18206 static boolean locationIsPrivileged(String path) { 18207 try { 18208 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18209 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18210 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18211 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18212 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18213 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18214 } catch (IOException e) { 18215 Slog.e(TAG, "Unable to access code path " + path); 18216 } 18217 return false; 18218 } 18219 18220 static boolean locationIsOem(String path) { 18221 try { 18222 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18223 } catch (IOException e) { 18224 Slog.e(TAG, "Unable to access code path " + path); 18225 } 18226 return false; 18227 } 18228 18229 static boolean locationIsVendor(String path) { 18230 try { 18231 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18232 } catch (IOException e) { 18233 Slog.e(TAG, "Unable to access code path " + path); 18234 } 18235 return false; 18236 } 18237 18238 static boolean locationIsProduct(String path) { 18239 try { 18240 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18241 } catch (IOException e) { 18242 Slog.e(TAG, "Unable to access code path " + path); 18243 } 18244 return false; 18245 } 18246 18247 /* 18248 * Tries to delete system package. 18249 */ 18250 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18251 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18252 boolean writeSettings) { 18253 if (deletedPs.parentPackageName != null) { 18254 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18255 return false; 18256 } 18257 18258 final boolean applyUserRestrictions 18259 = (allUserHandles != null) && (outInfo.origUsers != null); 18260 final PackageSetting disabledPs; 18261 // Confirm if the system package has been updated 18262 // An updated system app can be deleted. This will also have to restore 18263 // the system pkg from system partition 18264 // reader 18265 synchronized (mPackages) { 18266 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18267 } 18268 18269 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18270 + " disabledPs=" + disabledPs); 18271 18272 if (disabledPs == null) { 18273 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18274 return false; 18275 } else if (DEBUG_REMOVE) { 18276 Slog.d(TAG, "Deleting system pkg from data partition"); 18277 } 18278 18279 if (DEBUG_REMOVE) { 18280 if (applyUserRestrictions) { 18281 Slog.d(TAG, "Remembering install states:"); 18282 for (int userId : allUserHandles) { 18283 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18284 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18285 } 18286 } 18287 } 18288 18289 // Delete the updated package 18290 outInfo.isRemovedPackageSystemUpdate = true; 18291 if (outInfo.removedChildPackages != null) { 18292 final int childCount = (deletedPs.childPackageNames != null) 18293 ? deletedPs.childPackageNames.size() : 0; 18294 for (int i = 0; i < childCount; i++) { 18295 String childPackageName = deletedPs.childPackageNames.get(i); 18296 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18297 .contains(childPackageName)) { 18298 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18299 childPackageName); 18300 if (childInfo != null) { 18301 childInfo.isRemovedPackageSystemUpdate = true; 18302 } 18303 } 18304 } 18305 } 18306 18307 if (disabledPs.versionCode < deletedPs.versionCode) { 18308 // Delete data for downgrades 18309 flags &= ~PackageManager.DELETE_KEEP_DATA; 18310 } else { 18311 // Preserve data by setting flag 18312 flags |= PackageManager.DELETE_KEEP_DATA; 18313 } 18314 18315 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18316 outInfo, writeSettings, disabledPs.pkg); 18317 if (!ret) { 18318 return false; 18319 } 18320 18321 // writer 18322 synchronized (mPackages) { 18323 // NOTE: The system package always needs to be enabled; even if it's for 18324 // a compressed stub. If we don't, installing the system package fails 18325 // during scan [scanning checks the disabled packages]. We will reverse 18326 // this later, after we've "installed" the stub. 18327 // Reinstate the old system package 18328 enableSystemPackageLPw(disabledPs.pkg); 18329 // Remove any native libraries from the upgraded package. 18330 removeNativeBinariesLI(deletedPs); 18331 } 18332 18333 // Install the system package 18334 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18335 try { 18336 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18337 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18338 } catch (PackageManagerException e) { 18339 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18340 + e.getMessage()); 18341 return false; 18342 } finally { 18343 if (disabledPs.pkg.isStub) { 18344 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18345 } 18346 } 18347 return true; 18348 } 18349 18350 /** 18351 * Installs a package that's already on the system partition. 18352 */ 18353 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18354 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18355 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18356 throws PackageManagerException { 18357 @ParseFlags int parseFlags = 18358 mDefParseFlags 18359 | PackageParser.PARSE_MUST_BE_APK 18360 | PackageParser.PARSE_IS_SYSTEM_DIR; 18361 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18362 if (isPrivileged || locationIsPrivileged(codePathString)) { 18363 scanFlags |= SCAN_AS_PRIVILEGED; 18364 } 18365 if (locationIsOem(codePathString)) { 18366 scanFlags |= SCAN_AS_OEM; 18367 } 18368 if (locationIsVendor(codePathString)) { 18369 scanFlags |= SCAN_AS_VENDOR; 18370 } 18371 if (locationIsProduct(codePathString)) { 18372 scanFlags |= SCAN_AS_PRODUCT; 18373 } 18374 18375 final File codePath = new File(codePathString); 18376 final PackageParser.Package pkg = 18377 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18378 18379 try { 18380 // update shared libraries for the newly re-installed system package 18381 updateSharedLibrariesLPr(pkg, null); 18382 } catch (PackageManagerException e) { 18383 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18384 } 18385 18386 prepareAppDataAfterInstallLIF(pkg); 18387 18388 // writer 18389 synchronized (mPackages) { 18390 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18391 18392 // Propagate the permissions state as we do not want to drop on the floor 18393 // runtime permissions. The update permissions method below will take 18394 // care of removing obsolete permissions and grant install permissions. 18395 if (origPermissionState != null) { 18396 ps.getPermissionsState().copyFrom(origPermissionState); 18397 } 18398 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18399 mPermissionCallback); 18400 18401 final boolean applyUserRestrictions 18402 = (allUserHandles != null) && (origUserHandles != null); 18403 if (applyUserRestrictions) { 18404 boolean installedStateChanged = false; 18405 if (DEBUG_REMOVE) { 18406 Slog.d(TAG, "Propagating install state across reinstall"); 18407 } 18408 for (int userId : allUserHandles) { 18409 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18410 if (DEBUG_REMOVE) { 18411 Slog.d(TAG, " user " + userId + " => " + installed); 18412 } 18413 if (installed != ps.getInstalled(userId)) { 18414 installedStateChanged = true; 18415 } 18416 ps.setInstalled(installed, userId); 18417 18418 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18419 } 18420 // Regardless of writeSettings we need to ensure that this restriction 18421 // state propagation is persisted 18422 mSettings.writeAllUsersPackageRestrictionsLPr(); 18423 if (installedStateChanged) { 18424 mSettings.writeKernelMappingLPr(ps); 18425 } 18426 } 18427 // can downgrade to reader here 18428 if (writeSettings) { 18429 mSettings.writeLPr(); 18430 } 18431 } 18432 return pkg; 18433 } 18434 18435 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18436 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18437 PackageRemovedInfo outInfo, boolean writeSettings, 18438 PackageParser.Package replacingPackage) { 18439 synchronized (mPackages) { 18440 if (outInfo != null) { 18441 outInfo.uid = ps.appId; 18442 } 18443 18444 if (outInfo != null && outInfo.removedChildPackages != null) { 18445 final int childCount = (ps.childPackageNames != null) 18446 ? ps.childPackageNames.size() : 0; 18447 for (int i = 0; i < childCount; i++) { 18448 String childPackageName = ps.childPackageNames.get(i); 18449 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18450 if (childPs == null) { 18451 return false; 18452 } 18453 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18454 childPackageName); 18455 if (childInfo != null) { 18456 childInfo.uid = childPs.appId; 18457 } 18458 } 18459 } 18460 } 18461 18462 // Delete package data from internal structures and also remove data if flag is set 18463 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18464 18465 // Delete the child packages data 18466 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18467 for (int i = 0; i < childCount; i++) { 18468 PackageSetting childPs; 18469 synchronized (mPackages) { 18470 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18471 } 18472 if (childPs != null) { 18473 PackageRemovedInfo childOutInfo = (outInfo != null 18474 && outInfo.removedChildPackages != null) 18475 ? outInfo.removedChildPackages.get(childPs.name) : null; 18476 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18477 && (replacingPackage != null 18478 && !replacingPackage.hasChildPackage(childPs.name)) 18479 ? flags & ~DELETE_KEEP_DATA : flags; 18480 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18481 deleteFlags, writeSettings); 18482 } 18483 } 18484 18485 // Delete application code and resources only for parent packages 18486 if (ps.parentPackageName == null) { 18487 if (deleteCodeAndResources && (outInfo != null)) { 18488 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18489 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18490 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18491 } 18492 } 18493 18494 return true; 18495 } 18496 18497 @Override 18498 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18499 int userId) { 18500 mContext.enforceCallingOrSelfPermission( 18501 android.Manifest.permission.DELETE_PACKAGES, null); 18502 synchronized (mPackages) { 18503 // Cannot block uninstall of static shared libs as they are 18504 // considered a part of the using app (emulating static linking). 18505 // Also static libs are installed always on internal storage. 18506 PackageParser.Package pkg = mPackages.get(packageName); 18507 if (pkg != null && pkg.staticSharedLibName != null) { 18508 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18509 + " providing static shared library: " + pkg.staticSharedLibName); 18510 return false; 18511 } 18512 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18513 mSettings.writePackageRestrictionsLPr(userId); 18514 } 18515 return true; 18516 } 18517 18518 @Override 18519 public boolean getBlockUninstallForUser(String packageName, int userId) { 18520 synchronized (mPackages) { 18521 final PackageSetting ps = mSettings.mPackages.get(packageName); 18522 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18523 return false; 18524 } 18525 return mSettings.getBlockUninstallLPr(userId, packageName); 18526 } 18527 } 18528 18529 @Override 18530 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18531 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18532 synchronized (mPackages) { 18533 PackageSetting ps = mSettings.mPackages.get(packageName); 18534 if (ps == null) { 18535 Log.w(TAG, "Package doesn't exist: " + packageName); 18536 return false; 18537 } 18538 if (systemUserApp) { 18539 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18540 } else { 18541 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18542 } 18543 mSettings.writeLPr(); 18544 } 18545 return true; 18546 } 18547 18548 /* 18549 * This method handles package deletion in general 18550 */ 18551 private boolean deletePackageLIF(String packageName, UserHandle user, 18552 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18553 PackageRemovedInfo outInfo, boolean writeSettings, 18554 PackageParser.Package replacingPackage) { 18555 if (packageName == null) { 18556 Slog.w(TAG, "Attempt to delete null packageName."); 18557 return false; 18558 } 18559 18560 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18561 18562 PackageSetting ps; 18563 synchronized (mPackages) { 18564 ps = mSettings.mPackages.get(packageName); 18565 if (ps == null) { 18566 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18567 return false; 18568 } 18569 18570 if (ps.parentPackageName != null && (!isSystemApp(ps) 18571 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18572 if (DEBUG_REMOVE) { 18573 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18574 + ((user == null) ? UserHandle.USER_ALL : user)); 18575 } 18576 final int removedUserId = (user != null) ? user.getIdentifier() 18577 : UserHandle.USER_ALL; 18578 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18579 return false; 18580 } 18581 markPackageUninstalledForUserLPw(ps, user); 18582 scheduleWritePackageRestrictionsLocked(user); 18583 return true; 18584 } 18585 } 18586 18587 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18588 && user.getIdentifier() != UserHandle.USER_ALL)) { 18589 // The caller is asking that the package only be deleted for a single 18590 // user. To do this, we just mark its uninstalled state and delete 18591 // its data. If this is a system app, we only allow this to happen if 18592 // they have set the special DELETE_SYSTEM_APP which requests different 18593 // semantics than normal for uninstalling system apps. 18594 markPackageUninstalledForUserLPw(ps, user); 18595 18596 if (!isSystemApp(ps)) { 18597 // Do not uninstall the APK if an app should be cached 18598 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18599 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18600 // Other user still have this package installed, so all 18601 // we need to do is clear this user's data and save that 18602 // it is uninstalled. 18603 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18604 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18605 return false; 18606 } 18607 scheduleWritePackageRestrictionsLocked(user); 18608 return true; 18609 } else { 18610 // We need to set it back to 'installed' so the uninstall 18611 // broadcasts will be sent correctly. 18612 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18613 ps.setInstalled(true, user.getIdentifier()); 18614 mSettings.writeKernelMappingLPr(ps); 18615 } 18616 } else { 18617 // This is a system app, so we assume that the 18618 // other users still have this package installed, so all 18619 // we need to do is clear this user's data and save that 18620 // it is uninstalled. 18621 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18622 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18623 return false; 18624 } 18625 scheduleWritePackageRestrictionsLocked(user); 18626 return true; 18627 } 18628 } 18629 18630 // If we are deleting a composite package for all users, keep track 18631 // of result for each child. 18632 if (ps.childPackageNames != null && outInfo != null) { 18633 synchronized (mPackages) { 18634 final int childCount = ps.childPackageNames.size(); 18635 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18636 for (int i = 0; i < childCount; i++) { 18637 String childPackageName = ps.childPackageNames.get(i); 18638 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18639 childInfo.removedPackage = childPackageName; 18640 childInfo.installerPackageName = ps.installerPackageName; 18641 outInfo.removedChildPackages.put(childPackageName, childInfo); 18642 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18643 if (childPs != null) { 18644 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18645 } 18646 } 18647 } 18648 } 18649 18650 boolean ret = false; 18651 if (isSystemApp(ps)) { 18652 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18653 // When an updated system application is deleted we delete the existing resources 18654 // as well and fall back to existing code in system partition 18655 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18656 } else { 18657 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18658 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18659 outInfo, writeSettings, replacingPackage); 18660 } 18661 18662 // Take a note whether we deleted the package for all users 18663 if (outInfo != null) { 18664 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18665 if (outInfo.removedChildPackages != null) { 18666 synchronized (mPackages) { 18667 final int childCount = outInfo.removedChildPackages.size(); 18668 for (int i = 0; i < childCount; i++) { 18669 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18670 if (childInfo != null) { 18671 childInfo.removedForAllUsers = mPackages.get( 18672 childInfo.removedPackage) == null; 18673 } 18674 } 18675 } 18676 } 18677 // If we uninstalled an update to a system app there may be some 18678 // child packages that appeared as they are declared in the system 18679 // app but were not declared in the update. 18680 if (isSystemApp(ps)) { 18681 synchronized (mPackages) { 18682 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18683 final int childCount = (updatedPs.childPackageNames != null) 18684 ? updatedPs.childPackageNames.size() : 0; 18685 for (int i = 0; i < childCount; i++) { 18686 String childPackageName = updatedPs.childPackageNames.get(i); 18687 if (outInfo.removedChildPackages == null 18688 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18689 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18690 if (childPs == null) { 18691 continue; 18692 } 18693 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18694 installRes.name = childPackageName; 18695 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18696 installRes.pkg = mPackages.get(childPackageName); 18697 installRes.uid = childPs.pkg.applicationInfo.uid; 18698 if (outInfo.appearedChildPackages == null) { 18699 outInfo.appearedChildPackages = new ArrayMap<>(); 18700 } 18701 outInfo.appearedChildPackages.put(childPackageName, installRes); 18702 } 18703 } 18704 } 18705 } 18706 } 18707 18708 return ret; 18709 } 18710 18711 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18712 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18713 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18714 for (int nextUserId : userIds) { 18715 if (DEBUG_REMOVE) { 18716 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18717 } 18718 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18719 false /*installed*/, 18720 true /*stopped*/, 18721 true /*notLaunched*/, 18722 false /*hidden*/, 18723 false /*suspended*/, 18724 false /*instantApp*/, 18725 false /*virtualPreload*/, 18726 null /*lastDisableAppCaller*/, 18727 null /*enabledComponents*/, 18728 null /*disabledComponents*/, 18729 ps.readUserState(nextUserId).domainVerificationStatus, 18730 0, PackageManager.INSTALL_REASON_UNKNOWN, 18731 null /*harmfulAppWarning*/); 18732 } 18733 mSettings.writeKernelMappingLPr(ps); 18734 } 18735 18736 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18737 PackageRemovedInfo outInfo) { 18738 final PackageParser.Package pkg; 18739 synchronized (mPackages) { 18740 pkg = mPackages.get(ps.name); 18741 } 18742 18743 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18744 : new int[] {userId}; 18745 for (int nextUserId : userIds) { 18746 if (DEBUG_REMOVE) { 18747 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18748 + nextUserId); 18749 } 18750 18751 destroyAppDataLIF(pkg, userId, 18752 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18753 destroyAppProfilesLIF(pkg, userId); 18754 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18755 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18756 schedulePackageCleaning(ps.name, nextUserId, false); 18757 synchronized (mPackages) { 18758 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18759 scheduleWritePackageRestrictionsLocked(nextUserId); 18760 } 18761 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18762 } 18763 } 18764 18765 if (outInfo != null) { 18766 outInfo.removedPackage = ps.name; 18767 outInfo.installerPackageName = ps.installerPackageName; 18768 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18769 outInfo.removedAppId = ps.appId; 18770 outInfo.removedUsers = userIds; 18771 outInfo.broadcastUsers = userIds; 18772 } 18773 18774 return true; 18775 } 18776 18777 private final class ClearStorageConnection implements ServiceConnection { 18778 IMediaContainerService mContainerService; 18779 18780 @Override 18781 public void onServiceConnected(ComponentName name, IBinder service) { 18782 synchronized (this) { 18783 mContainerService = IMediaContainerService.Stub 18784 .asInterface(Binder.allowBlocking(service)); 18785 notifyAll(); 18786 } 18787 } 18788 18789 @Override 18790 public void onServiceDisconnected(ComponentName name) { 18791 } 18792 } 18793 18794 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18795 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18796 18797 final boolean mounted; 18798 if (Environment.isExternalStorageEmulated()) { 18799 mounted = true; 18800 } else { 18801 final String status = Environment.getExternalStorageState(); 18802 18803 mounted = status.equals(Environment.MEDIA_MOUNTED) 18804 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18805 } 18806 18807 if (!mounted) { 18808 return; 18809 } 18810 18811 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18812 int[] users; 18813 if (userId == UserHandle.USER_ALL) { 18814 users = sUserManager.getUserIds(); 18815 } else { 18816 users = new int[] { userId }; 18817 } 18818 final ClearStorageConnection conn = new ClearStorageConnection(); 18819 if (mContext.bindServiceAsUser( 18820 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18821 try { 18822 for (int curUser : users) { 18823 long timeout = SystemClock.uptimeMillis() + 5000; 18824 synchronized (conn) { 18825 long now; 18826 while (conn.mContainerService == null && 18827 (now = SystemClock.uptimeMillis()) < timeout) { 18828 try { 18829 conn.wait(timeout - now); 18830 } catch (InterruptedException e) { 18831 } 18832 } 18833 } 18834 if (conn.mContainerService == null) { 18835 return; 18836 } 18837 18838 final UserEnvironment userEnv = new UserEnvironment(curUser); 18839 clearDirectory(conn.mContainerService, 18840 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18841 if (allData) { 18842 clearDirectory(conn.mContainerService, 18843 userEnv.buildExternalStorageAppDataDirs(packageName)); 18844 clearDirectory(conn.mContainerService, 18845 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18846 } 18847 } 18848 } finally { 18849 mContext.unbindService(conn); 18850 } 18851 } 18852 } 18853 18854 @Override 18855 public void clearApplicationProfileData(String packageName) { 18856 enforceSystemOrRoot("Only the system can clear all profile data"); 18857 18858 final PackageParser.Package pkg; 18859 synchronized (mPackages) { 18860 pkg = mPackages.get(packageName); 18861 } 18862 18863 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18864 synchronized (mInstallLock) { 18865 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18866 } 18867 } 18868 } 18869 18870 @Override 18871 public void clearApplicationUserData(final String packageName, 18872 final IPackageDataObserver observer, final int userId) { 18873 mContext.enforceCallingOrSelfPermission( 18874 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18875 18876 final int callingUid = Binder.getCallingUid(); 18877 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18878 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18879 18880 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18881 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18882 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18883 throw new SecurityException("Cannot clear data for a protected package: " 18884 + packageName); 18885 } 18886 // Queue up an async operation since the package deletion may take a little while. 18887 mHandler.post(new Runnable() { 18888 public void run() { 18889 mHandler.removeCallbacks(this); 18890 final boolean succeeded; 18891 if (!filterApp) { 18892 try (PackageFreezer freezer = freezePackage(packageName, 18893 "clearApplicationUserData")) { 18894 synchronized (mInstallLock) { 18895 succeeded = clearApplicationUserDataLIF(packageName, userId); 18896 } 18897 clearExternalStorageDataSync(packageName, userId, true); 18898 synchronized (mPackages) { 18899 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18900 packageName, userId); 18901 } 18902 } 18903 if (succeeded) { 18904 // invoke DeviceStorageMonitor's update method to clear any notifications 18905 DeviceStorageMonitorInternal dsm = LocalServices 18906 .getService(DeviceStorageMonitorInternal.class); 18907 if (dsm != null) { 18908 dsm.checkMemory(); 18909 } 18910 } 18911 } else { 18912 succeeded = false; 18913 } 18914 if (observer != null) { 18915 try { 18916 observer.onRemoveCompleted(packageName, succeeded); 18917 } catch (RemoteException e) { 18918 Log.i(TAG, "Observer no longer exists."); 18919 } 18920 } //end if observer 18921 } //end run 18922 }); 18923 } 18924 18925 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18926 if (packageName == null) { 18927 Slog.w(TAG, "Attempt to delete null packageName."); 18928 return false; 18929 } 18930 18931 // Try finding details about the requested package 18932 PackageParser.Package pkg; 18933 synchronized (mPackages) { 18934 pkg = mPackages.get(packageName); 18935 if (pkg == null) { 18936 final PackageSetting ps = mSettings.mPackages.get(packageName); 18937 if (ps != null) { 18938 pkg = ps.pkg; 18939 } 18940 } 18941 18942 if (pkg == null) { 18943 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18944 return false; 18945 } 18946 18947 PackageSetting ps = (PackageSetting) pkg.mExtras; 18948 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18949 } 18950 18951 clearAppDataLIF(pkg, userId, 18952 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18953 18954 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18955 removeKeystoreDataIfNeeded(userId, appId); 18956 18957 UserManagerInternal umInternal = getUserManagerInternal(); 18958 final int flags; 18959 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18960 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18961 } else if (umInternal.isUserRunning(userId)) { 18962 flags = StorageManager.FLAG_STORAGE_DE; 18963 } else { 18964 flags = 0; 18965 } 18966 prepareAppDataContentsLIF(pkg, userId, flags); 18967 18968 return true; 18969 } 18970 18971 /** 18972 * Reverts user permission state changes (permissions and flags) in 18973 * all packages for a given user. 18974 * 18975 * @param userId The device user for which to do a reset. 18976 */ 18977 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18978 final int packageCount = mPackages.size(); 18979 for (int i = 0; i < packageCount; i++) { 18980 PackageParser.Package pkg = mPackages.valueAt(i); 18981 PackageSetting ps = (PackageSetting) pkg.mExtras; 18982 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18983 } 18984 } 18985 18986 private void resetNetworkPolicies(int userId) { 18987 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18988 } 18989 18990 /** 18991 * Reverts user permission state changes (permissions and flags). 18992 * 18993 * @param ps The package for which to reset. 18994 * @param userId The device user for which to do a reset. 18995 */ 18996 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18997 final PackageSetting ps, final int userId) { 18998 if (ps.pkg == null) { 18999 return; 19000 } 19001 19002 // These are flags that can change base on user actions. 19003 final int userSettableMask = FLAG_PERMISSION_USER_SET 19004 | FLAG_PERMISSION_USER_FIXED 19005 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19006 | FLAG_PERMISSION_REVIEW_REQUIRED; 19007 19008 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19009 | FLAG_PERMISSION_POLICY_FIXED; 19010 19011 boolean writeInstallPermissions = false; 19012 boolean writeRuntimePermissions = false; 19013 19014 final int permissionCount = ps.pkg.requestedPermissions.size(); 19015 for (int i = 0; i < permissionCount; i++) { 19016 final String permName = ps.pkg.requestedPermissions.get(i); 19017 final BasePermission bp = 19018 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19019 if (bp == null) { 19020 continue; 19021 } 19022 19023 // If shared user we just reset the state to which only this app contributed. 19024 if (ps.sharedUser != null) { 19025 boolean used = false; 19026 final int packageCount = ps.sharedUser.packages.size(); 19027 for (int j = 0; j < packageCount; j++) { 19028 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19029 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19030 && pkg.pkg.requestedPermissions.contains(permName)) { 19031 used = true; 19032 break; 19033 } 19034 } 19035 if (used) { 19036 continue; 19037 } 19038 } 19039 19040 final PermissionsState permissionsState = ps.getPermissionsState(); 19041 19042 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19043 19044 // Always clear the user settable flags. 19045 final boolean hasInstallState = 19046 permissionsState.getInstallPermissionState(permName) != null; 19047 // If permission review is enabled and this is a legacy app, mark the 19048 // permission as requiring a review as this is the initial state. 19049 int flags = 0; 19050 if (mSettings.mPermissions.mPermissionReviewRequired 19051 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19052 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19053 } 19054 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19055 if (hasInstallState) { 19056 writeInstallPermissions = true; 19057 } else { 19058 writeRuntimePermissions = true; 19059 } 19060 } 19061 19062 // Below is only runtime permission handling. 19063 if (!bp.isRuntime()) { 19064 continue; 19065 } 19066 19067 // Never clobber system or policy. 19068 if ((oldFlags & policyOrSystemFlags) != 0) { 19069 continue; 19070 } 19071 19072 // If this permission was granted by default, make sure it is. 19073 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19074 if (permissionsState.grantRuntimePermission(bp, userId) 19075 != PERMISSION_OPERATION_FAILURE) { 19076 writeRuntimePermissions = true; 19077 } 19078 // If permission review is enabled the permissions for a legacy apps 19079 // are represented as constantly granted runtime ones, so don't revoke. 19080 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19081 // Otherwise, reset the permission. 19082 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19083 switch (revokeResult) { 19084 case PERMISSION_OPERATION_SUCCESS: 19085 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19086 writeRuntimePermissions = true; 19087 final int appId = ps.appId; 19088 mHandler.post(new Runnable() { 19089 @Override 19090 public void run() { 19091 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19092 } 19093 }); 19094 } break; 19095 } 19096 } 19097 } 19098 19099 // Synchronously write as we are taking permissions away. 19100 if (writeRuntimePermissions) { 19101 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19102 } 19103 19104 // Synchronously write as we are taking permissions away. 19105 if (writeInstallPermissions) { 19106 mSettings.writeLPr(); 19107 } 19108 } 19109 19110 /** 19111 * Remove entries from the keystore daemon. Will only remove it if the 19112 * {@code appId} is valid. 19113 */ 19114 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19115 if (appId < 0) { 19116 return; 19117 } 19118 19119 final KeyStore keyStore = KeyStore.getInstance(); 19120 if (keyStore != null) { 19121 if (userId == UserHandle.USER_ALL) { 19122 for (final int individual : sUserManager.getUserIds()) { 19123 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19124 } 19125 } else { 19126 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19127 } 19128 } else { 19129 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19130 } 19131 } 19132 19133 @Override 19134 public void deleteApplicationCacheFiles(final String packageName, 19135 final IPackageDataObserver observer) { 19136 final int userId = UserHandle.getCallingUserId(); 19137 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19138 } 19139 19140 @Override 19141 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19142 final IPackageDataObserver observer) { 19143 final int callingUid = Binder.getCallingUid(); 19144 mContext.enforceCallingOrSelfPermission( 19145 android.Manifest.permission.DELETE_CACHE_FILES, null); 19146 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19147 /* requireFullPermission= */ true, /* checkShell= */ false, 19148 "delete application cache files"); 19149 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19150 android.Manifest.permission.ACCESS_INSTANT_APPS); 19151 19152 final PackageParser.Package pkg; 19153 synchronized (mPackages) { 19154 pkg = mPackages.get(packageName); 19155 } 19156 19157 // Queue up an async operation since the package deletion may take a little while. 19158 mHandler.post(new Runnable() { 19159 public void run() { 19160 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19161 boolean doClearData = true; 19162 if (ps != null) { 19163 final boolean targetIsInstantApp = 19164 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19165 doClearData = !targetIsInstantApp 19166 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19167 } 19168 if (doClearData) { 19169 synchronized (mInstallLock) { 19170 final int flags = StorageManager.FLAG_STORAGE_DE 19171 | StorageManager.FLAG_STORAGE_CE; 19172 // We're only clearing cache files, so we don't care if the 19173 // app is unfrozen and still able to run 19174 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19175 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19176 } 19177 clearExternalStorageDataSync(packageName, userId, false); 19178 } 19179 if (observer != null) { 19180 try { 19181 observer.onRemoveCompleted(packageName, true); 19182 } catch (RemoteException e) { 19183 Log.i(TAG, "Observer no longer exists."); 19184 } 19185 } 19186 } 19187 }); 19188 } 19189 19190 @Override 19191 public void getPackageSizeInfo(final String packageName, int userHandle, 19192 final IPackageStatsObserver observer) { 19193 throw new UnsupportedOperationException( 19194 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19195 } 19196 19197 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19198 final PackageSetting ps; 19199 synchronized (mPackages) { 19200 ps = mSettings.mPackages.get(packageName); 19201 if (ps == null) { 19202 Slog.w(TAG, "Failed to find settings for " + packageName); 19203 return false; 19204 } 19205 } 19206 19207 final String[] packageNames = { packageName }; 19208 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19209 final String[] codePaths = { ps.codePathString }; 19210 19211 try { 19212 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19213 ps.appId, ceDataInodes, codePaths, stats); 19214 19215 // For now, ignore code size of packages on system partition 19216 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19217 stats.codeSize = 0; 19218 } 19219 19220 // External clients expect these to be tracked separately 19221 stats.dataSize -= stats.cacheSize; 19222 19223 } catch (InstallerException e) { 19224 Slog.w(TAG, String.valueOf(e)); 19225 return false; 19226 } 19227 19228 return true; 19229 } 19230 19231 private int getUidTargetSdkVersionLockedLPr(int uid) { 19232 Object obj = mSettings.getUserIdLPr(uid); 19233 if (obj instanceof SharedUserSetting) { 19234 final SharedUserSetting sus = (SharedUserSetting) obj; 19235 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19236 final Iterator<PackageSetting> it = sus.packages.iterator(); 19237 while (it.hasNext()) { 19238 final PackageSetting ps = it.next(); 19239 if (ps.pkg != null) { 19240 int v = ps.pkg.applicationInfo.targetSdkVersion; 19241 if (v < vers) vers = v; 19242 } 19243 } 19244 return vers; 19245 } else if (obj instanceof PackageSetting) { 19246 final PackageSetting ps = (PackageSetting) obj; 19247 if (ps.pkg != null) { 19248 return ps.pkg.applicationInfo.targetSdkVersion; 19249 } 19250 } 19251 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19252 } 19253 19254 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19255 final PackageParser.Package p = mPackages.get(packageName); 19256 if (p != null) { 19257 return p.applicationInfo.targetSdkVersion; 19258 } 19259 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19260 } 19261 19262 @Override 19263 public void addPreferredActivity(IntentFilter filter, int match, 19264 ComponentName[] set, ComponentName activity, int userId) { 19265 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19266 "Adding preferred"); 19267 } 19268 19269 private void addPreferredActivityInternal(IntentFilter filter, int match, 19270 ComponentName[] set, ComponentName activity, boolean always, int userId, 19271 String opname) { 19272 // writer 19273 int callingUid = Binder.getCallingUid(); 19274 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19275 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19276 if (filter.countActions() == 0) { 19277 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19278 return; 19279 } 19280 synchronized (mPackages) { 19281 if (mContext.checkCallingOrSelfPermission( 19282 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19283 != PackageManager.PERMISSION_GRANTED) { 19284 if (getUidTargetSdkVersionLockedLPr(callingUid) 19285 < Build.VERSION_CODES.FROYO) { 19286 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19287 + callingUid); 19288 return; 19289 } 19290 mContext.enforceCallingOrSelfPermission( 19291 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19292 } 19293 19294 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19295 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19296 + userId + ":"); 19297 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19298 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19299 scheduleWritePackageRestrictionsLocked(userId); 19300 postPreferredActivityChangedBroadcast(userId); 19301 } 19302 } 19303 19304 private void postPreferredActivityChangedBroadcast(int userId) { 19305 mHandler.post(() -> { 19306 final IActivityManager am = ActivityManager.getService(); 19307 if (am == null) { 19308 return; 19309 } 19310 19311 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19312 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19313 try { 19314 am.broadcastIntent(null, intent, null, null, 19315 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19316 null, false, false, userId); 19317 } catch (RemoteException e) { 19318 } 19319 }); 19320 } 19321 19322 @Override 19323 public void replacePreferredActivity(IntentFilter filter, int match, 19324 ComponentName[] set, ComponentName activity, int userId) { 19325 if (filter.countActions() != 1) { 19326 throw new IllegalArgumentException( 19327 "replacePreferredActivity expects filter to have only 1 action."); 19328 } 19329 if (filter.countDataAuthorities() != 0 19330 || filter.countDataPaths() != 0 19331 || filter.countDataSchemes() > 1 19332 || filter.countDataTypes() != 0) { 19333 throw new IllegalArgumentException( 19334 "replacePreferredActivity expects filter to have no data authorities, " + 19335 "paths, or types; and at most one scheme."); 19336 } 19337 19338 final int callingUid = Binder.getCallingUid(); 19339 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19340 true /* requireFullPermission */, false /* checkShell */, 19341 "replace preferred activity"); 19342 synchronized (mPackages) { 19343 if (mContext.checkCallingOrSelfPermission( 19344 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19345 != PackageManager.PERMISSION_GRANTED) { 19346 if (getUidTargetSdkVersionLockedLPr(callingUid) 19347 < Build.VERSION_CODES.FROYO) { 19348 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19349 + Binder.getCallingUid()); 19350 return; 19351 } 19352 mContext.enforceCallingOrSelfPermission( 19353 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19354 } 19355 19356 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19357 if (pir != null) { 19358 // Get all of the existing entries that exactly match this filter. 19359 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19360 if (existing != null && existing.size() == 1) { 19361 PreferredActivity cur = existing.get(0); 19362 if (DEBUG_PREFERRED) { 19363 Slog.i(TAG, "Checking replace of preferred:"); 19364 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19365 if (!cur.mPref.mAlways) { 19366 Slog.i(TAG, " -- CUR; not mAlways!"); 19367 } else { 19368 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19369 Slog.i(TAG, " -- CUR: mSet=" 19370 + Arrays.toString(cur.mPref.mSetComponents)); 19371 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19372 Slog.i(TAG, " -- NEW: mMatch=" 19373 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19374 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19375 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19376 } 19377 } 19378 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19379 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19380 && cur.mPref.sameSet(set)) { 19381 // Setting the preferred activity to what it happens to be already 19382 if (DEBUG_PREFERRED) { 19383 Slog.i(TAG, "Replacing with same preferred activity " 19384 + cur.mPref.mShortComponent + " for user " 19385 + userId + ":"); 19386 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19387 } 19388 return; 19389 } 19390 } 19391 19392 if (existing != null) { 19393 if (DEBUG_PREFERRED) { 19394 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19395 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19396 } 19397 for (int i = 0; i < existing.size(); i++) { 19398 PreferredActivity pa = existing.get(i); 19399 if (DEBUG_PREFERRED) { 19400 Slog.i(TAG, "Removing existing preferred activity " 19401 + pa.mPref.mComponent + ":"); 19402 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19403 } 19404 pir.removeFilter(pa); 19405 } 19406 } 19407 } 19408 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19409 "Replacing preferred"); 19410 } 19411 } 19412 19413 @Override 19414 public void clearPackagePreferredActivities(String packageName) { 19415 final int callingUid = Binder.getCallingUid(); 19416 if (getInstantAppPackageName(callingUid) != null) { 19417 return; 19418 } 19419 // writer 19420 synchronized (mPackages) { 19421 PackageParser.Package pkg = mPackages.get(packageName); 19422 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19423 if (mContext.checkCallingOrSelfPermission( 19424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19425 != PackageManager.PERMISSION_GRANTED) { 19426 if (getUidTargetSdkVersionLockedLPr(callingUid) 19427 < Build.VERSION_CODES.FROYO) { 19428 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19429 + callingUid); 19430 return; 19431 } 19432 mContext.enforceCallingOrSelfPermission( 19433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19434 } 19435 } 19436 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19437 if (ps != null 19438 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19439 return; 19440 } 19441 int user = UserHandle.getCallingUserId(); 19442 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19443 scheduleWritePackageRestrictionsLocked(user); 19444 } 19445 } 19446 } 19447 19448 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19449 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19450 ArrayList<PreferredActivity> removed = null; 19451 boolean changed = false; 19452 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19453 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19454 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19455 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19456 continue; 19457 } 19458 Iterator<PreferredActivity> it = pir.filterIterator(); 19459 while (it.hasNext()) { 19460 PreferredActivity pa = it.next(); 19461 // Mark entry for removal only if it matches the package name 19462 // and the entry is of type "always". 19463 if (packageName == null || 19464 (pa.mPref.mComponent.getPackageName().equals(packageName) 19465 && pa.mPref.mAlways)) { 19466 if (removed == null) { 19467 removed = new ArrayList<PreferredActivity>(); 19468 } 19469 removed.add(pa); 19470 } 19471 } 19472 if (removed != null) { 19473 for (int j=0; j<removed.size(); j++) { 19474 PreferredActivity pa = removed.get(j); 19475 pir.removeFilter(pa); 19476 } 19477 changed = true; 19478 } 19479 } 19480 if (changed) { 19481 postPreferredActivityChangedBroadcast(userId); 19482 } 19483 return changed; 19484 } 19485 19486 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19487 private void clearIntentFilterVerificationsLPw(int userId) { 19488 final int packageCount = mPackages.size(); 19489 for (int i = 0; i < packageCount; i++) { 19490 PackageParser.Package pkg = mPackages.valueAt(i); 19491 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19492 } 19493 } 19494 19495 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19496 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19497 if (userId == UserHandle.USER_ALL) { 19498 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19499 sUserManager.getUserIds())) { 19500 for (int oneUserId : sUserManager.getUserIds()) { 19501 scheduleWritePackageRestrictionsLocked(oneUserId); 19502 } 19503 } 19504 } else { 19505 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19506 scheduleWritePackageRestrictionsLocked(userId); 19507 } 19508 } 19509 } 19510 19511 /** Clears state for all users, and touches intent filter verification policy */ 19512 void clearDefaultBrowserIfNeeded(String packageName) { 19513 for (int oneUserId : sUserManager.getUserIds()) { 19514 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19515 } 19516 } 19517 19518 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19519 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19520 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19521 if (packageName.equals(defaultBrowserPackageName)) { 19522 setDefaultBrowserPackageName(null, userId); 19523 } 19524 } 19525 } 19526 19527 @Override 19528 public void resetApplicationPreferences(int userId) { 19529 mContext.enforceCallingOrSelfPermission( 19530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19531 final long identity = Binder.clearCallingIdentity(); 19532 // writer 19533 try { 19534 synchronized (mPackages) { 19535 clearPackagePreferredActivitiesLPw(null, userId); 19536 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19537 // TODO: We have to reset the default SMS and Phone. This requires 19538 // significant refactoring to keep all default apps in the package 19539 // manager (cleaner but more work) or have the services provide 19540 // callbacks to the package manager to request a default app reset. 19541 applyFactoryDefaultBrowserLPw(userId); 19542 clearIntentFilterVerificationsLPw(userId); 19543 primeDomainVerificationsLPw(userId); 19544 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19545 scheduleWritePackageRestrictionsLocked(userId); 19546 } 19547 resetNetworkPolicies(userId); 19548 } finally { 19549 Binder.restoreCallingIdentity(identity); 19550 } 19551 } 19552 19553 @Override 19554 public int getPreferredActivities(List<IntentFilter> outFilters, 19555 List<ComponentName> outActivities, String packageName) { 19556 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19557 return 0; 19558 } 19559 int num = 0; 19560 final int userId = UserHandle.getCallingUserId(); 19561 // reader 19562 synchronized (mPackages) { 19563 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19564 if (pir != null) { 19565 final Iterator<PreferredActivity> it = pir.filterIterator(); 19566 while (it.hasNext()) { 19567 final PreferredActivity pa = it.next(); 19568 if (packageName == null 19569 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19570 && pa.mPref.mAlways)) { 19571 if (outFilters != null) { 19572 outFilters.add(new IntentFilter(pa)); 19573 } 19574 if (outActivities != null) { 19575 outActivities.add(pa.mPref.mComponent); 19576 } 19577 } 19578 } 19579 } 19580 } 19581 19582 return num; 19583 } 19584 19585 @Override 19586 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19587 int userId) { 19588 int callingUid = Binder.getCallingUid(); 19589 if (callingUid != Process.SYSTEM_UID) { 19590 throw new SecurityException( 19591 "addPersistentPreferredActivity can only be run by the system"); 19592 } 19593 if (filter.countActions() == 0) { 19594 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19595 return; 19596 } 19597 synchronized (mPackages) { 19598 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19599 ":"); 19600 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19601 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19602 new PersistentPreferredActivity(filter, activity)); 19603 scheduleWritePackageRestrictionsLocked(userId); 19604 postPreferredActivityChangedBroadcast(userId); 19605 } 19606 } 19607 19608 @Override 19609 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19610 int callingUid = Binder.getCallingUid(); 19611 if (callingUid != Process.SYSTEM_UID) { 19612 throw new SecurityException( 19613 "clearPackagePersistentPreferredActivities can only be run by the system"); 19614 } 19615 ArrayList<PersistentPreferredActivity> removed = null; 19616 boolean changed = false; 19617 synchronized (mPackages) { 19618 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19619 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19620 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19621 .valueAt(i); 19622 if (userId != thisUserId) { 19623 continue; 19624 } 19625 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19626 while (it.hasNext()) { 19627 PersistentPreferredActivity ppa = it.next(); 19628 // Mark entry for removal only if it matches the package name. 19629 if (ppa.mComponent.getPackageName().equals(packageName)) { 19630 if (removed == null) { 19631 removed = new ArrayList<PersistentPreferredActivity>(); 19632 } 19633 removed.add(ppa); 19634 } 19635 } 19636 if (removed != null) { 19637 for (int j=0; j<removed.size(); j++) { 19638 PersistentPreferredActivity ppa = removed.get(j); 19639 ppir.removeFilter(ppa); 19640 } 19641 changed = true; 19642 } 19643 } 19644 19645 if (changed) { 19646 scheduleWritePackageRestrictionsLocked(userId); 19647 postPreferredActivityChangedBroadcast(userId); 19648 } 19649 } 19650 } 19651 19652 /** 19653 * Common machinery for picking apart a restored XML blob and passing 19654 * it to a caller-supplied functor to be applied to the running system. 19655 */ 19656 private void restoreFromXml(XmlPullParser parser, int userId, 19657 String expectedStartTag, BlobXmlRestorer functor) 19658 throws IOException, XmlPullParserException { 19659 int type; 19660 while ((type = parser.next()) != XmlPullParser.START_TAG 19661 && type != XmlPullParser.END_DOCUMENT) { 19662 } 19663 if (type != XmlPullParser.START_TAG) { 19664 // oops didn't find a start tag?! 19665 if (DEBUG_BACKUP) { 19666 Slog.e(TAG, "Didn't find start tag during restore"); 19667 } 19668 return; 19669 } 19670Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19671 // this is supposed to be TAG_PREFERRED_BACKUP 19672 if (!expectedStartTag.equals(parser.getName())) { 19673 if (DEBUG_BACKUP) { 19674 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19675 } 19676 return; 19677 } 19678 19679 // skip interfering stuff, then we're aligned with the backing implementation 19680 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19681Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19682 functor.apply(parser, userId); 19683 } 19684 19685 private interface BlobXmlRestorer { 19686 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19687 } 19688 19689 /** 19690 * Non-Binder method, support for the backup/restore mechanism: write the 19691 * full set of preferred activities in its canonical XML format. Returns the 19692 * XML output as a byte array, or null if there is none. 19693 */ 19694 @Override 19695 public byte[] getPreferredActivityBackup(int userId) { 19696 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19697 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19698 } 19699 19700 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19701 try { 19702 final XmlSerializer serializer = new FastXmlSerializer(); 19703 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19704 serializer.startDocument(null, true); 19705 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19706 19707 synchronized (mPackages) { 19708 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19709 } 19710 19711 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19712 serializer.endDocument(); 19713 serializer.flush(); 19714 } catch (Exception e) { 19715 if (DEBUG_BACKUP) { 19716 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19717 } 19718 return null; 19719 } 19720 19721 return dataStream.toByteArray(); 19722 } 19723 19724 @Override 19725 public void restorePreferredActivities(byte[] backup, int userId) { 19726 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19727 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19728 } 19729 19730 try { 19731 final XmlPullParser parser = Xml.newPullParser(); 19732 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19733 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19734 new BlobXmlRestorer() { 19735 @Override 19736 public void apply(XmlPullParser parser, int userId) 19737 throws XmlPullParserException, IOException { 19738 synchronized (mPackages) { 19739 mSettings.readPreferredActivitiesLPw(parser, userId); 19740 } 19741 } 19742 } ); 19743 } catch (Exception e) { 19744 if (DEBUG_BACKUP) { 19745 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19746 } 19747 } 19748 } 19749 19750 /** 19751 * Non-Binder method, support for the backup/restore mechanism: write the 19752 * default browser (etc) settings in its canonical XML format. Returns the default 19753 * browser XML representation as a byte array, or null if there is none. 19754 */ 19755 @Override 19756 public byte[] getDefaultAppsBackup(int userId) { 19757 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19758 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19759 } 19760 19761 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19762 try { 19763 final XmlSerializer serializer = new FastXmlSerializer(); 19764 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19765 serializer.startDocument(null, true); 19766 serializer.startTag(null, TAG_DEFAULT_APPS); 19767 19768 synchronized (mPackages) { 19769 mSettings.writeDefaultAppsLPr(serializer, userId); 19770 } 19771 19772 serializer.endTag(null, TAG_DEFAULT_APPS); 19773 serializer.endDocument(); 19774 serializer.flush(); 19775 } catch (Exception e) { 19776 if (DEBUG_BACKUP) { 19777 Slog.e(TAG, "Unable to write default apps for backup", e); 19778 } 19779 return null; 19780 } 19781 19782 return dataStream.toByteArray(); 19783 } 19784 19785 @Override 19786 public void restoreDefaultApps(byte[] backup, int userId) { 19787 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19788 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19789 } 19790 19791 try { 19792 final XmlPullParser parser = Xml.newPullParser(); 19793 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19794 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19795 new BlobXmlRestorer() { 19796 @Override 19797 public void apply(XmlPullParser parser, int userId) 19798 throws XmlPullParserException, IOException { 19799 synchronized (mPackages) { 19800 mSettings.readDefaultAppsLPw(parser, userId); 19801 } 19802 } 19803 } ); 19804 } catch (Exception e) { 19805 if (DEBUG_BACKUP) { 19806 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19807 } 19808 } 19809 } 19810 19811 @Override 19812 public byte[] getIntentFilterVerificationBackup(int userId) { 19813 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19814 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19815 } 19816 19817 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19818 try { 19819 final XmlSerializer serializer = new FastXmlSerializer(); 19820 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19821 serializer.startDocument(null, true); 19822 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19823 19824 synchronized (mPackages) { 19825 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19826 } 19827 19828 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19829 serializer.endDocument(); 19830 serializer.flush(); 19831 } catch (Exception e) { 19832 if (DEBUG_BACKUP) { 19833 Slog.e(TAG, "Unable to write default apps for backup", e); 19834 } 19835 return null; 19836 } 19837 19838 return dataStream.toByteArray(); 19839 } 19840 19841 @Override 19842 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19843 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19844 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19845 } 19846 19847 try { 19848 final XmlPullParser parser = Xml.newPullParser(); 19849 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19850 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19851 new BlobXmlRestorer() { 19852 @Override 19853 public void apply(XmlPullParser parser, int userId) 19854 throws XmlPullParserException, IOException { 19855 synchronized (mPackages) { 19856 mSettings.readAllDomainVerificationsLPr(parser, userId); 19857 mSettings.writeLPr(); 19858 } 19859 } 19860 } ); 19861 } catch (Exception e) { 19862 if (DEBUG_BACKUP) { 19863 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19864 } 19865 } 19866 } 19867 19868 @Override 19869 public byte[] getPermissionGrantBackup(int userId) { 19870 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19871 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19872 } 19873 19874 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19875 try { 19876 final XmlSerializer serializer = new FastXmlSerializer(); 19877 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19878 serializer.startDocument(null, true); 19879 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19880 19881 synchronized (mPackages) { 19882 serializeRuntimePermissionGrantsLPr(serializer, userId); 19883 } 19884 19885 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19886 serializer.endDocument(); 19887 serializer.flush(); 19888 } catch (Exception e) { 19889 if (DEBUG_BACKUP) { 19890 Slog.e(TAG, "Unable to write default apps for backup", e); 19891 } 19892 return null; 19893 } 19894 19895 return dataStream.toByteArray(); 19896 } 19897 19898 @Override 19899 public void restorePermissionGrants(byte[] backup, int userId) { 19900 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19901 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19902 } 19903 19904 try { 19905 final XmlPullParser parser = Xml.newPullParser(); 19906 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19907 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19908 new BlobXmlRestorer() { 19909 @Override 19910 public void apply(XmlPullParser parser, int userId) 19911 throws XmlPullParserException, IOException { 19912 synchronized (mPackages) { 19913 processRestoredPermissionGrantsLPr(parser, userId); 19914 } 19915 } 19916 } ); 19917 } catch (Exception e) { 19918 if (DEBUG_BACKUP) { 19919 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19920 } 19921 } 19922 } 19923 19924 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19925 throws IOException { 19926 serializer.startTag(null, TAG_ALL_GRANTS); 19927 19928 final int N = mSettings.mPackages.size(); 19929 for (int i = 0; i < N; i++) { 19930 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19931 boolean pkgGrantsKnown = false; 19932 19933 PermissionsState packagePerms = ps.getPermissionsState(); 19934 19935 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19936 final int grantFlags = state.getFlags(); 19937 // only look at grants that are not system/policy fixed 19938 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19939 final boolean isGranted = state.isGranted(); 19940 // And only back up the user-twiddled state bits 19941 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19942 final String packageName = mSettings.mPackages.keyAt(i); 19943 if (!pkgGrantsKnown) { 19944 serializer.startTag(null, TAG_GRANT); 19945 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19946 pkgGrantsKnown = true; 19947 } 19948 19949 final boolean userSet = 19950 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19951 final boolean userFixed = 19952 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19953 final boolean revoke = 19954 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19955 19956 serializer.startTag(null, TAG_PERMISSION); 19957 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19958 if (isGranted) { 19959 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19960 } 19961 if (userSet) { 19962 serializer.attribute(null, ATTR_USER_SET, "true"); 19963 } 19964 if (userFixed) { 19965 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19966 } 19967 if (revoke) { 19968 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19969 } 19970 serializer.endTag(null, TAG_PERMISSION); 19971 } 19972 } 19973 } 19974 19975 if (pkgGrantsKnown) { 19976 serializer.endTag(null, TAG_GRANT); 19977 } 19978 } 19979 19980 serializer.endTag(null, TAG_ALL_GRANTS); 19981 } 19982 19983 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19984 throws XmlPullParserException, IOException { 19985 String pkgName = null; 19986 int outerDepth = parser.getDepth(); 19987 int type; 19988 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19989 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19990 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19991 continue; 19992 } 19993 19994 final String tagName = parser.getName(); 19995 if (tagName.equals(TAG_GRANT)) { 19996 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19997 if (DEBUG_BACKUP) { 19998 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19999 } 20000 } else if (tagName.equals(TAG_PERMISSION)) { 20001 20002 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20003 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20004 20005 int newFlagSet = 0; 20006 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20007 newFlagSet |= FLAG_PERMISSION_USER_SET; 20008 } 20009 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20010 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20011 } 20012 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20013 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20014 } 20015 if (DEBUG_BACKUP) { 20016 Slog.v(TAG, " + Restoring grant:" 20017 + " pkg=" + pkgName 20018 + " perm=" + permName 20019 + " granted=" + isGranted 20020 + " bits=0x" + Integer.toHexString(newFlagSet)); 20021 } 20022 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20023 if (ps != null) { 20024 // Already installed so we apply the grant immediately 20025 if (DEBUG_BACKUP) { 20026 Slog.v(TAG, " + already installed; applying"); 20027 } 20028 PermissionsState perms = ps.getPermissionsState(); 20029 BasePermission bp = 20030 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20031 if (bp != null) { 20032 if (isGranted) { 20033 perms.grantRuntimePermission(bp, userId); 20034 } 20035 if (newFlagSet != 0) { 20036 perms.updatePermissionFlags( 20037 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20038 } 20039 } 20040 } else { 20041 // Need to wait for post-restore install to apply the grant 20042 if (DEBUG_BACKUP) { 20043 Slog.v(TAG, " - not yet installed; saving for later"); 20044 } 20045 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20046 isGranted, newFlagSet, userId); 20047 } 20048 } else { 20049 PackageManagerService.reportSettingsProblem(Log.WARN, 20050 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20051 XmlUtils.skipCurrentTag(parser); 20052 } 20053 } 20054 20055 scheduleWriteSettingsLocked(); 20056 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20057 } 20058 20059 @Override 20060 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20061 int sourceUserId, int targetUserId, int flags) { 20062 mContext.enforceCallingOrSelfPermission( 20063 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20064 int callingUid = Binder.getCallingUid(); 20065 enforceOwnerRights(ownerPackage, callingUid); 20066 PackageManagerServiceUtils.enforceShellRestriction( 20067 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20068 if (intentFilter.countActions() == 0) { 20069 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20070 return; 20071 } 20072 synchronized (mPackages) { 20073 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20074 ownerPackage, targetUserId, flags); 20075 CrossProfileIntentResolver resolver = 20076 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20077 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20078 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20079 if (existing != null) { 20080 int size = existing.size(); 20081 for (int i = 0; i < size; i++) { 20082 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20083 return; 20084 } 20085 } 20086 } 20087 resolver.addFilter(newFilter); 20088 scheduleWritePackageRestrictionsLocked(sourceUserId); 20089 } 20090 } 20091 20092 @Override 20093 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20094 mContext.enforceCallingOrSelfPermission( 20095 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20096 final int callingUid = Binder.getCallingUid(); 20097 enforceOwnerRights(ownerPackage, callingUid); 20098 PackageManagerServiceUtils.enforceShellRestriction( 20099 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20100 synchronized (mPackages) { 20101 CrossProfileIntentResolver resolver = 20102 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20103 ArraySet<CrossProfileIntentFilter> set = 20104 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20105 for (CrossProfileIntentFilter filter : set) { 20106 if (filter.getOwnerPackage().equals(ownerPackage)) { 20107 resolver.removeFilter(filter); 20108 } 20109 } 20110 scheduleWritePackageRestrictionsLocked(sourceUserId); 20111 } 20112 } 20113 20114 // Enforcing that callingUid is owning pkg on userId 20115 private void enforceOwnerRights(String pkg, int callingUid) { 20116 // The system owns everything. 20117 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20118 return; 20119 } 20120 final int callingUserId = UserHandle.getUserId(callingUid); 20121 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20122 if (pi == null) { 20123 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20124 + callingUserId); 20125 } 20126 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20127 throw new SecurityException("Calling uid " + callingUid 20128 + " does not own package " + pkg); 20129 } 20130 } 20131 20132 @Override 20133 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20134 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20135 return null; 20136 } 20137 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20138 } 20139 20140 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20141 UserManagerService ums = UserManagerService.getInstance(); 20142 if (ums != null) { 20143 final UserInfo parent = ums.getProfileParent(userId); 20144 final int launcherUid = (parent != null) ? parent.id : userId; 20145 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20146 if (launcherComponent != null) { 20147 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20148 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20149 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20150 .setPackage(launcherComponent.getPackageName()); 20151 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20152 } 20153 } 20154 } 20155 20156 /** 20157 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20158 * then reports the most likely home activity or null if there are more than one. 20159 */ 20160 private ComponentName getDefaultHomeActivity(int userId) { 20161 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20162 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20163 if (cn != null) { 20164 return cn; 20165 } 20166 20167 // Find the launcher with the highest priority and return that component if there are no 20168 // other home activity with the same priority. 20169 int lastPriority = Integer.MIN_VALUE; 20170 ComponentName lastComponent = null; 20171 final int size = allHomeCandidates.size(); 20172 for (int i = 0; i < size; i++) { 20173 final ResolveInfo ri = allHomeCandidates.get(i); 20174 if (ri.priority > lastPriority) { 20175 lastComponent = ri.activityInfo.getComponentName(); 20176 lastPriority = ri.priority; 20177 } else if (ri.priority == lastPriority) { 20178 // Two components found with same priority. 20179 lastComponent = null; 20180 } 20181 } 20182 return lastComponent; 20183 } 20184 20185 private Intent getHomeIntent() { 20186 Intent intent = new Intent(Intent.ACTION_MAIN); 20187 intent.addCategory(Intent.CATEGORY_HOME); 20188 intent.addCategory(Intent.CATEGORY_DEFAULT); 20189 return intent; 20190 } 20191 20192 private IntentFilter getHomeFilter() { 20193 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20194 filter.addCategory(Intent.CATEGORY_HOME); 20195 filter.addCategory(Intent.CATEGORY_DEFAULT); 20196 return filter; 20197 } 20198 20199 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20200 int userId) { 20201 Intent intent = getHomeIntent(); 20202 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20203 PackageManager.GET_META_DATA, userId); 20204 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20205 true, false, false, userId); 20206 20207 allHomeCandidates.clear(); 20208 if (list != null) { 20209 for (ResolveInfo ri : list) { 20210 allHomeCandidates.add(ri); 20211 } 20212 } 20213 return (preferred == null || preferred.activityInfo == null) 20214 ? null 20215 : new ComponentName(preferred.activityInfo.packageName, 20216 preferred.activityInfo.name); 20217 } 20218 20219 @Override 20220 public void setHomeActivity(ComponentName comp, int userId) { 20221 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20222 return; 20223 } 20224 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20225 getHomeActivitiesAsUser(homeActivities, userId); 20226 20227 boolean found = false; 20228 20229 final int size = homeActivities.size(); 20230 final ComponentName[] set = new ComponentName[size]; 20231 for (int i = 0; i < size; i++) { 20232 final ResolveInfo candidate = homeActivities.get(i); 20233 final ActivityInfo info = candidate.activityInfo; 20234 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20235 set[i] = activityName; 20236 if (!found && activityName.equals(comp)) { 20237 found = true; 20238 } 20239 } 20240 if (!found) { 20241 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20242 + userId); 20243 } 20244 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20245 set, comp, userId); 20246 } 20247 20248 private @Nullable String getSetupWizardPackageName() { 20249 final Intent intent = new Intent(Intent.ACTION_MAIN); 20250 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20251 20252 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20253 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20254 | MATCH_DISABLED_COMPONENTS, 20255 UserHandle.myUserId()); 20256 if (matches.size() == 1) { 20257 return matches.get(0).getComponentInfo().packageName; 20258 } else { 20259 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20260 + ": matches=" + matches); 20261 return null; 20262 } 20263 } 20264 20265 private @Nullable String getStorageManagerPackageName() { 20266 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20267 20268 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20269 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20270 | MATCH_DISABLED_COMPONENTS, 20271 UserHandle.myUserId()); 20272 if (matches.size() == 1) { 20273 return matches.get(0).getComponentInfo().packageName; 20274 } else { 20275 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20276 + matches.size() + ": matches=" + matches); 20277 return null; 20278 } 20279 } 20280 20281 @Override 20282 public void setApplicationEnabledSetting(String appPackageName, 20283 int newState, int flags, int userId, String callingPackage) { 20284 if (!sUserManager.exists(userId)) return; 20285 if (callingPackage == null) { 20286 callingPackage = Integer.toString(Binder.getCallingUid()); 20287 } 20288 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20289 } 20290 20291 @Override 20292 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20294 synchronized (mPackages) { 20295 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20296 if (pkgSetting != null) { 20297 pkgSetting.setUpdateAvailable(updateAvailable); 20298 } 20299 } 20300 } 20301 20302 @Override 20303 public void setComponentEnabledSetting(ComponentName componentName, 20304 int newState, int flags, int userId) { 20305 if (!sUserManager.exists(userId)) return; 20306 setEnabledSetting(componentName.getPackageName(), 20307 componentName.getClassName(), newState, flags, userId, null); 20308 } 20309 20310 private void setEnabledSetting(final String packageName, String className, int newState, 20311 final int flags, int userId, String callingPackage) { 20312 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20313 || newState == COMPONENT_ENABLED_STATE_ENABLED 20314 || newState == COMPONENT_ENABLED_STATE_DISABLED 20315 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20316 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20317 throw new IllegalArgumentException("Invalid new component state: " 20318 + newState); 20319 } 20320 PackageSetting pkgSetting; 20321 final int callingUid = Binder.getCallingUid(); 20322 final int permission; 20323 if (callingUid == Process.SYSTEM_UID) { 20324 permission = PackageManager.PERMISSION_GRANTED; 20325 } else { 20326 permission = mContext.checkCallingOrSelfPermission( 20327 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20328 } 20329 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20330 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20331 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20332 boolean sendNow = false; 20333 boolean isApp = (className == null); 20334 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20335 String componentName = isApp ? packageName : className; 20336 int packageUid = -1; 20337 ArrayList<String> components; 20338 20339 // reader 20340 synchronized (mPackages) { 20341 pkgSetting = mSettings.mPackages.get(packageName); 20342 if (pkgSetting == null) { 20343 if (!isCallerInstantApp) { 20344 if (className == null) { 20345 throw new IllegalArgumentException("Unknown package: " + packageName); 20346 } 20347 throw new IllegalArgumentException( 20348 "Unknown component: " + packageName + "/" + className); 20349 } else { 20350 // throw SecurityException to prevent leaking package information 20351 throw new SecurityException( 20352 "Attempt to change component state; " 20353 + "pid=" + Binder.getCallingPid() 20354 + ", uid=" + callingUid 20355 + (className == null 20356 ? ", package=" + packageName 20357 : ", component=" + packageName + "/" + className)); 20358 } 20359 } 20360 } 20361 20362 // Limit who can change which apps 20363 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20364 // Don't allow apps that don't have permission to modify other apps 20365 if (!allowedByPermission 20366 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20367 throw new SecurityException( 20368 "Attempt to change component state; " 20369 + "pid=" + Binder.getCallingPid() 20370 + ", uid=" + callingUid 20371 + (className == null 20372 ? ", package=" + packageName 20373 : ", component=" + packageName + "/" + className)); 20374 } 20375 // Don't allow changing protected packages. 20376 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20377 throw new SecurityException("Cannot disable a protected package: " + packageName); 20378 } 20379 } 20380 20381 synchronized (mPackages) { 20382 if (callingUid == Process.SHELL_UID 20383 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20384 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20385 // unless it is a test package. 20386 int oldState = pkgSetting.getEnabled(userId); 20387 if (className == null 20388 && 20389 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20390 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20391 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20392 && 20393 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20394 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20395 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20396 // ok 20397 } else { 20398 throw new SecurityException( 20399 "Shell cannot change component state for " + packageName + "/" 20400 + className + " to " + newState); 20401 } 20402 } 20403 } 20404 if (className == null) { 20405 // We're dealing with an application/package level state change 20406 synchronized (mPackages) { 20407 if (pkgSetting.getEnabled(userId) == newState) { 20408 // Nothing to do 20409 return; 20410 } 20411 } 20412 // If we're enabling a system stub, there's a little more work to do. 20413 // Prior to enabling the package, we need to decompress the APK(s) to the 20414 // data partition and then replace the version on the system partition. 20415 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20416 final boolean isSystemStub = deletedPkg.isStub 20417 && deletedPkg.isSystem(); 20418 if (isSystemStub 20419 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20420 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20421 final File codePath = decompressPackage(deletedPkg); 20422 if (codePath == null) { 20423 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20424 return; 20425 } 20426 // TODO remove direct parsing of the package object during internal cleanup 20427 // of scan package 20428 // We need to call parse directly here for no other reason than we need 20429 // the new package in order to disable the old one [we use the information 20430 // for some internal optimization to optionally create a new package setting 20431 // object on replace]. However, we can't get the package from the scan 20432 // because the scan modifies live structures and we need to remove the 20433 // old [system] package from the system before a scan can be attempted. 20434 // Once scan is indempotent we can remove this parse and use the package 20435 // object we scanned, prior to adding it to package settings. 20436 final PackageParser pp = new PackageParser(); 20437 pp.setSeparateProcesses(mSeparateProcesses); 20438 pp.setDisplayMetrics(mMetrics); 20439 pp.setCallback(mPackageParserCallback); 20440 final PackageParser.Package tmpPkg; 20441 try { 20442 final @ParseFlags int parseFlags = mDefParseFlags 20443 | PackageParser.PARSE_MUST_BE_APK 20444 | PackageParser.PARSE_IS_SYSTEM_DIR; 20445 tmpPkg = pp.parsePackage(codePath, parseFlags); 20446 } catch (PackageParserException e) { 20447 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20448 return; 20449 } 20450 synchronized (mInstallLock) { 20451 // Disable the stub and remove any package entries 20452 removePackageLI(deletedPkg, true); 20453 synchronized (mPackages) { 20454 disableSystemPackageLPw(deletedPkg, tmpPkg); 20455 } 20456 final PackageParser.Package pkg; 20457 try (PackageFreezer freezer = 20458 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20459 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20460 | PackageParser.PARSE_ENFORCE_CODE; 20461 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20462 0 /*currentTime*/, null /*user*/); 20463 prepareAppDataAfterInstallLIF(pkg); 20464 synchronized (mPackages) { 20465 try { 20466 updateSharedLibrariesLPr(pkg, null); 20467 } catch (PackageManagerException e) { 20468 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20469 } 20470 mPermissionManager.updatePermissions( 20471 pkg.packageName, pkg, true, mPackages.values(), 20472 mPermissionCallback); 20473 mSettings.writeLPr(); 20474 } 20475 } catch (PackageManagerException e) { 20476 // Whoops! Something went wrong; try to roll back to the stub 20477 Slog.w(TAG, "Failed to install compressed system package:" 20478 + pkgSetting.name, e); 20479 // Remove the failed install 20480 removeCodePathLI(codePath); 20481 20482 // Install the system package 20483 try (PackageFreezer freezer = 20484 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20485 synchronized (mPackages) { 20486 // NOTE: The system package always needs to be enabled; even 20487 // if it's for a compressed stub. If we don't, installing the 20488 // system package fails during scan [scanning checks the disabled 20489 // packages]. We will reverse this later, after we've "installed" 20490 // the stub. 20491 // This leaves us in a fragile state; the stub should never be 20492 // enabled, so, cross your fingers and hope nothing goes wrong 20493 // until we can disable the package later. 20494 enableSystemPackageLPw(deletedPkg); 20495 } 20496 installPackageFromSystemLIF(deletedPkg.codePath, 20497 false /*isPrivileged*/, null /*allUserHandles*/, 20498 null /*origUserHandles*/, null /*origPermissionsState*/, 20499 true /*writeSettings*/); 20500 } catch (PackageManagerException pme) { 20501 Slog.w(TAG, "Failed to restore system package:" 20502 + deletedPkg.packageName, pme); 20503 } finally { 20504 synchronized (mPackages) { 20505 mSettings.disableSystemPackageLPw( 20506 deletedPkg.packageName, true /*replaced*/); 20507 mSettings.writeLPr(); 20508 } 20509 } 20510 return; 20511 } 20512 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20513 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20514 mDexManager.notifyPackageUpdated(pkg.packageName, 20515 pkg.baseCodePath, pkg.splitCodePaths); 20516 } 20517 } 20518 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20519 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20520 // Don't care about who enables an app. 20521 callingPackage = null; 20522 } 20523 synchronized (mPackages) { 20524 pkgSetting.setEnabled(newState, userId, callingPackage); 20525 } 20526 } else { 20527 synchronized (mPackages) { 20528 // We're dealing with a component level state change 20529 // First, verify that this is a valid class name. 20530 PackageParser.Package pkg = pkgSetting.pkg; 20531 if (pkg == null || !pkg.hasComponentClassName(className)) { 20532 if (pkg != null && 20533 pkg.applicationInfo.targetSdkVersion >= 20534 Build.VERSION_CODES.JELLY_BEAN) { 20535 throw new IllegalArgumentException("Component class " + className 20536 + " does not exist in " + packageName); 20537 } else { 20538 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20539 + className + " does not exist in " + packageName); 20540 } 20541 } 20542 switch (newState) { 20543 case COMPONENT_ENABLED_STATE_ENABLED: 20544 if (!pkgSetting.enableComponentLPw(className, userId)) { 20545 return; 20546 } 20547 break; 20548 case COMPONENT_ENABLED_STATE_DISABLED: 20549 if (!pkgSetting.disableComponentLPw(className, userId)) { 20550 return; 20551 } 20552 break; 20553 case COMPONENT_ENABLED_STATE_DEFAULT: 20554 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20555 return; 20556 } 20557 break; 20558 default: 20559 Slog.e(TAG, "Invalid new component state: " + newState); 20560 return; 20561 } 20562 } 20563 } 20564 synchronized (mPackages) { 20565 scheduleWritePackageRestrictionsLocked(userId); 20566 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20567 final long callingId = Binder.clearCallingIdentity(); 20568 try { 20569 updateInstantAppInstallerLocked(packageName); 20570 } finally { 20571 Binder.restoreCallingIdentity(callingId); 20572 } 20573 components = mPendingBroadcasts.get(userId, packageName); 20574 final boolean newPackage = components == null; 20575 if (newPackage) { 20576 components = new ArrayList<String>(); 20577 } 20578 if (!components.contains(componentName)) { 20579 components.add(componentName); 20580 } 20581 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20582 sendNow = true; 20583 // Purge entry from pending broadcast list if another one exists already 20584 // since we are sending one right away. 20585 mPendingBroadcasts.remove(userId, packageName); 20586 } else { 20587 if (newPackage) { 20588 mPendingBroadcasts.put(userId, packageName, components); 20589 } 20590 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20591 // Schedule a message 20592 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20593 } 20594 } 20595 } 20596 20597 long callingId = Binder.clearCallingIdentity(); 20598 try { 20599 if (sendNow) { 20600 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20601 sendPackageChangedBroadcast(packageName, 20602 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20603 } 20604 } finally { 20605 Binder.restoreCallingIdentity(callingId); 20606 } 20607 } 20608 20609 @Override 20610 public void flushPackageRestrictionsAsUser(int userId) { 20611 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20612 return; 20613 } 20614 if (!sUserManager.exists(userId)) { 20615 return; 20616 } 20617 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20618 false /* checkShell */, "flushPackageRestrictions"); 20619 synchronized (mPackages) { 20620 mSettings.writePackageRestrictionsLPr(userId); 20621 mDirtyUsers.remove(userId); 20622 if (mDirtyUsers.isEmpty()) { 20623 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20624 } 20625 } 20626 } 20627 20628 private void sendPackageChangedBroadcast(String packageName, 20629 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20630 if (DEBUG_INSTALL) 20631 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20632 + componentNames); 20633 Bundle extras = new Bundle(4); 20634 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20635 String nameList[] = new String[componentNames.size()]; 20636 componentNames.toArray(nameList); 20637 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20638 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20639 extras.putInt(Intent.EXTRA_UID, packageUid); 20640 // If this is not reporting a change of the overall package, then only send it 20641 // to registered receivers. We don't want to launch a swath of apps for every 20642 // little component state change. 20643 final int flags = !componentNames.contains(packageName) 20644 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20645 final int userId = UserHandle.getUserId(packageUid); 20646 final boolean isInstantApp = isInstantApp(packageName, userId); 20647 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20648 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20649 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20650 userIds, instantUserIds); 20651 } 20652 20653 @Override 20654 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20655 if (!sUserManager.exists(userId)) return; 20656 final int callingUid = Binder.getCallingUid(); 20657 if (getInstantAppPackageName(callingUid) != null) { 20658 return; 20659 } 20660 final int permission = mContext.checkCallingOrSelfPermission( 20661 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20662 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20663 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20664 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20665 // writer 20666 synchronized (mPackages) { 20667 final PackageSetting ps = mSettings.mPackages.get(packageName); 20668 if (!filterAppAccessLPr(ps, callingUid, userId) 20669 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20670 allowedByPermission, callingUid, userId)) { 20671 scheduleWritePackageRestrictionsLocked(userId); 20672 } 20673 } 20674 } 20675 20676 @Override 20677 public String getInstallerPackageName(String packageName) { 20678 final int callingUid = Binder.getCallingUid(); 20679 if (getInstantAppPackageName(callingUid) != null) { 20680 return null; 20681 } 20682 // reader 20683 synchronized (mPackages) { 20684 final PackageSetting ps = mSettings.mPackages.get(packageName); 20685 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20686 return null; 20687 } 20688 return mSettings.getInstallerPackageNameLPr(packageName); 20689 } 20690 } 20691 20692 public boolean isOrphaned(String packageName) { 20693 // reader 20694 synchronized (mPackages) { 20695 return mSettings.isOrphaned(packageName); 20696 } 20697 } 20698 20699 @Override 20700 public int getApplicationEnabledSetting(String packageName, int userId) { 20701 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20702 int callingUid = Binder.getCallingUid(); 20703 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20704 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20705 // reader 20706 synchronized (mPackages) { 20707 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20708 return COMPONENT_ENABLED_STATE_DISABLED; 20709 } 20710 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20711 } 20712 } 20713 20714 @Override 20715 public int getComponentEnabledSetting(ComponentName component, int userId) { 20716 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20717 int callingUid = Binder.getCallingUid(); 20718 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20719 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20720 synchronized (mPackages) { 20721 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20722 component, TYPE_UNKNOWN, userId)) { 20723 return COMPONENT_ENABLED_STATE_DISABLED; 20724 } 20725 return mSettings.getComponentEnabledSettingLPr(component, userId); 20726 } 20727 } 20728 20729 @Override 20730 public void enterSafeMode() { 20731 enforceSystemOrRoot("Only the system can request entering safe mode"); 20732 20733 if (!mSystemReady) { 20734 mSafeMode = true; 20735 } 20736 } 20737 20738 @Override 20739 public void systemReady() { 20740 enforceSystemOrRoot("Only the system can claim the system is ready"); 20741 20742 mSystemReady = true; 20743 final ContentResolver resolver = mContext.getContentResolver(); 20744 ContentObserver co = new ContentObserver(mHandler) { 20745 @Override 20746 public void onChange(boolean selfChange) { 20747 mEphemeralAppsDisabled = 20748 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20749 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20750 } 20751 }; 20752 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20753 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20754 false, co, UserHandle.USER_SYSTEM); 20755 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20756 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20757 co.onChange(true); 20758 20759 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20760 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20761 // it is done. 20762 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20763 @Override 20764 public void onChange(boolean selfChange) { 20765 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20766 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20767 oobEnabled == 1 ? "true" : "false"); 20768 } 20769 }; 20770 mContext.getContentResolver().registerContentObserver( 20771 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20772 UserHandle.USER_SYSTEM); 20773 // At boot, restore the value from the setting, which persists across reboot. 20774 privAppOobObserver.onChange(true); 20775 20776 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20777 // disabled after already being started. 20778 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20779 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20780 20781 // Read the compatibilty setting when the system is ready. 20782 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20783 mContext.getContentResolver(), 20784 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20785 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20786 if (DEBUG_SETTINGS) { 20787 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20788 } 20789 20790 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20791 20792 synchronized (mPackages) { 20793 // Verify that all of the preferred activity components actually 20794 // exist. It is possible for applications to be updated and at 20795 // that point remove a previously declared activity component that 20796 // had been set as a preferred activity. We try to clean this up 20797 // the next time we encounter that preferred activity, but it is 20798 // possible for the user flow to never be able to return to that 20799 // situation so here we do a sanity check to make sure we haven't 20800 // left any junk around. 20801 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20802 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20803 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20804 removed.clear(); 20805 for (PreferredActivity pa : pir.filterSet()) { 20806 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20807 removed.add(pa); 20808 } 20809 } 20810 if (removed.size() > 0) { 20811 for (int r=0; r<removed.size(); r++) { 20812 PreferredActivity pa = removed.get(r); 20813 Slog.w(TAG, "Removing dangling preferred activity: " 20814 + pa.mPref.mComponent); 20815 pir.removeFilter(pa); 20816 } 20817 mSettings.writePackageRestrictionsLPr( 20818 mSettings.mPreferredActivities.keyAt(i)); 20819 } 20820 } 20821 20822 for (int userId : UserManagerService.getInstance().getUserIds()) { 20823 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20824 grantPermissionsUserIds = ArrayUtils.appendInt( 20825 grantPermissionsUserIds, userId); 20826 } 20827 } 20828 } 20829 sUserManager.systemReady(); 20830 // If we upgraded grant all default permissions before kicking off. 20831 for (int userId : grantPermissionsUserIds) { 20832 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20833 } 20834 20835 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20836 // If we did not grant default permissions, we preload from this the 20837 // default permission exceptions lazily to ensure we don't hit the 20838 // disk on a new user creation. 20839 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20840 } 20841 20842 // Now that we've scanned all packages, and granted any default 20843 // permissions, ensure permissions are updated. Beware of dragons if you 20844 // try optimizing this. 20845 synchronized (mPackages) { 20846 mPermissionManager.updateAllPermissions( 20847 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20848 mPermissionCallback); 20849 } 20850 20851 // Kick off any messages waiting for system ready 20852 if (mPostSystemReadyMessages != null) { 20853 for (Message msg : mPostSystemReadyMessages) { 20854 msg.sendToTarget(); 20855 } 20856 mPostSystemReadyMessages = null; 20857 } 20858 20859 // Watch for external volumes that come and go over time 20860 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20861 storage.registerListener(mStorageListener); 20862 20863 mInstallerService.systemReady(); 20864 mPackageDexOptimizer.systemReady(); 20865 20866 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20867 StorageManagerInternal.class); 20868 StorageManagerInternal.addExternalStoragePolicy( 20869 new StorageManagerInternal.ExternalStorageMountPolicy() { 20870 @Override 20871 public int getMountMode(int uid, String packageName) { 20872 if (Process.isIsolated(uid)) { 20873 return Zygote.MOUNT_EXTERNAL_NONE; 20874 } 20875 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20876 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20877 } 20878 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20879 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20880 } 20881 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20882 return Zygote.MOUNT_EXTERNAL_READ; 20883 } 20884 return Zygote.MOUNT_EXTERNAL_WRITE; 20885 } 20886 20887 @Override 20888 public boolean hasExternalStorage(int uid, String packageName) { 20889 return true; 20890 } 20891 }); 20892 20893 // Now that we're mostly running, clean up stale users and apps 20894 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20895 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20896 20897 mPermissionManager.systemReady(); 20898 } 20899 20900 public void waitForAppDataPrepared() { 20901 if (mPrepareAppDataFuture == null) { 20902 return; 20903 } 20904 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20905 mPrepareAppDataFuture = null; 20906 } 20907 20908 @Override 20909 public boolean isSafeMode() { 20910 // allow instant applications 20911 return mSafeMode; 20912 } 20913 20914 @Override 20915 public boolean hasSystemUidErrors() { 20916 // allow instant applications 20917 return mHasSystemUidErrors; 20918 } 20919 20920 static String arrayToString(int[] array) { 20921 StringBuffer buf = new StringBuffer(128); 20922 buf.append('['); 20923 if (array != null) { 20924 for (int i=0; i<array.length; i++) { 20925 if (i > 0) buf.append(", "); 20926 buf.append(array[i]); 20927 } 20928 } 20929 buf.append(']'); 20930 return buf.toString(); 20931 } 20932 20933 @Override 20934 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20935 FileDescriptor err, String[] args, ShellCallback callback, 20936 ResultReceiver resultReceiver) { 20937 (new PackageManagerShellCommand(this)).exec( 20938 this, in, out, err, args, callback, resultReceiver); 20939 } 20940 20941 @Override 20942 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20943 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20944 20945 DumpState dumpState = new DumpState(); 20946 boolean fullPreferred = false; 20947 boolean checkin = false; 20948 20949 String packageName = null; 20950 ArraySet<String> permissionNames = null; 20951 20952 int opti = 0; 20953 while (opti < args.length) { 20954 String opt = args[opti]; 20955 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20956 break; 20957 } 20958 opti++; 20959 20960 if ("-a".equals(opt)) { 20961 // Right now we only know how to print all. 20962 } else if ("-h".equals(opt)) { 20963 pw.println("Package manager dump options:"); 20964 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20965 pw.println(" --checkin: dump for a checkin"); 20966 pw.println(" -f: print details of intent filters"); 20967 pw.println(" -h: print this help"); 20968 pw.println(" cmd may be one of:"); 20969 pw.println(" l[ibraries]: list known shared libraries"); 20970 pw.println(" f[eatures]: list device features"); 20971 pw.println(" k[eysets]: print known keysets"); 20972 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20973 pw.println(" perm[issions]: dump permissions"); 20974 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20975 pw.println(" pref[erred]: print preferred package settings"); 20976 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20977 pw.println(" prov[iders]: dump content providers"); 20978 pw.println(" p[ackages]: dump installed packages"); 20979 pw.println(" s[hared-users]: dump shared user IDs"); 20980 pw.println(" m[essages]: print collected runtime messages"); 20981 pw.println(" v[erifiers]: print package verifier info"); 20982 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20983 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20984 pw.println(" version: print database version info"); 20985 pw.println(" write: write current settings now"); 20986 pw.println(" installs: details about install sessions"); 20987 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20988 pw.println(" dexopt: dump dexopt state"); 20989 pw.println(" compiler-stats: dump compiler statistics"); 20990 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20991 pw.println(" service-permissions: dump permissions required by services"); 20992 pw.println(" <package.name>: info about given package"); 20993 return; 20994 } else if ("--checkin".equals(opt)) { 20995 checkin = true; 20996 } else if ("-f".equals(opt)) { 20997 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20998 } else if ("--proto".equals(opt)) { 20999 dumpProto(fd); 21000 return; 21001 } else { 21002 pw.println("Unknown argument: " + opt + "; use -h for help"); 21003 } 21004 } 21005 21006 // Is the caller requesting to dump a particular piece of data? 21007 if (opti < args.length) { 21008 String cmd = args[opti]; 21009 opti++; 21010 // Is this a package name? 21011 if ("android".equals(cmd) || cmd.contains(".")) { 21012 packageName = cmd; 21013 // When dumping a single package, we always dump all of its 21014 // filter information since the amount of data will be reasonable. 21015 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21016 } else if ("check-permission".equals(cmd)) { 21017 if (opti >= args.length) { 21018 pw.println("Error: check-permission missing permission argument"); 21019 return; 21020 } 21021 String perm = args[opti]; 21022 opti++; 21023 if (opti >= args.length) { 21024 pw.println("Error: check-permission missing package argument"); 21025 return; 21026 } 21027 21028 String pkg = args[opti]; 21029 opti++; 21030 int user = UserHandle.getUserId(Binder.getCallingUid()); 21031 if (opti < args.length) { 21032 try { 21033 user = Integer.parseInt(args[opti]); 21034 } catch (NumberFormatException e) { 21035 pw.println("Error: check-permission user argument is not a number: " 21036 + args[opti]); 21037 return; 21038 } 21039 } 21040 21041 // Normalize package name to handle renamed packages and static libs 21042 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21043 21044 pw.println(checkPermission(perm, pkg, user)); 21045 return; 21046 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21047 dumpState.setDump(DumpState.DUMP_LIBS); 21048 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21049 dumpState.setDump(DumpState.DUMP_FEATURES); 21050 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21051 if (opti >= args.length) { 21052 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21053 | DumpState.DUMP_SERVICE_RESOLVERS 21054 | DumpState.DUMP_RECEIVER_RESOLVERS 21055 | DumpState.DUMP_CONTENT_RESOLVERS); 21056 } else { 21057 while (opti < args.length) { 21058 String name = args[opti]; 21059 if ("a".equals(name) || "activity".equals(name)) { 21060 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21061 } else if ("s".equals(name) || "service".equals(name)) { 21062 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21063 } else if ("r".equals(name) || "receiver".equals(name)) { 21064 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21065 } else if ("c".equals(name) || "content".equals(name)) { 21066 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21067 } else { 21068 pw.println("Error: unknown resolver table type: " + name); 21069 return; 21070 } 21071 opti++; 21072 } 21073 } 21074 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21075 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21076 } else if ("permission".equals(cmd)) { 21077 if (opti >= args.length) { 21078 pw.println("Error: permission requires permission name"); 21079 return; 21080 } 21081 permissionNames = new ArraySet<>(); 21082 while (opti < args.length) { 21083 permissionNames.add(args[opti]); 21084 opti++; 21085 } 21086 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21087 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21088 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21089 dumpState.setDump(DumpState.DUMP_PREFERRED); 21090 } else if ("preferred-xml".equals(cmd)) { 21091 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21092 if (opti < args.length && "--full".equals(args[opti])) { 21093 fullPreferred = true; 21094 opti++; 21095 } 21096 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21097 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21098 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21099 dumpState.setDump(DumpState.DUMP_PACKAGES); 21100 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21101 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21102 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21103 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21104 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21105 dumpState.setDump(DumpState.DUMP_MESSAGES); 21106 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21107 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21108 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21109 || "intent-filter-verifiers".equals(cmd)) { 21110 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21111 } else if ("version".equals(cmd)) { 21112 dumpState.setDump(DumpState.DUMP_VERSION); 21113 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21114 dumpState.setDump(DumpState.DUMP_KEYSETS); 21115 } else if ("installs".equals(cmd)) { 21116 dumpState.setDump(DumpState.DUMP_INSTALLS); 21117 } else if ("frozen".equals(cmd)) { 21118 dumpState.setDump(DumpState.DUMP_FROZEN); 21119 } else if ("volumes".equals(cmd)) { 21120 dumpState.setDump(DumpState.DUMP_VOLUMES); 21121 } else if ("dexopt".equals(cmd)) { 21122 dumpState.setDump(DumpState.DUMP_DEXOPT); 21123 } else if ("compiler-stats".equals(cmd)) { 21124 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21125 } else if ("changes".equals(cmd)) { 21126 dumpState.setDump(DumpState.DUMP_CHANGES); 21127 } else if ("service-permissions".equals(cmd)) { 21128 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21129 } else if ("write".equals(cmd)) { 21130 synchronized (mPackages) { 21131 mSettings.writeLPr(); 21132 pw.println("Settings written."); 21133 return; 21134 } 21135 } 21136 } 21137 21138 if (checkin) { 21139 pw.println("vers,1"); 21140 } 21141 21142 // reader 21143 synchronized (mPackages) { 21144 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21145 if (!checkin) { 21146 if (dumpState.onTitlePrinted()) 21147 pw.println(); 21148 pw.println("Database versions:"); 21149 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21150 } 21151 } 21152 21153 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21154 if (!checkin) { 21155 if (dumpState.onTitlePrinted()) 21156 pw.println(); 21157 pw.println("Verifiers:"); 21158 pw.print(" Required: "); 21159 pw.print(mRequiredVerifierPackage); 21160 pw.print(" (uid="); 21161 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21162 UserHandle.USER_SYSTEM)); 21163 pw.println(")"); 21164 } else if (mRequiredVerifierPackage != null) { 21165 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21166 pw.print(","); 21167 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21168 UserHandle.USER_SYSTEM)); 21169 } 21170 } 21171 21172 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21173 packageName == null) { 21174 if (mIntentFilterVerifierComponent != null) { 21175 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21176 if (!checkin) { 21177 if (dumpState.onTitlePrinted()) 21178 pw.println(); 21179 pw.println("Intent Filter Verifier:"); 21180 pw.print(" Using: "); 21181 pw.print(verifierPackageName); 21182 pw.print(" (uid="); 21183 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21184 UserHandle.USER_SYSTEM)); 21185 pw.println(")"); 21186 } else if (verifierPackageName != null) { 21187 pw.print("ifv,"); pw.print(verifierPackageName); 21188 pw.print(","); 21189 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21190 UserHandle.USER_SYSTEM)); 21191 } 21192 } else { 21193 pw.println(); 21194 pw.println("No Intent Filter Verifier available!"); 21195 } 21196 } 21197 21198 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21199 boolean printedHeader = false; 21200 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21201 while (it.hasNext()) { 21202 String libName = it.next(); 21203 LongSparseArray<SharedLibraryEntry> versionedLib 21204 = mSharedLibraries.get(libName); 21205 if (versionedLib == null) { 21206 continue; 21207 } 21208 final int versionCount = versionedLib.size(); 21209 for (int i = 0; i < versionCount; i++) { 21210 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21211 if (!checkin) { 21212 if (!printedHeader) { 21213 if (dumpState.onTitlePrinted()) 21214 pw.println(); 21215 pw.println("Libraries:"); 21216 printedHeader = true; 21217 } 21218 pw.print(" "); 21219 } else { 21220 pw.print("lib,"); 21221 } 21222 pw.print(libEntry.info.getName()); 21223 if (libEntry.info.isStatic()) { 21224 pw.print(" version=" + libEntry.info.getLongVersion()); 21225 } 21226 if (!checkin) { 21227 pw.print(" -> "); 21228 } 21229 if (libEntry.path != null) { 21230 pw.print(" (jar) "); 21231 pw.print(libEntry.path); 21232 } else { 21233 pw.print(" (apk) "); 21234 pw.print(libEntry.apk); 21235 } 21236 pw.println(); 21237 } 21238 } 21239 } 21240 21241 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21242 if (dumpState.onTitlePrinted()) 21243 pw.println(); 21244 if (!checkin) { 21245 pw.println("Features:"); 21246 } 21247 21248 synchronized (mAvailableFeatures) { 21249 for (FeatureInfo feat : mAvailableFeatures.values()) { 21250 if (checkin) { 21251 pw.print("feat,"); 21252 pw.print(feat.name); 21253 pw.print(","); 21254 pw.println(feat.version); 21255 } else { 21256 pw.print(" "); 21257 pw.print(feat.name); 21258 if (feat.version > 0) { 21259 pw.print(" version="); 21260 pw.print(feat.version); 21261 } 21262 pw.println(); 21263 } 21264 } 21265 } 21266 } 21267 21268 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21269 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21270 : "Activity Resolver Table:", " ", packageName, 21271 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21272 dumpState.setTitlePrinted(true); 21273 } 21274 } 21275 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21276 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21277 : "Receiver Resolver Table:", " ", packageName, 21278 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21279 dumpState.setTitlePrinted(true); 21280 } 21281 } 21282 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21283 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21284 : "Service Resolver Table:", " ", packageName, 21285 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21286 dumpState.setTitlePrinted(true); 21287 } 21288 } 21289 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21290 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21291 : "Provider Resolver Table:", " ", packageName, 21292 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21293 dumpState.setTitlePrinted(true); 21294 } 21295 } 21296 21297 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21298 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21299 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21300 int user = mSettings.mPreferredActivities.keyAt(i); 21301 if (pir.dump(pw, 21302 dumpState.getTitlePrinted() 21303 ? "\nPreferred Activities User " + user + ":" 21304 : "Preferred Activities User " + user + ":", " ", 21305 packageName, true, false)) { 21306 dumpState.setTitlePrinted(true); 21307 } 21308 } 21309 } 21310 21311 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21312 pw.flush(); 21313 FileOutputStream fout = new FileOutputStream(fd); 21314 BufferedOutputStream str = new BufferedOutputStream(fout); 21315 XmlSerializer serializer = new FastXmlSerializer(); 21316 try { 21317 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21318 serializer.startDocument(null, true); 21319 serializer.setFeature( 21320 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21321 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21322 serializer.endDocument(); 21323 serializer.flush(); 21324 } catch (IllegalArgumentException e) { 21325 pw.println("Failed writing: " + e); 21326 } catch (IllegalStateException e) { 21327 pw.println("Failed writing: " + e); 21328 } catch (IOException e) { 21329 pw.println("Failed writing: " + e); 21330 } 21331 } 21332 21333 if (!checkin 21334 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21335 && packageName == null) { 21336 pw.println(); 21337 int count = mSettings.mPackages.size(); 21338 if (count == 0) { 21339 pw.println("No applications!"); 21340 pw.println(); 21341 } else { 21342 final String prefix = " "; 21343 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21344 if (allPackageSettings.size() == 0) { 21345 pw.println("No domain preferred apps!"); 21346 pw.println(); 21347 } else { 21348 pw.println("App verification status:"); 21349 pw.println(); 21350 count = 0; 21351 for (PackageSetting ps : allPackageSettings) { 21352 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21353 if (ivi == null || ivi.getPackageName() == null) continue; 21354 pw.println(prefix + "Package: " + ivi.getPackageName()); 21355 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21356 pw.println(prefix + "Status: " + ivi.getStatusString()); 21357 pw.println(); 21358 count++; 21359 } 21360 if (count == 0) { 21361 pw.println(prefix + "No app verification established."); 21362 pw.println(); 21363 } 21364 for (int userId : sUserManager.getUserIds()) { 21365 pw.println("App linkages for user " + userId + ":"); 21366 pw.println(); 21367 count = 0; 21368 for (PackageSetting ps : allPackageSettings) { 21369 final long status = ps.getDomainVerificationStatusForUser(userId); 21370 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21371 && !DEBUG_DOMAIN_VERIFICATION) { 21372 continue; 21373 } 21374 pw.println(prefix + "Package: " + ps.name); 21375 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21376 String statusStr = IntentFilterVerificationInfo. 21377 getStatusStringFromValue(status); 21378 pw.println(prefix + "Status: " + statusStr); 21379 pw.println(); 21380 count++; 21381 } 21382 if (count == 0) { 21383 pw.println(prefix + "No configured app linkages."); 21384 pw.println(); 21385 } 21386 } 21387 } 21388 } 21389 } 21390 21391 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21392 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21393 } 21394 21395 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21396 boolean printedSomething = false; 21397 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21398 if (packageName != null && !packageName.equals(p.info.packageName)) { 21399 continue; 21400 } 21401 if (!printedSomething) { 21402 if (dumpState.onTitlePrinted()) 21403 pw.println(); 21404 pw.println("Registered ContentProviders:"); 21405 printedSomething = true; 21406 } 21407 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21408 pw.print(" "); pw.println(p.toString()); 21409 } 21410 printedSomething = false; 21411 for (Map.Entry<String, PackageParser.Provider> entry : 21412 mProvidersByAuthority.entrySet()) { 21413 PackageParser.Provider p = entry.getValue(); 21414 if (packageName != null && !packageName.equals(p.info.packageName)) { 21415 continue; 21416 } 21417 if (!printedSomething) { 21418 if (dumpState.onTitlePrinted()) 21419 pw.println(); 21420 pw.println("ContentProvider Authorities:"); 21421 printedSomething = true; 21422 } 21423 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21424 pw.print(" "); pw.println(p.toString()); 21425 if (p.info != null && p.info.applicationInfo != null) { 21426 final String appInfo = p.info.applicationInfo.toString(); 21427 pw.print(" applicationInfo="); pw.println(appInfo); 21428 } 21429 } 21430 } 21431 21432 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21433 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21434 } 21435 21436 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21437 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21438 } 21439 21440 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21441 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21442 } 21443 21444 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21445 if (dumpState.onTitlePrinted()) pw.println(); 21446 pw.println("Package Changes:"); 21447 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21448 final int K = mChangedPackages.size(); 21449 for (int i = 0; i < K; i++) { 21450 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21451 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21452 final int N = changes.size(); 21453 if (N == 0) { 21454 pw.print(" "); pw.println("No packages changed"); 21455 } else { 21456 for (int j = 0; j < N; j++) { 21457 final String pkgName = changes.valueAt(j); 21458 final int sequenceNumber = changes.keyAt(j); 21459 pw.print(" "); 21460 pw.print("seq="); 21461 pw.print(sequenceNumber); 21462 pw.print(", package="); 21463 pw.println(pkgName); 21464 } 21465 } 21466 } 21467 } 21468 21469 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21470 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21471 } 21472 21473 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21474 // XXX should handle packageName != null by dumping only install data that 21475 // the given package is involved with. 21476 if (dumpState.onTitlePrinted()) pw.println(); 21477 21478 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21479 ipw.println(); 21480 ipw.println("Frozen packages:"); 21481 ipw.increaseIndent(); 21482 if (mFrozenPackages.size() == 0) { 21483 ipw.println("(none)"); 21484 } else { 21485 for (int i = 0; i < mFrozenPackages.size(); i++) { 21486 ipw.println(mFrozenPackages.valueAt(i)); 21487 } 21488 } 21489 ipw.decreaseIndent(); 21490 } 21491 21492 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21493 if (dumpState.onTitlePrinted()) pw.println(); 21494 21495 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21496 ipw.println(); 21497 ipw.println("Loaded volumes:"); 21498 ipw.increaseIndent(); 21499 if (mLoadedVolumes.size() == 0) { 21500 ipw.println("(none)"); 21501 } else { 21502 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21503 ipw.println(mLoadedVolumes.valueAt(i)); 21504 } 21505 } 21506 ipw.decreaseIndent(); 21507 } 21508 21509 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21510 && packageName == null) { 21511 if (dumpState.onTitlePrinted()) pw.println(); 21512 pw.println("Service permissions:"); 21513 21514 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21515 while (filterIterator.hasNext()) { 21516 final ServiceIntentInfo info = filterIterator.next(); 21517 final ServiceInfo serviceInfo = info.service.info; 21518 final String permission = serviceInfo.permission; 21519 if (permission != null) { 21520 pw.print(" "); 21521 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21522 pw.print(": "); 21523 pw.println(permission); 21524 } 21525 } 21526 } 21527 21528 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21529 if (dumpState.onTitlePrinted()) pw.println(); 21530 dumpDexoptStateLPr(pw, packageName); 21531 } 21532 21533 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21534 if (dumpState.onTitlePrinted()) pw.println(); 21535 dumpCompilerStatsLPr(pw, packageName); 21536 } 21537 21538 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21539 if (dumpState.onTitlePrinted()) pw.println(); 21540 mSettings.dumpReadMessagesLPr(pw, dumpState); 21541 21542 pw.println(); 21543 pw.println("Package warning messages:"); 21544 dumpCriticalInfo(pw, null); 21545 } 21546 21547 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21548 dumpCriticalInfo(pw, "msg,"); 21549 } 21550 } 21551 21552 // PackageInstaller should be called outside of mPackages lock 21553 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21554 // XXX should handle packageName != null by dumping only install data that 21555 // the given package is involved with. 21556 if (dumpState.onTitlePrinted()) pw.println(); 21557 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21558 } 21559 } 21560 21561 private void dumpProto(FileDescriptor fd) { 21562 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21563 21564 synchronized (mPackages) { 21565 final long requiredVerifierPackageToken = 21566 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21567 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21568 proto.write( 21569 PackageServiceDumpProto.PackageShortProto.UID, 21570 getPackageUid( 21571 mRequiredVerifierPackage, 21572 MATCH_DEBUG_TRIAGED_MISSING, 21573 UserHandle.USER_SYSTEM)); 21574 proto.end(requiredVerifierPackageToken); 21575 21576 if (mIntentFilterVerifierComponent != null) { 21577 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21578 final long verifierPackageToken = 21579 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21580 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21581 proto.write( 21582 PackageServiceDumpProto.PackageShortProto.UID, 21583 getPackageUid( 21584 verifierPackageName, 21585 MATCH_DEBUG_TRIAGED_MISSING, 21586 UserHandle.USER_SYSTEM)); 21587 proto.end(verifierPackageToken); 21588 } 21589 21590 dumpSharedLibrariesProto(proto); 21591 dumpFeaturesProto(proto); 21592 mSettings.dumpPackagesProto(proto); 21593 mSettings.dumpSharedUsersProto(proto); 21594 dumpCriticalInfo(proto); 21595 } 21596 proto.flush(); 21597 } 21598 21599 private void dumpFeaturesProto(ProtoOutputStream proto) { 21600 synchronized (mAvailableFeatures) { 21601 final int count = mAvailableFeatures.size(); 21602 for (int i = 0; i < count; i++) { 21603 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21604 } 21605 } 21606 } 21607 21608 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21609 final int count = mSharedLibraries.size(); 21610 for (int i = 0; i < count; i++) { 21611 final String libName = mSharedLibraries.keyAt(i); 21612 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21613 if (versionedLib == null) { 21614 continue; 21615 } 21616 final int versionCount = versionedLib.size(); 21617 for (int j = 0; j < versionCount; j++) { 21618 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21619 final long sharedLibraryToken = 21620 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21621 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21622 final boolean isJar = (libEntry.path != null); 21623 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21624 if (isJar) { 21625 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21626 } else { 21627 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21628 } 21629 proto.end(sharedLibraryToken); 21630 } 21631 } 21632 } 21633 21634 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21635 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21636 ipw.println(); 21637 ipw.println("Dexopt state:"); 21638 ipw.increaseIndent(); 21639 Collection<PackageParser.Package> packages = null; 21640 if (packageName != null) { 21641 PackageParser.Package targetPackage = mPackages.get(packageName); 21642 if (targetPackage != null) { 21643 packages = Collections.singletonList(targetPackage); 21644 } else { 21645 ipw.println("Unable to find package: " + packageName); 21646 return; 21647 } 21648 } else { 21649 packages = mPackages.values(); 21650 } 21651 21652 for (PackageParser.Package pkg : packages) { 21653 ipw.println("[" + pkg.packageName + "]"); 21654 ipw.increaseIndent(); 21655 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21656 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21657 ipw.decreaseIndent(); 21658 } 21659 } 21660 21661 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21662 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21663 ipw.println(); 21664 ipw.println("Compiler stats:"); 21665 ipw.increaseIndent(); 21666 Collection<PackageParser.Package> packages = null; 21667 if (packageName != null) { 21668 PackageParser.Package targetPackage = mPackages.get(packageName); 21669 if (targetPackage != null) { 21670 packages = Collections.singletonList(targetPackage); 21671 } else { 21672 ipw.println("Unable to find package: " + packageName); 21673 return; 21674 } 21675 } else { 21676 packages = mPackages.values(); 21677 } 21678 21679 for (PackageParser.Package pkg : packages) { 21680 ipw.println("[" + pkg.packageName + "]"); 21681 ipw.increaseIndent(); 21682 21683 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21684 if (stats == null) { 21685 ipw.println("(No recorded stats)"); 21686 } else { 21687 stats.dump(ipw); 21688 } 21689 ipw.decreaseIndent(); 21690 } 21691 } 21692 21693 private String dumpDomainString(String packageName) { 21694 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21695 .getList(); 21696 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21697 21698 ArraySet<String> result = new ArraySet<>(); 21699 if (iviList.size() > 0) { 21700 for (IntentFilterVerificationInfo ivi : iviList) { 21701 for (String host : ivi.getDomains()) { 21702 result.add(host); 21703 } 21704 } 21705 } 21706 if (filters != null && filters.size() > 0) { 21707 for (IntentFilter filter : filters) { 21708 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21709 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21710 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21711 result.addAll(filter.getHostsList()); 21712 } 21713 } 21714 } 21715 21716 StringBuilder sb = new StringBuilder(result.size() * 16); 21717 for (String domain : result) { 21718 if (sb.length() > 0) sb.append(" "); 21719 sb.append(domain); 21720 } 21721 return sb.toString(); 21722 } 21723 21724 // ------- apps on sdcard specific code ------- 21725 static final boolean DEBUG_SD_INSTALL = false; 21726 21727 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21728 21729 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21730 21731 private boolean mMediaMounted = false; 21732 21733 static String getEncryptKey() { 21734 try { 21735 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21736 SD_ENCRYPTION_KEYSTORE_NAME); 21737 if (sdEncKey == null) { 21738 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21739 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21740 if (sdEncKey == null) { 21741 Slog.e(TAG, "Failed to create encryption keys"); 21742 return null; 21743 } 21744 } 21745 return sdEncKey; 21746 } catch (NoSuchAlgorithmException nsae) { 21747 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21748 return null; 21749 } catch (IOException ioe) { 21750 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21751 return null; 21752 } 21753 } 21754 21755 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21756 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21757 final int size = infos.size(); 21758 final String[] packageNames = new String[size]; 21759 final int[] packageUids = new int[size]; 21760 for (int i = 0; i < size; i++) { 21761 final ApplicationInfo info = infos.get(i); 21762 packageNames[i] = info.packageName; 21763 packageUids[i] = info.uid; 21764 } 21765 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21766 finishedReceiver); 21767 } 21768 21769 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21770 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21771 sendResourcesChangedBroadcast(mediaStatus, replacing, 21772 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21773 } 21774 21775 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21776 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21777 int size = pkgList.length; 21778 if (size > 0) { 21779 // Send broadcasts here 21780 Bundle extras = new Bundle(); 21781 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21782 if (uidArr != null) { 21783 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21784 } 21785 if (replacing) { 21786 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21787 } 21788 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21789 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21790 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21791 } 21792 } 21793 21794 private void loadPrivatePackages(final VolumeInfo vol) { 21795 mHandler.post(new Runnable() { 21796 @Override 21797 public void run() { 21798 loadPrivatePackagesInner(vol); 21799 } 21800 }); 21801 } 21802 21803 private void loadPrivatePackagesInner(VolumeInfo vol) { 21804 final String volumeUuid = vol.fsUuid; 21805 if (TextUtils.isEmpty(volumeUuid)) { 21806 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21807 return; 21808 } 21809 21810 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21811 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21812 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21813 21814 final VersionInfo ver; 21815 final List<PackageSetting> packages; 21816 synchronized (mPackages) { 21817 ver = mSettings.findOrCreateVersion(volumeUuid); 21818 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21819 } 21820 21821 for (PackageSetting ps : packages) { 21822 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21823 synchronized (mInstallLock) { 21824 final PackageParser.Package pkg; 21825 try { 21826 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21827 loaded.add(pkg.applicationInfo); 21828 21829 } catch (PackageManagerException e) { 21830 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21831 } 21832 21833 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21834 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21835 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21836 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21837 } 21838 } 21839 } 21840 21841 // Reconcile app data for all started/unlocked users 21842 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21843 final UserManager um = mContext.getSystemService(UserManager.class); 21844 UserManagerInternal umInternal = getUserManagerInternal(); 21845 for (UserInfo user : um.getUsers()) { 21846 final int flags; 21847 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21848 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21849 } else if (umInternal.isUserRunning(user.id)) { 21850 flags = StorageManager.FLAG_STORAGE_DE; 21851 } else { 21852 continue; 21853 } 21854 21855 try { 21856 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21857 synchronized (mInstallLock) { 21858 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21859 } 21860 } catch (IllegalStateException e) { 21861 // Device was probably ejected, and we'll process that event momentarily 21862 Slog.w(TAG, "Failed to prepare storage: " + e); 21863 } 21864 } 21865 21866 synchronized (mPackages) { 21867 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21868 if (sdkUpdated) { 21869 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21870 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21871 } 21872 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21873 mPermissionCallback); 21874 21875 // Yay, everything is now upgraded 21876 ver.forceCurrent(); 21877 21878 mSettings.writeLPr(); 21879 } 21880 21881 for (PackageFreezer freezer : freezers) { 21882 freezer.close(); 21883 } 21884 21885 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21886 sendResourcesChangedBroadcast(true, false, loaded, null); 21887 mLoadedVolumes.add(vol.getId()); 21888 } 21889 21890 private void unloadPrivatePackages(final VolumeInfo vol) { 21891 mHandler.post(new Runnable() { 21892 @Override 21893 public void run() { 21894 unloadPrivatePackagesInner(vol); 21895 } 21896 }); 21897 } 21898 21899 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21900 final String volumeUuid = vol.fsUuid; 21901 if (TextUtils.isEmpty(volumeUuid)) { 21902 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21903 return; 21904 } 21905 21906 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21907 synchronized (mInstallLock) { 21908 synchronized (mPackages) { 21909 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21910 for (PackageSetting ps : packages) { 21911 if (ps.pkg == null) continue; 21912 21913 final ApplicationInfo info = ps.pkg.applicationInfo; 21914 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21915 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21916 21917 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21918 "unloadPrivatePackagesInner")) { 21919 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21920 false, null)) { 21921 unloaded.add(info); 21922 } else { 21923 Slog.w(TAG, "Failed to unload " + ps.codePath); 21924 } 21925 } 21926 21927 // Try very hard to release any references to this package 21928 // so we don't risk the system server being killed due to 21929 // open FDs 21930 AttributeCache.instance().removePackage(ps.name); 21931 } 21932 21933 mSettings.writeLPr(); 21934 } 21935 } 21936 21937 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21938 sendResourcesChangedBroadcast(false, false, unloaded, null); 21939 mLoadedVolumes.remove(vol.getId()); 21940 21941 // Try very hard to release any references to this path so we don't risk 21942 // the system server being killed due to open FDs 21943 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21944 21945 for (int i = 0; i < 3; i++) { 21946 System.gc(); 21947 System.runFinalization(); 21948 } 21949 } 21950 21951 private void assertPackageKnown(String volumeUuid, String packageName) 21952 throws PackageManagerException { 21953 synchronized (mPackages) { 21954 // Normalize package name to handle renamed packages 21955 packageName = normalizePackageNameLPr(packageName); 21956 21957 final PackageSetting ps = mSettings.mPackages.get(packageName); 21958 if (ps == null) { 21959 throw new PackageManagerException("Package " + packageName + " is unknown"); 21960 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21961 throw new PackageManagerException( 21962 "Package " + packageName + " found on unknown volume " + volumeUuid 21963 + "; expected volume " + ps.volumeUuid); 21964 } 21965 } 21966 } 21967 21968 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21969 throws PackageManagerException { 21970 synchronized (mPackages) { 21971 // Normalize package name to handle renamed packages 21972 packageName = normalizePackageNameLPr(packageName); 21973 21974 final PackageSetting ps = mSettings.mPackages.get(packageName); 21975 if (ps == null) { 21976 throw new PackageManagerException("Package " + packageName + " is unknown"); 21977 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21978 throw new PackageManagerException( 21979 "Package " + packageName + " found on unknown volume " + volumeUuid 21980 + "; expected volume " + ps.volumeUuid); 21981 } else if (!ps.getInstalled(userId)) { 21982 throw new PackageManagerException( 21983 "Package " + packageName + " not installed for user " + userId); 21984 } 21985 } 21986 } 21987 21988 private List<String> collectAbsoluteCodePaths() { 21989 synchronized (mPackages) { 21990 List<String> codePaths = new ArrayList<>(); 21991 final int packageCount = mSettings.mPackages.size(); 21992 for (int i = 0; i < packageCount; i++) { 21993 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21994 codePaths.add(ps.codePath.getAbsolutePath()); 21995 } 21996 return codePaths; 21997 } 21998 } 21999 22000 /** 22001 * Examine all apps present on given mounted volume, and destroy apps that 22002 * aren't expected, either due to uninstallation or reinstallation on 22003 * another volume. 22004 */ 22005 private void reconcileApps(String volumeUuid) { 22006 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22007 List<File> filesToDelete = null; 22008 22009 final File[] files = FileUtils.listFilesOrEmpty( 22010 Environment.getDataAppDirectory(volumeUuid)); 22011 for (File file : files) { 22012 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22013 && !PackageInstallerService.isStageName(file.getName()); 22014 if (!isPackage) { 22015 // Ignore entries which are not packages 22016 continue; 22017 } 22018 22019 String absolutePath = file.getAbsolutePath(); 22020 22021 boolean pathValid = false; 22022 final int absoluteCodePathCount = absoluteCodePaths.size(); 22023 for (int i = 0; i < absoluteCodePathCount; i++) { 22024 String absoluteCodePath = absoluteCodePaths.get(i); 22025 if (absolutePath.startsWith(absoluteCodePath)) { 22026 pathValid = true; 22027 break; 22028 } 22029 } 22030 22031 if (!pathValid) { 22032 if (filesToDelete == null) { 22033 filesToDelete = new ArrayList<>(); 22034 } 22035 filesToDelete.add(file); 22036 } 22037 } 22038 22039 if (filesToDelete != null) { 22040 final int fileToDeleteCount = filesToDelete.size(); 22041 for (int i = 0; i < fileToDeleteCount; i++) { 22042 File fileToDelete = filesToDelete.get(i); 22043 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22044 synchronized (mInstallLock) { 22045 removeCodePathLI(fileToDelete); 22046 } 22047 } 22048 } 22049 } 22050 22051 /** 22052 * Reconcile all app data for the given user. 22053 * <p> 22054 * Verifies that directories exist and that ownership and labeling is 22055 * correct for all installed apps on all mounted volumes. 22056 */ 22057 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22058 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22059 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22060 final String volumeUuid = vol.getFsUuid(); 22061 synchronized (mInstallLock) { 22062 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22063 } 22064 } 22065 } 22066 22067 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22068 boolean migrateAppData) { 22069 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22070 } 22071 22072 /** 22073 * Reconcile all app data on given mounted volume. 22074 * <p> 22075 * Destroys app data that isn't expected, either due to uninstallation or 22076 * reinstallation on another volume. 22077 * <p> 22078 * Verifies that directories exist and that ownership and labeling is 22079 * correct for all installed apps. 22080 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22081 */ 22082 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22083 boolean migrateAppData, boolean onlyCoreApps) { 22084 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22085 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22086 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22087 22088 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22089 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22090 22091 // First look for stale data that doesn't belong, and check if things 22092 // have changed since we did our last restorecon 22093 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22094 if (StorageManager.isFileEncryptedNativeOrEmulated() 22095 && !StorageManager.isUserKeyUnlocked(userId)) { 22096 throw new RuntimeException( 22097 "Yikes, someone asked us to reconcile CE storage while " + userId 22098 + " was still locked; this would have caused massive data loss!"); 22099 } 22100 22101 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22102 for (File file : files) { 22103 final String packageName = file.getName(); 22104 try { 22105 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22106 } catch (PackageManagerException e) { 22107 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22108 try { 22109 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22110 StorageManager.FLAG_STORAGE_CE, 0); 22111 } catch (InstallerException e2) { 22112 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22113 } 22114 } 22115 } 22116 } 22117 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22118 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22119 for (File file : files) { 22120 final String packageName = file.getName(); 22121 try { 22122 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22123 } catch (PackageManagerException e) { 22124 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22125 try { 22126 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22127 StorageManager.FLAG_STORAGE_DE, 0); 22128 } catch (InstallerException e2) { 22129 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22130 } 22131 } 22132 } 22133 } 22134 22135 // Ensure that data directories are ready to roll for all packages 22136 // installed for this volume and user 22137 final List<PackageSetting> packages; 22138 synchronized (mPackages) { 22139 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22140 } 22141 int preparedCount = 0; 22142 for (PackageSetting ps : packages) { 22143 final String packageName = ps.name; 22144 if (ps.pkg == null) { 22145 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22146 // TODO: might be due to legacy ASEC apps; we should circle back 22147 // and reconcile again once they're scanned 22148 continue; 22149 } 22150 // Skip non-core apps if requested 22151 if (onlyCoreApps && !ps.pkg.coreApp) { 22152 result.add(packageName); 22153 continue; 22154 } 22155 22156 if (ps.getInstalled(userId)) { 22157 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22158 preparedCount++; 22159 } 22160 } 22161 22162 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22163 return result; 22164 } 22165 22166 /** 22167 * Prepare app data for the given app just after it was installed or 22168 * upgraded. This method carefully only touches users that it's installed 22169 * for, and it forces a restorecon to handle any seinfo changes. 22170 * <p> 22171 * Verifies that directories exist and that ownership and labeling is 22172 * correct for all installed apps. If there is an ownership mismatch, it 22173 * will try recovering system apps by wiping data; third-party app data is 22174 * left intact. 22175 * <p> 22176 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22177 */ 22178 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22179 final PackageSetting ps; 22180 synchronized (mPackages) { 22181 ps = mSettings.mPackages.get(pkg.packageName); 22182 mSettings.writeKernelMappingLPr(ps); 22183 } 22184 22185 final UserManager um = mContext.getSystemService(UserManager.class); 22186 UserManagerInternal umInternal = getUserManagerInternal(); 22187 for (UserInfo user : um.getUsers()) { 22188 final int flags; 22189 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22190 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22191 } else if (umInternal.isUserRunning(user.id)) { 22192 flags = StorageManager.FLAG_STORAGE_DE; 22193 } else { 22194 continue; 22195 } 22196 22197 if (ps.getInstalled(user.id)) { 22198 // TODO: when user data is locked, mark that we're still dirty 22199 prepareAppDataLIF(pkg, user.id, flags); 22200 } 22201 } 22202 } 22203 22204 /** 22205 * Prepare app data for the given app. 22206 * <p> 22207 * Verifies that directories exist and that ownership and labeling is 22208 * correct for all installed apps. If there is an ownership mismatch, this 22209 * will try recovering system apps by wiping data; third-party app data is 22210 * left intact. 22211 */ 22212 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22213 if (pkg == null) { 22214 Slog.wtf(TAG, "Package was null!", new Throwable()); 22215 return; 22216 } 22217 prepareAppDataLeafLIF(pkg, userId, flags); 22218 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22219 for (int i = 0; i < childCount; i++) { 22220 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22221 } 22222 } 22223 22224 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22225 boolean maybeMigrateAppData) { 22226 prepareAppDataLIF(pkg, userId, flags); 22227 22228 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22229 // We may have just shuffled around app data directories, so 22230 // prepare them one more time 22231 prepareAppDataLIF(pkg, userId, flags); 22232 } 22233 } 22234 22235 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22236 if (DEBUG_APP_DATA) { 22237 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22238 + Integer.toHexString(flags)); 22239 } 22240 22241 final String volumeUuid = pkg.volumeUuid; 22242 final String packageName = pkg.packageName; 22243 final ApplicationInfo app = pkg.applicationInfo; 22244 final int appId = UserHandle.getAppId(app.uid); 22245 22246 Preconditions.checkNotNull(app.seInfo); 22247 22248 long ceDataInode = -1; 22249 try { 22250 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22251 appId, app.seInfo, app.targetSdkVersion); 22252 } catch (InstallerException e) { 22253 if (app.isSystemApp()) { 22254 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22255 + ", but trying to recover: " + e); 22256 destroyAppDataLeafLIF(pkg, userId, flags); 22257 try { 22258 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22259 appId, app.seInfo, app.targetSdkVersion); 22260 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22261 } catch (InstallerException e2) { 22262 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22263 } 22264 } else { 22265 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22266 } 22267 } 22268 // Prepare the application profiles. 22269 mArtManagerService.prepareAppProfiles(pkg, userId); 22270 22271 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22272 // TODO: mark this structure as dirty so we persist it! 22273 synchronized (mPackages) { 22274 final PackageSetting ps = mSettings.mPackages.get(packageName); 22275 if (ps != null) { 22276 ps.setCeDataInode(ceDataInode, userId); 22277 } 22278 } 22279 } 22280 22281 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22282 } 22283 22284 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22285 if (pkg == null) { 22286 Slog.wtf(TAG, "Package was null!", new Throwable()); 22287 return; 22288 } 22289 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22290 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22291 for (int i = 0; i < childCount; i++) { 22292 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22293 } 22294 } 22295 22296 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22297 final String volumeUuid = pkg.volumeUuid; 22298 final String packageName = pkg.packageName; 22299 final ApplicationInfo app = pkg.applicationInfo; 22300 22301 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22302 // Create a native library symlink only if we have native libraries 22303 // and if the native libraries are 32 bit libraries. We do not provide 22304 // this symlink for 64 bit libraries. 22305 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22306 final String nativeLibPath = app.nativeLibraryDir; 22307 try { 22308 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22309 nativeLibPath, userId); 22310 } catch (InstallerException e) { 22311 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22312 } 22313 } 22314 } 22315 } 22316 22317 /** 22318 * For system apps on non-FBE devices, this method migrates any existing 22319 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22320 * requested by the app. 22321 */ 22322 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22323 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22324 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22325 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22326 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22327 try { 22328 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22329 storageTarget); 22330 } catch (InstallerException e) { 22331 logCriticalInfo(Log.WARN, 22332 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22333 } 22334 return true; 22335 } else { 22336 return false; 22337 } 22338 } 22339 22340 public PackageFreezer freezePackage(String packageName, String killReason) { 22341 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22342 } 22343 22344 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22345 return new PackageFreezer(packageName, userId, killReason); 22346 } 22347 22348 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22349 String killReason) { 22350 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22351 } 22352 22353 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22354 String killReason) { 22355 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22356 return new PackageFreezer(); 22357 } else { 22358 return freezePackage(packageName, userId, killReason); 22359 } 22360 } 22361 22362 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22363 String killReason) { 22364 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22365 } 22366 22367 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22368 String killReason) { 22369 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22370 return new PackageFreezer(); 22371 } else { 22372 return freezePackage(packageName, userId, killReason); 22373 } 22374 } 22375 22376 /** 22377 * Class that freezes and kills the given package upon creation, and 22378 * unfreezes it upon closing. This is typically used when doing surgery on 22379 * app code/data to prevent the app from running while you're working. 22380 */ 22381 private class PackageFreezer implements AutoCloseable { 22382 private final String mPackageName; 22383 private final PackageFreezer[] mChildren; 22384 22385 private final boolean mWeFroze; 22386 22387 private final AtomicBoolean mClosed = new AtomicBoolean(); 22388 private final CloseGuard mCloseGuard = CloseGuard.get(); 22389 22390 /** 22391 * Create and return a stub freezer that doesn't actually do anything, 22392 * typically used when someone requested 22393 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22394 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22395 */ 22396 public PackageFreezer() { 22397 mPackageName = null; 22398 mChildren = null; 22399 mWeFroze = false; 22400 mCloseGuard.open("close"); 22401 } 22402 22403 public PackageFreezer(String packageName, int userId, String killReason) { 22404 synchronized (mPackages) { 22405 mPackageName = packageName; 22406 mWeFroze = mFrozenPackages.add(mPackageName); 22407 22408 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22409 if (ps != null) { 22410 killApplication(ps.name, ps.appId, userId, killReason); 22411 } 22412 22413 final PackageParser.Package p = mPackages.get(packageName); 22414 if (p != null && p.childPackages != null) { 22415 final int N = p.childPackages.size(); 22416 mChildren = new PackageFreezer[N]; 22417 for (int i = 0; i < N; i++) { 22418 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22419 userId, killReason); 22420 } 22421 } else { 22422 mChildren = null; 22423 } 22424 } 22425 mCloseGuard.open("close"); 22426 } 22427 22428 @Override 22429 protected void finalize() throws Throwable { 22430 try { 22431 if (mCloseGuard != null) { 22432 mCloseGuard.warnIfOpen(); 22433 } 22434 22435 close(); 22436 } finally { 22437 super.finalize(); 22438 } 22439 } 22440 22441 @Override 22442 public void close() { 22443 mCloseGuard.close(); 22444 if (mClosed.compareAndSet(false, true)) { 22445 synchronized (mPackages) { 22446 if (mWeFroze) { 22447 mFrozenPackages.remove(mPackageName); 22448 } 22449 22450 if (mChildren != null) { 22451 for (PackageFreezer freezer : mChildren) { 22452 freezer.close(); 22453 } 22454 } 22455 } 22456 } 22457 } 22458 } 22459 22460 /** 22461 * Verify that given package is currently frozen. 22462 */ 22463 private void checkPackageFrozen(String packageName) { 22464 synchronized (mPackages) { 22465 if (!mFrozenPackages.contains(packageName)) { 22466 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22467 } 22468 } 22469 } 22470 22471 @Override 22472 public int movePackage(final String packageName, final String volumeUuid) { 22473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22474 22475 final int callingUid = Binder.getCallingUid(); 22476 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22477 final int moveId = mNextMoveId.getAndIncrement(); 22478 mHandler.post(new Runnable() { 22479 @Override 22480 public void run() { 22481 try { 22482 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22483 } catch (PackageManagerException e) { 22484 Slog.w(TAG, "Failed to move " + packageName, e); 22485 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22486 } 22487 } 22488 }); 22489 return moveId; 22490 } 22491 22492 private void movePackageInternal(final String packageName, final String volumeUuid, 22493 final int moveId, final int callingUid, UserHandle user) 22494 throws PackageManagerException { 22495 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22496 final PackageManager pm = mContext.getPackageManager(); 22497 22498 final boolean currentAsec; 22499 final String currentVolumeUuid; 22500 final File codeFile; 22501 final String installerPackageName; 22502 final String packageAbiOverride; 22503 final int appId; 22504 final String seinfo; 22505 final String label; 22506 final int targetSdkVersion; 22507 final PackageFreezer freezer; 22508 final int[] installedUserIds; 22509 22510 // reader 22511 synchronized (mPackages) { 22512 final PackageParser.Package pkg = mPackages.get(packageName); 22513 final PackageSetting ps = mSettings.mPackages.get(packageName); 22514 if (pkg == null 22515 || ps == null 22516 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22517 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22518 } 22519 if (pkg.applicationInfo.isSystemApp()) { 22520 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22521 "Cannot move system application"); 22522 } 22523 22524 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22525 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22526 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22527 if (isInternalStorage && !allow3rdPartyOnInternal) { 22528 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22529 "3rd party apps are not allowed on internal storage"); 22530 } 22531 22532 if (pkg.applicationInfo.isExternalAsec()) { 22533 currentAsec = true; 22534 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22535 } else if (pkg.applicationInfo.isForwardLocked()) { 22536 currentAsec = true; 22537 currentVolumeUuid = "forward_locked"; 22538 } else { 22539 currentAsec = false; 22540 currentVolumeUuid = ps.volumeUuid; 22541 22542 final File probe = new File(pkg.codePath); 22543 final File probeOat = new File(probe, "oat"); 22544 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22545 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22546 "Move only supported for modern cluster style installs"); 22547 } 22548 } 22549 22550 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22551 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22552 "Package already moved to " + volumeUuid); 22553 } 22554 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22555 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22556 "Device admin cannot be moved"); 22557 } 22558 22559 if (mFrozenPackages.contains(packageName)) { 22560 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22561 "Failed to move already frozen package"); 22562 } 22563 22564 codeFile = new File(pkg.codePath); 22565 installerPackageName = ps.installerPackageName; 22566 packageAbiOverride = ps.cpuAbiOverrideString; 22567 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22568 seinfo = pkg.applicationInfo.seInfo; 22569 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22570 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22571 freezer = freezePackage(packageName, "movePackageInternal"); 22572 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22573 } 22574 22575 final Bundle extras = new Bundle(); 22576 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22577 extras.putString(Intent.EXTRA_TITLE, label); 22578 mMoveCallbacks.notifyCreated(moveId, extras); 22579 22580 int installFlags; 22581 final boolean moveCompleteApp; 22582 final File measurePath; 22583 22584 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22585 installFlags = INSTALL_INTERNAL; 22586 moveCompleteApp = !currentAsec; 22587 measurePath = Environment.getDataAppDirectory(volumeUuid); 22588 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22589 installFlags = INSTALL_EXTERNAL; 22590 moveCompleteApp = false; 22591 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22592 } else { 22593 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22594 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22595 || !volume.isMountedWritable()) { 22596 freezer.close(); 22597 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22598 "Move location not mounted private volume"); 22599 } 22600 22601 Preconditions.checkState(!currentAsec); 22602 22603 installFlags = INSTALL_INTERNAL; 22604 moveCompleteApp = true; 22605 measurePath = Environment.getDataAppDirectory(volumeUuid); 22606 } 22607 22608 // If we're moving app data around, we need all the users unlocked 22609 if (moveCompleteApp) { 22610 for (int userId : installedUserIds) { 22611 if (StorageManager.isFileEncryptedNativeOrEmulated() 22612 && !StorageManager.isUserKeyUnlocked(userId)) { 22613 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22614 "User " + userId + " must be unlocked"); 22615 } 22616 } 22617 } 22618 22619 final PackageStats stats = new PackageStats(null, -1); 22620 synchronized (mInstaller) { 22621 for (int userId : installedUserIds) { 22622 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22623 freezer.close(); 22624 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22625 "Failed to measure package size"); 22626 } 22627 } 22628 } 22629 22630 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22631 + stats.dataSize); 22632 22633 final long startFreeBytes = measurePath.getUsableSpace(); 22634 final long sizeBytes; 22635 if (moveCompleteApp) { 22636 sizeBytes = stats.codeSize + stats.dataSize; 22637 } else { 22638 sizeBytes = stats.codeSize; 22639 } 22640 22641 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22642 freezer.close(); 22643 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22644 "Not enough free space to move"); 22645 } 22646 22647 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22648 22649 final CountDownLatch installedLatch = new CountDownLatch(1); 22650 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22651 @Override 22652 public void onUserActionRequired(Intent intent) throws RemoteException { 22653 throw new IllegalStateException(); 22654 } 22655 22656 @Override 22657 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22658 Bundle extras) throws RemoteException { 22659 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22660 + PackageManager.installStatusToString(returnCode, msg)); 22661 22662 installedLatch.countDown(); 22663 freezer.close(); 22664 22665 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22666 switch (status) { 22667 case PackageInstaller.STATUS_SUCCESS: 22668 mMoveCallbacks.notifyStatusChanged(moveId, 22669 PackageManager.MOVE_SUCCEEDED); 22670 break; 22671 case PackageInstaller.STATUS_FAILURE_STORAGE: 22672 mMoveCallbacks.notifyStatusChanged(moveId, 22673 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22674 break; 22675 default: 22676 mMoveCallbacks.notifyStatusChanged(moveId, 22677 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22678 break; 22679 } 22680 } 22681 }; 22682 22683 final MoveInfo move; 22684 if (moveCompleteApp) { 22685 // Kick off a thread to report progress estimates 22686 new Thread() { 22687 @Override 22688 public void run() { 22689 while (true) { 22690 try { 22691 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22692 break; 22693 } 22694 } catch (InterruptedException ignored) { 22695 } 22696 22697 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22698 final int progress = 10 + (int) MathUtils.constrain( 22699 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22700 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22701 } 22702 } 22703 }.start(); 22704 22705 final String dataAppName = codeFile.getName(); 22706 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22707 dataAppName, appId, seinfo, targetSdkVersion); 22708 } else { 22709 move = null; 22710 } 22711 22712 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22713 22714 final Message msg = mHandler.obtainMessage(INIT_COPY); 22715 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22716 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22717 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22718 packageAbiOverride, null /*grantedPermissions*/, 22719 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22720 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22721 msg.obj = params; 22722 22723 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22724 System.identityHashCode(msg.obj)); 22725 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22726 System.identityHashCode(msg.obj)); 22727 22728 mHandler.sendMessage(msg); 22729 } 22730 22731 @Override 22732 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22733 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22734 22735 final int realMoveId = mNextMoveId.getAndIncrement(); 22736 final Bundle extras = new Bundle(); 22737 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22738 mMoveCallbacks.notifyCreated(realMoveId, extras); 22739 22740 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22741 @Override 22742 public void onCreated(int moveId, Bundle extras) { 22743 // Ignored 22744 } 22745 22746 @Override 22747 public void onStatusChanged(int moveId, int status, long estMillis) { 22748 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22749 } 22750 }; 22751 22752 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22753 storage.setPrimaryStorageUuid(volumeUuid, callback); 22754 return realMoveId; 22755 } 22756 22757 @Override 22758 public int getMoveStatus(int moveId) { 22759 mContext.enforceCallingOrSelfPermission( 22760 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22761 return mMoveCallbacks.mLastStatus.get(moveId); 22762 } 22763 22764 @Override 22765 public void registerMoveCallback(IPackageMoveObserver callback) { 22766 mContext.enforceCallingOrSelfPermission( 22767 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22768 mMoveCallbacks.register(callback); 22769 } 22770 22771 @Override 22772 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22773 mContext.enforceCallingOrSelfPermission( 22774 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22775 mMoveCallbacks.unregister(callback); 22776 } 22777 22778 @Override 22779 public boolean setInstallLocation(int loc) { 22780 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22781 null); 22782 if (getInstallLocation() == loc) { 22783 return true; 22784 } 22785 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22786 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22787 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22788 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22789 return true; 22790 } 22791 return false; 22792 } 22793 22794 @Override 22795 public int getInstallLocation() { 22796 // allow instant app access 22797 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22798 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22799 PackageHelper.APP_INSTALL_AUTO); 22800 } 22801 22802 /** Called by UserManagerService */ 22803 void cleanUpUser(UserManagerService userManager, int userHandle) { 22804 synchronized (mPackages) { 22805 mDirtyUsers.remove(userHandle); 22806 mUserNeedsBadging.delete(userHandle); 22807 mSettings.removeUserLPw(userHandle); 22808 mPendingBroadcasts.remove(userHandle); 22809 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22810 removeUnusedPackagesLPw(userManager, userHandle); 22811 } 22812 } 22813 22814 /** 22815 * We're removing userHandle and would like to remove any downloaded packages 22816 * that are no longer in use by any other user. 22817 * @param userHandle the user being removed 22818 */ 22819 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22820 final boolean DEBUG_CLEAN_APKS = false; 22821 int [] users = userManager.getUserIds(); 22822 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22823 while (psit.hasNext()) { 22824 PackageSetting ps = psit.next(); 22825 if (ps.pkg == null) { 22826 continue; 22827 } 22828 final String packageName = ps.pkg.packageName; 22829 // Skip over if system app 22830 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22831 continue; 22832 } 22833 if (DEBUG_CLEAN_APKS) { 22834 Slog.i(TAG, "Checking package " + packageName); 22835 } 22836 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22837 if (keep) { 22838 if (DEBUG_CLEAN_APKS) { 22839 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22840 } 22841 } else { 22842 for (int i = 0; i < users.length; i++) { 22843 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22844 keep = true; 22845 if (DEBUG_CLEAN_APKS) { 22846 Slog.i(TAG, " Keeping package " + packageName + " for user " 22847 + users[i]); 22848 } 22849 break; 22850 } 22851 } 22852 } 22853 if (!keep) { 22854 if (DEBUG_CLEAN_APKS) { 22855 Slog.i(TAG, " Removing package " + packageName); 22856 } 22857 mHandler.post(new Runnable() { 22858 public void run() { 22859 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22860 userHandle, 0); 22861 } //end run 22862 }); 22863 } 22864 } 22865 } 22866 22867 /** Called by UserManagerService */ 22868 void createNewUser(int userId, String[] disallowedPackages) { 22869 synchronized (mInstallLock) { 22870 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22871 } 22872 synchronized (mPackages) { 22873 scheduleWritePackageRestrictionsLocked(userId); 22874 scheduleWritePackageListLocked(userId); 22875 applyFactoryDefaultBrowserLPw(userId); 22876 primeDomainVerificationsLPw(userId); 22877 } 22878 } 22879 22880 void onNewUserCreated(final int userId) { 22881 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22882 synchronized(mPackages) { 22883 // If permission review for legacy apps is required, we represent 22884 // dagerous permissions for such apps as always granted runtime 22885 // permissions to keep per user flag state whether review is needed. 22886 // Hence, if a new user is added we have to propagate dangerous 22887 // permission grants for these legacy apps. 22888 if (mSettings.mPermissions.mPermissionReviewRequired) { 22889// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22890 mPermissionManager.updateAllPermissions( 22891 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22892 mPermissionCallback); 22893 } 22894 } 22895 } 22896 22897 @Override 22898 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22899 mContext.enforceCallingOrSelfPermission( 22900 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22901 "Only package verification agents can read the verifier device identity"); 22902 22903 synchronized (mPackages) { 22904 return mSettings.getVerifierDeviceIdentityLPw(); 22905 } 22906 } 22907 22908 @Override 22909 public void setPermissionEnforced(String permission, boolean enforced) { 22910 // TODO: Now that we no longer change GID for storage, this should to away. 22911 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22912 "setPermissionEnforced"); 22913 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22914 synchronized (mPackages) { 22915 if (mSettings.mReadExternalStorageEnforced == null 22916 || mSettings.mReadExternalStorageEnforced != enforced) { 22917 mSettings.mReadExternalStorageEnforced = 22918 enforced ? Boolean.TRUE : Boolean.FALSE; 22919 mSettings.writeLPr(); 22920 } 22921 } 22922 // kill any non-foreground processes so we restart them and 22923 // grant/revoke the GID. 22924 final IActivityManager am = ActivityManager.getService(); 22925 if (am != null) { 22926 final long token = Binder.clearCallingIdentity(); 22927 try { 22928 am.killProcessesBelowForeground("setPermissionEnforcement"); 22929 } catch (RemoteException e) { 22930 } finally { 22931 Binder.restoreCallingIdentity(token); 22932 } 22933 } 22934 } else { 22935 throw new IllegalArgumentException("No selective enforcement for " + permission); 22936 } 22937 } 22938 22939 @Override 22940 @Deprecated 22941 public boolean isPermissionEnforced(String permission) { 22942 // allow instant applications 22943 return true; 22944 } 22945 22946 @Override 22947 public boolean isStorageLow() { 22948 // allow instant applications 22949 final long token = Binder.clearCallingIdentity(); 22950 try { 22951 final DeviceStorageMonitorInternal 22952 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22953 if (dsm != null) { 22954 return dsm.isMemoryLow(); 22955 } else { 22956 return false; 22957 } 22958 } finally { 22959 Binder.restoreCallingIdentity(token); 22960 } 22961 } 22962 22963 @Override 22964 public IPackageInstaller getPackageInstaller() { 22965 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22966 return null; 22967 } 22968 return mInstallerService; 22969 } 22970 22971 @Override 22972 public IArtManager getArtManager() { 22973 return mArtManagerService; 22974 } 22975 22976 private boolean userNeedsBadging(int userId) { 22977 int index = mUserNeedsBadging.indexOfKey(userId); 22978 if (index < 0) { 22979 final UserInfo userInfo; 22980 final long token = Binder.clearCallingIdentity(); 22981 try { 22982 userInfo = sUserManager.getUserInfo(userId); 22983 } finally { 22984 Binder.restoreCallingIdentity(token); 22985 } 22986 final boolean b; 22987 if (userInfo != null && userInfo.isManagedProfile()) { 22988 b = true; 22989 } else { 22990 b = false; 22991 } 22992 mUserNeedsBadging.put(userId, b); 22993 return b; 22994 } 22995 return mUserNeedsBadging.valueAt(index); 22996 } 22997 22998 @Override 22999 public KeySet getKeySetByAlias(String packageName, String alias) { 23000 if (packageName == null || alias == null) { 23001 return null; 23002 } 23003 synchronized(mPackages) { 23004 final PackageParser.Package pkg = mPackages.get(packageName); 23005 if (pkg == null) { 23006 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23007 throw new IllegalArgumentException("Unknown package: " + packageName); 23008 } 23009 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23010 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23011 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23012 throw new IllegalArgumentException("Unknown package: " + packageName); 23013 } 23014 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23015 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23016 } 23017 } 23018 23019 @Override 23020 public KeySet getSigningKeySet(String packageName) { 23021 if (packageName == null) { 23022 return null; 23023 } 23024 synchronized(mPackages) { 23025 final int callingUid = Binder.getCallingUid(); 23026 final int callingUserId = UserHandle.getUserId(callingUid); 23027 final PackageParser.Package pkg = mPackages.get(packageName); 23028 if (pkg == null) { 23029 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23030 throw new IllegalArgumentException("Unknown package: " + packageName); 23031 } 23032 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23033 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23034 // filter and pretend the package doesn't exist 23035 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23036 + ", uid:" + callingUid); 23037 throw new IllegalArgumentException("Unknown package: " + packageName); 23038 } 23039 if (pkg.applicationInfo.uid != callingUid 23040 && Process.SYSTEM_UID != callingUid) { 23041 throw new SecurityException("May not access signing KeySet of other apps."); 23042 } 23043 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23044 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23045 } 23046 } 23047 23048 @Override 23049 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23050 final int callingUid = Binder.getCallingUid(); 23051 if (getInstantAppPackageName(callingUid) != null) { 23052 return false; 23053 } 23054 if (packageName == null || ks == null) { 23055 return false; 23056 } 23057 synchronized(mPackages) { 23058 final PackageParser.Package pkg = mPackages.get(packageName); 23059 if (pkg == null 23060 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23061 UserHandle.getUserId(callingUid))) { 23062 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23063 throw new IllegalArgumentException("Unknown package: " + packageName); 23064 } 23065 IBinder ksh = ks.getToken(); 23066 if (ksh instanceof KeySetHandle) { 23067 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23068 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23069 } 23070 return false; 23071 } 23072 } 23073 23074 @Override 23075 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23076 final int callingUid = Binder.getCallingUid(); 23077 if (getInstantAppPackageName(callingUid) != null) { 23078 return false; 23079 } 23080 if (packageName == null || ks == null) { 23081 return false; 23082 } 23083 synchronized(mPackages) { 23084 final PackageParser.Package pkg = mPackages.get(packageName); 23085 if (pkg == null 23086 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23087 UserHandle.getUserId(callingUid))) { 23088 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23089 throw new IllegalArgumentException("Unknown package: " + packageName); 23090 } 23091 IBinder ksh = ks.getToken(); 23092 if (ksh instanceof KeySetHandle) { 23093 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23094 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23095 } 23096 return false; 23097 } 23098 } 23099 23100 private void deletePackageIfUnusedLPr(final String packageName) { 23101 PackageSetting ps = mSettings.mPackages.get(packageName); 23102 if (ps == null) { 23103 return; 23104 } 23105 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23106 // TODO Implement atomic delete if package is unused 23107 // It is currently possible that the package will be deleted even if it is installed 23108 // after this method returns. 23109 mHandler.post(new Runnable() { 23110 public void run() { 23111 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23112 0, PackageManager.DELETE_ALL_USERS); 23113 } 23114 }); 23115 } 23116 } 23117 23118 /** 23119 * Check and throw if the given before/after packages would be considered a 23120 * downgrade. 23121 */ 23122 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23123 throws PackageManagerException { 23124 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23125 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23126 "Update version code " + after.versionCode + " is older than current " 23127 + before.getLongVersionCode()); 23128 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23129 if (after.baseRevisionCode < before.baseRevisionCode) { 23130 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23131 "Update base revision code " + after.baseRevisionCode 23132 + " is older than current " + before.baseRevisionCode); 23133 } 23134 23135 if (!ArrayUtils.isEmpty(after.splitNames)) { 23136 for (int i = 0; i < after.splitNames.length; i++) { 23137 final String splitName = after.splitNames[i]; 23138 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23139 if (j != -1) { 23140 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23141 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23142 "Update split " + splitName + " revision code " 23143 + after.splitRevisionCodes[i] + " is older than current " 23144 + before.splitRevisionCodes[j]); 23145 } 23146 } 23147 } 23148 } 23149 } 23150 } 23151 23152 private static class MoveCallbacks extends Handler { 23153 private static final int MSG_CREATED = 1; 23154 private static final int MSG_STATUS_CHANGED = 2; 23155 23156 private final RemoteCallbackList<IPackageMoveObserver> 23157 mCallbacks = new RemoteCallbackList<>(); 23158 23159 private final SparseIntArray mLastStatus = new SparseIntArray(); 23160 23161 public MoveCallbacks(Looper looper) { 23162 super(looper); 23163 } 23164 23165 public void register(IPackageMoveObserver callback) { 23166 mCallbacks.register(callback); 23167 } 23168 23169 public void unregister(IPackageMoveObserver callback) { 23170 mCallbacks.unregister(callback); 23171 } 23172 23173 @Override 23174 public void handleMessage(Message msg) { 23175 final SomeArgs args = (SomeArgs) msg.obj; 23176 final int n = mCallbacks.beginBroadcast(); 23177 for (int i = 0; i < n; i++) { 23178 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23179 try { 23180 invokeCallback(callback, msg.what, args); 23181 } catch (RemoteException ignored) { 23182 } 23183 } 23184 mCallbacks.finishBroadcast(); 23185 args.recycle(); 23186 } 23187 23188 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23189 throws RemoteException { 23190 switch (what) { 23191 case MSG_CREATED: { 23192 callback.onCreated(args.argi1, (Bundle) args.arg2); 23193 break; 23194 } 23195 case MSG_STATUS_CHANGED: { 23196 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23197 break; 23198 } 23199 } 23200 } 23201 23202 private void notifyCreated(int moveId, Bundle extras) { 23203 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23204 23205 final SomeArgs args = SomeArgs.obtain(); 23206 args.argi1 = moveId; 23207 args.arg2 = extras; 23208 obtainMessage(MSG_CREATED, args).sendToTarget(); 23209 } 23210 23211 private void notifyStatusChanged(int moveId, int status) { 23212 notifyStatusChanged(moveId, status, -1); 23213 } 23214 23215 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23216 Slog.v(TAG, "Move " + moveId + " status " + status); 23217 23218 final SomeArgs args = SomeArgs.obtain(); 23219 args.argi1 = moveId; 23220 args.argi2 = status; 23221 args.arg3 = estMillis; 23222 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23223 23224 synchronized (mLastStatus) { 23225 mLastStatus.put(moveId, status); 23226 } 23227 } 23228 } 23229 23230 private final static class OnPermissionChangeListeners extends Handler { 23231 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23232 23233 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23234 new RemoteCallbackList<>(); 23235 23236 public OnPermissionChangeListeners(Looper looper) { 23237 super(looper); 23238 } 23239 23240 @Override 23241 public void handleMessage(Message msg) { 23242 switch (msg.what) { 23243 case MSG_ON_PERMISSIONS_CHANGED: { 23244 final int uid = msg.arg1; 23245 handleOnPermissionsChanged(uid); 23246 } break; 23247 } 23248 } 23249 23250 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23251 mPermissionListeners.register(listener); 23252 23253 } 23254 23255 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23256 mPermissionListeners.unregister(listener); 23257 } 23258 23259 public void onPermissionsChanged(int uid) { 23260 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23261 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23262 } 23263 } 23264 23265 private void handleOnPermissionsChanged(int uid) { 23266 final int count = mPermissionListeners.beginBroadcast(); 23267 try { 23268 for (int i = 0; i < count; i++) { 23269 IOnPermissionsChangeListener callback = mPermissionListeners 23270 .getBroadcastItem(i); 23271 try { 23272 callback.onPermissionsChanged(uid); 23273 } catch (RemoteException e) { 23274 Log.e(TAG, "Permission listener is dead", e); 23275 } 23276 } 23277 } finally { 23278 mPermissionListeners.finishBroadcast(); 23279 } 23280 } 23281 } 23282 23283 private class PackageManagerNative extends IPackageManagerNative.Stub { 23284 @Override 23285 public String[] getNamesForUids(int[] uids) throws RemoteException { 23286 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23287 // massage results so they can be parsed by the native binder 23288 for (int i = results.length - 1; i >= 0; --i) { 23289 if (results[i] == null) { 23290 results[i] = ""; 23291 } 23292 } 23293 return results; 23294 } 23295 23296 // NB: this differentiates between preloads and sideloads 23297 @Override 23298 public String getInstallerForPackage(String packageName) throws RemoteException { 23299 final String installerName = getInstallerPackageName(packageName); 23300 if (!TextUtils.isEmpty(installerName)) { 23301 return installerName; 23302 } 23303 // differentiate between preload and sideload 23304 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23305 ApplicationInfo appInfo = getApplicationInfo(packageName, 23306 /*flags*/ 0, 23307 /*userId*/ callingUser); 23308 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23309 return "preload"; 23310 } 23311 return ""; 23312 } 23313 23314 @Override 23315 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23316 try { 23317 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23318 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23319 if (pInfo != null) { 23320 return pInfo.getLongVersionCode(); 23321 } 23322 } catch (Exception e) { 23323 } 23324 return 0; 23325 } 23326 } 23327 23328 private class PackageManagerInternalImpl extends PackageManagerInternal { 23329 @Override 23330 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23331 int flagValues, int userId) { 23332 PackageManagerService.this.updatePermissionFlags( 23333 permName, packageName, flagMask, flagValues, userId); 23334 } 23335 23336 @Override 23337 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23338 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23339 } 23340 23341 @Override 23342 public boolean isInstantApp(String packageName, int userId) { 23343 return PackageManagerService.this.isInstantApp(packageName, userId); 23344 } 23345 23346 @Override 23347 public String getInstantAppPackageName(int uid) { 23348 return PackageManagerService.this.getInstantAppPackageName(uid); 23349 } 23350 23351 @Override 23352 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23353 synchronized (mPackages) { 23354 return PackageManagerService.this.filterAppAccessLPr( 23355 (PackageSetting) pkg.mExtras, callingUid, userId); 23356 } 23357 } 23358 23359 @Override 23360 public PackageParser.Package getPackage(String packageName) { 23361 synchronized (mPackages) { 23362 packageName = resolveInternalPackageNameLPr( 23363 packageName, PackageManager.VERSION_CODE_HIGHEST); 23364 return mPackages.get(packageName); 23365 } 23366 } 23367 23368 @Override 23369 public PackageList getPackageList(PackageListObserver observer) { 23370 synchronized (mPackages) { 23371 final int N = mPackages.size(); 23372 final ArrayList<String> list = new ArrayList<>(N); 23373 for (int i = 0; i < N; i++) { 23374 list.add(mPackages.keyAt(i)); 23375 } 23376 final PackageList packageList = new PackageList(list, observer); 23377 if (observer != null) { 23378 mPackageListObservers.add(packageList); 23379 } 23380 return packageList; 23381 } 23382 } 23383 23384 @Override 23385 public void removePackageListObserver(PackageListObserver observer) { 23386 synchronized (mPackages) { 23387 mPackageListObservers.remove(observer); 23388 } 23389 } 23390 23391 @Override 23392 public PackageParser.Package getDisabledPackage(String packageName) { 23393 synchronized (mPackages) { 23394 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23395 return (ps != null) ? ps.pkg : null; 23396 } 23397 } 23398 23399 @Override 23400 public String getKnownPackageName(int knownPackage, int userId) { 23401 switch(knownPackage) { 23402 case PackageManagerInternal.PACKAGE_BROWSER: 23403 return getDefaultBrowserPackageName(userId); 23404 case PackageManagerInternal.PACKAGE_INSTALLER: 23405 return mRequiredInstallerPackage; 23406 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23407 return mSetupWizardPackage; 23408 case PackageManagerInternal.PACKAGE_SYSTEM: 23409 return "android"; 23410 case PackageManagerInternal.PACKAGE_VERIFIER: 23411 return mRequiredVerifierPackage; 23412 } 23413 return null; 23414 } 23415 23416 @Override 23417 public boolean isResolveActivityComponent(ComponentInfo component) { 23418 return mResolveActivity.packageName.equals(component.packageName) 23419 && mResolveActivity.name.equals(component.name); 23420 } 23421 23422 @Override 23423 public void setLocationPackagesProvider(PackagesProvider provider) { 23424 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23425 } 23426 23427 @Override 23428 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23429 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23430 } 23431 23432 @Override 23433 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23434 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23435 } 23436 23437 @Override 23438 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23439 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23440 } 23441 23442 @Override 23443 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23444 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23445 } 23446 23447 @Override 23448 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23449 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23450 } 23451 23452 @Override 23453 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23454 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23455 } 23456 23457 @Override 23458 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23459 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23460 } 23461 23462 @Override 23463 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23464 synchronized (mPackages) { 23465 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23466 } 23467 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23468 } 23469 23470 @Override 23471 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23472 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23473 packageName, userId); 23474 } 23475 23476 @Override 23477 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23478 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23479 packageName, userId); 23480 } 23481 23482 @Override 23483 public void setKeepUninstalledPackages(final List<String> packageList) { 23484 Preconditions.checkNotNull(packageList); 23485 List<String> removedFromList = null; 23486 synchronized (mPackages) { 23487 if (mKeepUninstalledPackages != null) { 23488 final int packagesCount = mKeepUninstalledPackages.size(); 23489 for (int i = 0; i < packagesCount; i++) { 23490 String oldPackage = mKeepUninstalledPackages.get(i); 23491 if (packageList != null && packageList.contains(oldPackage)) { 23492 continue; 23493 } 23494 if (removedFromList == null) { 23495 removedFromList = new ArrayList<>(); 23496 } 23497 removedFromList.add(oldPackage); 23498 } 23499 } 23500 mKeepUninstalledPackages = new ArrayList<>(packageList); 23501 if (removedFromList != null) { 23502 final int removedCount = removedFromList.size(); 23503 for (int i = 0; i < removedCount; i++) { 23504 deletePackageIfUnusedLPr(removedFromList.get(i)); 23505 } 23506 } 23507 } 23508 } 23509 23510 @Override 23511 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23512 synchronized (mPackages) { 23513 return mPermissionManager.isPermissionsReviewRequired( 23514 mPackages.get(packageName), userId); 23515 } 23516 } 23517 23518 @Override 23519 public PackageInfo getPackageInfo( 23520 String packageName, int flags, int filterCallingUid, int userId) { 23521 return PackageManagerService.this 23522 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23523 flags, filterCallingUid, userId); 23524 } 23525 23526 @Override 23527 public int getPackageUid(String packageName, int flags, int userId) { 23528 return PackageManagerService.this 23529 .getPackageUid(packageName, flags, userId); 23530 } 23531 23532 @Override 23533 public ApplicationInfo getApplicationInfo( 23534 String packageName, int flags, int filterCallingUid, int userId) { 23535 return PackageManagerService.this 23536 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23537 } 23538 23539 @Override 23540 public ActivityInfo getActivityInfo( 23541 ComponentName component, int flags, int filterCallingUid, int userId) { 23542 return PackageManagerService.this 23543 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23544 } 23545 23546 @Override 23547 public List<ResolveInfo> queryIntentActivities( 23548 Intent intent, int flags, int filterCallingUid, int userId) { 23549 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23550 return PackageManagerService.this 23551 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23552 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23553 } 23554 23555 @Override 23556 public List<ResolveInfo> queryIntentServices( 23557 Intent intent, int flags, int callingUid, int userId) { 23558 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23559 return PackageManagerService.this 23560 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23561 false); 23562 } 23563 23564 @Override 23565 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23566 int userId) { 23567 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23568 } 23569 23570 @Override 23571 public void setDeviceAndProfileOwnerPackages( 23572 int deviceOwnerUserId, String deviceOwnerPackage, 23573 SparseArray<String> profileOwnerPackages) { 23574 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23575 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23576 } 23577 23578 @Override 23579 public boolean isPackageDataProtected(int userId, String packageName) { 23580 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23581 } 23582 23583 @Override 23584 public boolean isPackageEphemeral(int userId, String packageName) { 23585 synchronized (mPackages) { 23586 final PackageSetting ps = mSettings.mPackages.get(packageName); 23587 return ps != null ? ps.getInstantApp(userId) : false; 23588 } 23589 } 23590 23591 @Override 23592 public boolean wasPackageEverLaunched(String packageName, int userId) { 23593 synchronized (mPackages) { 23594 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23595 } 23596 } 23597 23598 @Override 23599 public void grantRuntimePermission(String packageName, String permName, int userId, 23600 boolean overridePolicy) { 23601 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23602 permName, packageName, overridePolicy, getCallingUid(), userId, 23603 mPermissionCallback); 23604 } 23605 23606 @Override 23607 public void revokeRuntimePermission(String packageName, String permName, int userId, 23608 boolean overridePolicy) { 23609 mPermissionManager.revokeRuntimePermission( 23610 permName, packageName, overridePolicy, getCallingUid(), userId, 23611 mPermissionCallback); 23612 } 23613 23614 @Override 23615 public String getNameForUid(int uid) { 23616 return PackageManagerService.this.getNameForUid(uid); 23617 } 23618 23619 @Override 23620 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23621 Intent origIntent, String resolvedType, String callingPackage, 23622 Bundle verificationBundle, int userId) { 23623 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23624 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23625 userId); 23626 } 23627 23628 @Override 23629 public void grantEphemeralAccess(int userId, Intent intent, 23630 int targetAppId, int ephemeralAppId) { 23631 synchronized (mPackages) { 23632 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23633 targetAppId, ephemeralAppId); 23634 } 23635 } 23636 23637 @Override 23638 public boolean isInstantAppInstallerComponent(ComponentName component) { 23639 synchronized (mPackages) { 23640 return mInstantAppInstallerActivity != null 23641 && mInstantAppInstallerActivity.getComponentName().equals(component); 23642 } 23643 } 23644 23645 @Override 23646 public void pruneInstantApps() { 23647 mInstantAppRegistry.pruneInstantApps(); 23648 } 23649 23650 @Override 23651 public String getSetupWizardPackageName() { 23652 return mSetupWizardPackage; 23653 } 23654 23655 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23656 if (policy != null) { 23657 mExternalSourcesPolicy = policy; 23658 } 23659 } 23660 23661 @Override 23662 public boolean isPackagePersistent(String packageName) { 23663 synchronized (mPackages) { 23664 PackageParser.Package pkg = mPackages.get(packageName); 23665 return pkg != null 23666 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23667 | ApplicationInfo.FLAG_PERSISTENT)) == 23668 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23669 : false; 23670 } 23671 } 23672 23673 @Override 23674 public boolean isLegacySystemApp(Package pkg) { 23675 synchronized (mPackages) { 23676 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23677 return mPromoteSystemApps 23678 && ps.isSystem() 23679 && mExistingSystemPackages.contains(ps.name); 23680 } 23681 } 23682 23683 @Override 23684 public List<PackageInfo> getOverlayPackages(int userId) { 23685 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23686 synchronized (mPackages) { 23687 for (PackageParser.Package p : mPackages.values()) { 23688 if (p.mOverlayTarget != null) { 23689 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23690 if (pkg != null) { 23691 overlayPackages.add(pkg); 23692 } 23693 } 23694 } 23695 } 23696 return overlayPackages; 23697 } 23698 23699 @Override 23700 public List<String> getTargetPackageNames(int userId) { 23701 List<String> targetPackages = new ArrayList<>(); 23702 synchronized (mPackages) { 23703 for (PackageParser.Package p : mPackages.values()) { 23704 if (p.mOverlayTarget == null) { 23705 targetPackages.add(p.packageName); 23706 } 23707 } 23708 } 23709 return targetPackages; 23710 } 23711 23712 @Override 23713 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23714 @Nullable List<String> overlayPackageNames) { 23715 synchronized (mPackages) { 23716 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23717 Slog.e(TAG, "failed to find package " + targetPackageName); 23718 return false; 23719 } 23720 ArrayList<String> overlayPaths = null; 23721 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23722 final int N = overlayPackageNames.size(); 23723 overlayPaths = new ArrayList<>(N); 23724 for (int i = 0; i < N; i++) { 23725 final String packageName = overlayPackageNames.get(i); 23726 final PackageParser.Package pkg = mPackages.get(packageName); 23727 if (pkg == null) { 23728 Slog.e(TAG, "failed to find package " + packageName); 23729 return false; 23730 } 23731 overlayPaths.add(pkg.baseCodePath); 23732 } 23733 } 23734 23735 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23736 ps.setOverlayPaths(overlayPaths, userId); 23737 return true; 23738 } 23739 } 23740 23741 @Override 23742 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23743 int flags, int userId, boolean resolveForStart) { 23744 return resolveIntentInternal( 23745 intent, resolvedType, flags, userId, resolveForStart); 23746 } 23747 23748 @Override 23749 public ResolveInfo resolveService(Intent intent, String resolvedType, 23750 int flags, int userId, int callingUid) { 23751 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23752 } 23753 23754 @Override 23755 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23756 return PackageManagerService.this.resolveContentProviderInternal( 23757 name, flags, userId); 23758 } 23759 23760 @Override 23761 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23762 synchronized (mPackages) { 23763 mIsolatedOwners.put(isolatedUid, ownerUid); 23764 } 23765 } 23766 23767 @Override 23768 public void removeIsolatedUid(int isolatedUid) { 23769 synchronized (mPackages) { 23770 mIsolatedOwners.delete(isolatedUid); 23771 } 23772 } 23773 23774 @Override 23775 public int getUidTargetSdkVersion(int uid) { 23776 synchronized (mPackages) { 23777 return getUidTargetSdkVersionLockedLPr(uid); 23778 } 23779 } 23780 23781 @Override 23782 public int getPackageTargetSdkVersion(String packageName) { 23783 synchronized (mPackages) { 23784 return getPackageTargetSdkVersionLockedLPr(packageName); 23785 } 23786 } 23787 23788 @Override 23789 public boolean canAccessInstantApps(int callingUid, int userId) { 23790 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23791 } 23792 23793 @Override 23794 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23795 synchronized (mPackages) { 23796 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23797 } 23798 } 23799 23800 @Override 23801 public void notifyPackageUse(String packageName, int reason) { 23802 synchronized (mPackages) { 23803 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23804 } 23805 } 23806 } 23807 23808 @Override 23809 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23810 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23811 synchronized (mPackages) { 23812 final long identity = Binder.clearCallingIdentity(); 23813 try { 23814 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23815 packageNames, userId); 23816 } finally { 23817 Binder.restoreCallingIdentity(identity); 23818 } 23819 } 23820 } 23821 23822 @Override 23823 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23824 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23825 synchronized (mPackages) { 23826 final long identity = Binder.clearCallingIdentity(); 23827 try { 23828 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23829 packageNames, userId); 23830 } finally { 23831 Binder.restoreCallingIdentity(identity); 23832 } 23833 } 23834 } 23835 23836 private static void enforceSystemOrPhoneCaller(String tag) { 23837 int callingUid = Binder.getCallingUid(); 23838 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23839 throw new SecurityException( 23840 "Cannot call " + tag + " from UID " + callingUid); 23841 } 23842 } 23843 23844 boolean isHistoricalPackageUsageAvailable() { 23845 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23846 } 23847 23848 /** 23849 * Return a <b>copy</b> of the collection of packages known to the package manager. 23850 * @return A copy of the values of mPackages. 23851 */ 23852 Collection<PackageParser.Package> getPackages() { 23853 synchronized (mPackages) { 23854 return new ArrayList<>(mPackages.values()); 23855 } 23856 } 23857 23858 /** 23859 * Logs process start information (including base APK hash) to the security log. 23860 * @hide 23861 */ 23862 @Override 23863 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23864 String apkFile, int pid) { 23865 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23866 return; 23867 } 23868 if (!SecurityLog.isLoggingEnabled()) { 23869 return; 23870 } 23871 Bundle data = new Bundle(); 23872 data.putLong("startTimestamp", System.currentTimeMillis()); 23873 data.putString("processName", processName); 23874 data.putInt("uid", uid); 23875 data.putString("seinfo", seinfo); 23876 data.putString("apkFile", apkFile); 23877 data.putInt("pid", pid); 23878 Message msg = mProcessLoggingHandler.obtainMessage( 23879 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23880 msg.setData(data); 23881 mProcessLoggingHandler.sendMessage(msg); 23882 } 23883 23884 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23885 return mCompilerStats.getPackageStats(pkgName); 23886 } 23887 23888 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23889 return getOrCreateCompilerPackageStats(pkg.packageName); 23890 } 23891 23892 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23893 return mCompilerStats.getOrCreatePackageStats(pkgName); 23894 } 23895 23896 public void deleteCompilerPackageStats(String pkgName) { 23897 mCompilerStats.deletePackageStats(pkgName); 23898 } 23899 23900 @Override 23901 public int getInstallReason(String packageName, int userId) { 23902 final int callingUid = Binder.getCallingUid(); 23903 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23904 true /* requireFullPermission */, false /* checkShell */, 23905 "get install reason"); 23906 synchronized (mPackages) { 23907 final PackageSetting ps = mSettings.mPackages.get(packageName); 23908 if (filterAppAccessLPr(ps, callingUid, userId)) { 23909 return PackageManager.INSTALL_REASON_UNKNOWN; 23910 } 23911 if (ps != null) { 23912 return ps.getInstallReason(userId); 23913 } 23914 } 23915 return PackageManager.INSTALL_REASON_UNKNOWN; 23916 } 23917 23918 @Override 23919 public boolean canRequestPackageInstalls(String packageName, int userId) { 23920 return canRequestPackageInstallsInternal(packageName, 0, userId, 23921 true /* throwIfPermNotDeclared*/); 23922 } 23923 23924 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23925 boolean throwIfPermNotDeclared) { 23926 int callingUid = Binder.getCallingUid(); 23927 int uid = getPackageUid(packageName, 0, userId); 23928 if (callingUid != uid && callingUid != Process.ROOT_UID 23929 && callingUid != Process.SYSTEM_UID) { 23930 throw new SecurityException( 23931 "Caller uid " + callingUid + " does not own package " + packageName); 23932 } 23933 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23934 if (info == null) { 23935 return false; 23936 } 23937 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23938 return false; 23939 } 23940 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23941 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23942 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23943 if (throwIfPermNotDeclared) { 23944 throw new SecurityException("Need to declare " + appOpPermission 23945 + " to call this api"); 23946 } else { 23947 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23948 return false; 23949 } 23950 } 23951 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23952 return false; 23953 } 23954 if (mExternalSourcesPolicy != null) { 23955 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23956 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23957 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23958 } 23959 } 23960 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23961 } 23962 23963 @Override 23964 public ComponentName getInstantAppResolverSettingsComponent() { 23965 return mInstantAppResolverSettingsComponent; 23966 } 23967 23968 @Override 23969 public ComponentName getInstantAppInstallerComponent() { 23970 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23971 return null; 23972 } 23973 return mInstantAppInstallerActivity == null 23974 ? null : mInstantAppInstallerActivity.getComponentName(); 23975 } 23976 23977 @Override 23978 public String getInstantAppAndroidId(String packageName, int userId) { 23979 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23980 "getInstantAppAndroidId"); 23981 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23982 true /* requireFullPermission */, false /* checkShell */, 23983 "getInstantAppAndroidId"); 23984 // Make sure the target is an Instant App. 23985 if (!isInstantApp(packageName, userId)) { 23986 return null; 23987 } 23988 synchronized (mPackages) { 23989 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23990 } 23991 } 23992 23993 boolean canHaveOatDir(String packageName) { 23994 synchronized (mPackages) { 23995 PackageParser.Package p = mPackages.get(packageName); 23996 if (p == null) { 23997 return false; 23998 } 23999 return p.canHaveOatDir(); 24000 } 24001 } 24002 24003 private String getOatDir(PackageParser.Package pkg) { 24004 if (!pkg.canHaveOatDir()) { 24005 return null; 24006 } 24007 File codePath = new File(pkg.codePath); 24008 if (codePath.isDirectory()) { 24009 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24010 } 24011 return null; 24012 } 24013 24014 void deleteOatArtifactsOfPackage(String packageName) { 24015 final String[] instructionSets; 24016 final List<String> codePaths; 24017 final String oatDir; 24018 final PackageParser.Package pkg; 24019 synchronized (mPackages) { 24020 pkg = mPackages.get(packageName); 24021 } 24022 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24023 codePaths = pkg.getAllCodePaths(); 24024 oatDir = getOatDir(pkg); 24025 24026 for (String codePath : codePaths) { 24027 for (String isa : instructionSets) { 24028 try { 24029 mInstaller.deleteOdex(codePath, isa, oatDir); 24030 } catch (InstallerException e) { 24031 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24032 } 24033 } 24034 } 24035 } 24036 24037 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24038 Set<String> unusedPackages = new HashSet<>(); 24039 long currentTimeInMillis = System.currentTimeMillis(); 24040 synchronized (mPackages) { 24041 for (PackageParser.Package pkg : mPackages.values()) { 24042 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24043 if (ps == null) { 24044 continue; 24045 } 24046 PackageDexUsage.PackageUseInfo packageUseInfo = 24047 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24048 if (PackageManagerServiceUtils 24049 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24050 downgradeTimeThresholdMillis, packageUseInfo, 24051 pkg.getLatestPackageUseTimeInMills(), 24052 pkg.getLatestForegroundPackageUseTimeInMills())) { 24053 unusedPackages.add(pkg.packageName); 24054 } 24055 } 24056 } 24057 return unusedPackages; 24058 } 24059 24060 @Override 24061 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24062 int userId) { 24063 final int callingUid = Binder.getCallingUid(); 24064 final int callingAppId = UserHandle.getAppId(callingUid); 24065 24066 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24067 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24068 24069 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24070 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24071 throw new SecurityException("Caller must have the " 24072 + SET_HARMFUL_APP_WARNINGS + " permission."); 24073 } 24074 24075 synchronized(mPackages) { 24076 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24077 scheduleWritePackageRestrictionsLocked(userId); 24078 } 24079 } 24080 24081 @Nullable 24082 @Override 24083 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24084 final int callingUid = Binder.getCallingUid(); 24085 final int callingAppId = UserHandle.getAppId(callingUid); 24086 24087 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24088 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24089 24090 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24091 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24092 throw new SecurityException("Caller must have the " 24093 + SET_HARMFUL_APP_WARNINGS + " permission."); 24094 } 24095 24096 synchronized(mPackages) { 24097 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24098 } 24099 } 24100} 24101 24102interface PackageSender { 24103 /** 24104 * @param userIds User IDs where the action occurred on a full application 24105 * @param instantUserIds User IDs where the action occurred on an instant application 24106 */ 24107 void sendPackageBroadcast(final String action, final String pkg, 24108 final Bundle extras, final int flags, final String targetPkg, 24109 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24110 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24111 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24112 void notifyPackageAdded(String packageName); 24113 void notifyPackageRemoved(String packageName); 24114} 24115