PackageManagerService.java revision 6149b0fa49479dbe8c6208dbd87dc5e39c7f4c13
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 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3599 intent.addCategory(Intent.CATEGORY_DEFAULT); 3600 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3601 3602 final int resolveFlags = 3603 MATCH_DIRECT_BOOT_AWARE 3604 | MATCH_DIRECT_BOOT_UNAWARE 3605 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3606 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3607 resolveFlags, UserHandle.USER_SYSTEM); 3608 // temporarily look for the old action 3609 if (matches.isEmpty()) { 3610 if (DEBUG_EPHEMERAL) { 3611 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3612 } 3613 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3614 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3615 resolveFlags, UserHandle.USER_SYSTEM); 3616 } 3617 Iterator<ResolveInfo> iter = matches.iterator(); 3618 while (iter.hasNext()) { 3619 final ResolveInfo rInfo = iter.next(); 3620 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3621 if (ps != null) { 3622 final PermissionsState permissionsState = ps.getPermissionsState(); 3623 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3624 continue; 3625 } 3626 } 3627 iter.remove(); 3628 } 3629 if (matches.size() == 0) { 3630 return null; 3631 } else if (matches.size() == 1) { 3632 return (ActivityInfo) matches.get(0).getComponentInfo(); 3633 } else { 3634 throw new RuntimeException( 3635 "There must be at most one ephemeral installer; found " + matches); 3636 } 3637 } 3638 3639 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3640 @NonNull ComponentName resolver) { 3641 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3642 .addCategory(Intent.CATEGORY_DEFAULT) 3643 .setPackage(resolver.getPackageName()); 3644 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3645 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3646 UserHandle.USER_SYSTEM); 3647 // temporarily look for the old action 3648 if (matches.isEmpty()) { 3649 if (DEBUG_EPHEMERAL) { 3650 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3651 } 3652 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3653 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3654 UserHandle.USER_SYSTEM); 3655 } 3656 if (matches.isEmpty()) { 3657 return null; 3658 } 3659 return matches.get(0).getComponentInfo().getComponentName(); 3660 } 3661 3662 private void primeDomainVerificationsLPw(int userId) { 3663 if (DEBUG_DOMAIN_VERIFICATION) { 3664 Slog.d(TAG, "Priming domain verifications in user " + userId); 3665 } 3666 3667 SystemConfig systemConfig = SystemConfig.getInstance(); 3668 ArraySet<String> packages = systemConfig.getLinkedApps(); 3669 3670 for (String packageName : packages) { 3671 PackageParser.Package pkg = mPackages.get(packageName); 3672 if (pkg != null) { 3673 if (!pkg.isSystem()) { 3674 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3675 continue; 3676 } 3677 3678 ArraySet<String> domains = null; 3679 for (PackageParser.Activity a : pkg.activities) { 3680 for (ActivityIntentInfo filter : a.intents) { 3681 if (hasValidDomains(filter)) { 3682 if (domains == null) { 3683 domains = new ArraySet<String>(); 3684 } 3685 domains.addAll(filter.getHostsList()); 3686 } 3687 } 3688 } 3689 3690 if (domains != null && domains.size() > 0) { 3691 if (DEBUG_DOMAIN_VERIFICATION) { 3692 Slog.v(TAG, " + " + packageName); 3693 } 3694 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3695 // state w.r.t. the formal app-linkage "no verification attempted" state; 3696 // and then 'always' in the per-user state actually used for intent resolution. 3697 final IntentFilterVerificationInfo ivi; 3698 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3699 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3700 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3701 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3702 } else { 3703 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3704 + "' does not handle web links"); 3705 } 3706 } else { 3707 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3708 } 3709 } 3710 3711 scheduleWritePackageRestrictionsLocked(userId); 3712 scheduleWriteSettingsLocked(); 3713 } 3714 3715 private void applyFactoryDefaultBrowserLPw(int userId) { 3716 // The default browser app's package name is stored in a string resource, 3717 // with a product-specific overlay used for vendor customization. 3718 String browserPkg = mContext.getResources().getString( 3719 com.android.internal.R.string.default_browser); 3720 if (!TextUtils.isEmpty(browserPkg)) { 3721 // non-empty string => required to be a known package 3722 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3723 if (ps == null) { 3724 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3725 browserPkg = null; 3726 } else { 3727 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3728 } 3729 } 3730 3731 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3732 // default. If there's more than one, just leave everything alone. 3733 if (browserPkg == null) { 3734 calculateDefaultBrowserLPw(userId); 3735 } 3736 } 3737 3738 private void calculateDefaultBrowserLPw(int userId) { 3739 List<String> allBrowsers = resolveAllBrowserApps(userId); 3740 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3741 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3742 } 3743 3744 private List<String> resolveAllBrowserApps(int userId) { 3745 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3746 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3747 PackageManager.MATCH_ALL, userId); 3748 3749 final int count = list.size(); 3750 List<String> result = new ArrayList<String>(count); 3751 for (int i=0; i<count; i++) { 3752 ResolveInfo info = list.get(i); 3753 if (info.activityInfo == null 3754 || !info.handleAllWebDataURI 3755 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3756 || result.contains(info.activityInfo.packageName)) { 3757 continue; 3758 } 3759 result.add(info.activityInfo.packageName); 3760 } 3761 3762 return result; 3763 } 3764 3765 private boolean packageIsBrowser(String packageName, int userId) { 3766 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3767 PackageManager.MATCH_ALL, userId); 3768 final int N = list.size(); 3769 for (int i = 0; i < N; i++) { 3770 ResolveInfo info = list.get(i); 3771 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3772 return true; 3773 } 3774 } 3775 return false; 3776 } 3777 3778 private void checkDefaultBrowser() { 3779 final int myUserId = UserHandle.myUserId(); 3780 final String packageName = getDefaultBrowserPackageName(myUserId); 3781 if (packageName != null) { 3782 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3783 if (info == null) { 3784 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3785 synchronized (mPackages) { 3786 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3787 } 3788 } 3789 } 3790 } 3791 3792 @Override 3793 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3794 throws RemoteException { 3795 try { 3796 return super.onTransact(code, data, reply, flags); 3797 } catch (RuntimeException e) { 3798 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3799 Slog.wtf(TAG, "Package Manager Crash", e); 3800 } 3801 throw e; 3802 } 3803 } 3804 3805 static int[] appendInts(int[] cur, int[] add) { 3806 if (add == null) return cur; 3807 if (cur == null) return add; 3808 final int N = add.length; 3809 for (int i=0; i<N; i++) { 3810 cur = appendInt(cur, add[i]); 3811 } 3812 return cur; 3813 } 3814 3815 /** 3816 * Returns whether or not a full application can see an instant application. 3817 * <p> 3818 * Currently, there are three cases in which this can occur: 3819 * <ol> 3820 * <li>The calling application is a "special" process. Special processes 3821 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3822 * <li>The calling application has the permission 3823 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3824 * <li>The calling application is the default launcher on the 3825 * system partition.</li> 3826 * </ol> 3827 */ 3828 private boolean canViewInstantApps(int callingUid, int userId) { 3829 if (callingUid < Process.FIRST_APPLICATION_UID) { 3830 return true; 3831 } 3832 if (mContext.checkCallingOrSelfPermission( 3833 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3834 return true; 3835 } 3836 if (mContext.checkCallingOrSelfPermission( 3837 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3838 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3839 if (homeComponent != null 3840 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3841 return true; 3842 } 3843 } 3844 return false; 3845 } 3846 3847 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3848 if (!sUserManager.exists(userId)) return null; 3849 if (ps == null) { 3850 return null; 3851 } 3852 PackageParser.Package p = ps.pkg; 3853 if (p == null) { 3854 return null; 3855 } 3856 final int callingUid = Binder.getCallingUid(); 3857 // Filter out ephemeral app metadata: 3858 // * The system/shell/root can see metadata for any app 3859 // * An installed app can see metadata for 1) other installed apps 3860 // and 2) ephemeral apps that have explicitly interacted with it 3861 // * Ephemeral apps can only see their own data and exposed installed apps 3862 // * Holding a signature permission allows seeing instant apps 3863 if (filterAppAccessLPr(ps, callingUid, userId)) { 3864 return null; 3865 } 3866 3867 final PermissionsState permissionsState = ps.getPermissionsState(); 3868 3869 // Compute GIDs only if requested 3870 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3871 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3872 // Compute granted permissions only if package has requested permissions 3873 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3874 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3875 final PackageUserState state = ps.readUserState(userId); 3876 3877 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3878 && ps.isSystem()) { 3879 flags |= MATCH_ANY_USER; 3880 } 3881 3882 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3883 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3884 3885 if (packageInfo == null) { 3886 return null; 3887 } 3888 3889 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3890 resolveExternalPackageNameLPr(p); 3891 3892 return packageInfo; 3893 } 3894 3895 @Override 3896 public void checkPackageStartable(String packageName, int userId) { 3897 final int callingUid = Binder.getCallingUid(); 3898 if (getInstantAppPackageName(callingUid) != null) { 3899 throw new SecurityException("Instant applications don't have access to this method"); 3900 } 3901 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3902 synchronized (mPackages) { 3903 final PackageSetting ps = mSettings.mPackages.get(packageName); 3904 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3905 throw new SecurityException("Package " + packageName + " was not found!"); 3906 } 3907 3908 if (!ps.getInstalled(userId)) { 3909 throw new SecurityException( 3910 "Package " + packageName + " was not installed for user " + userId + "!"); 3911 } 3912 3913 if (mSafeMode && !ps.isSystem()) { 3914 throw new SecurityException("Package " + packageName + " not a system app!"); 3915 } 3916 3917 if (mFrozenPackages.contains(packageName)) { 3918 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3919 } 3920 3921 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3922 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3923 } 3924 } 3925 } 3926 3927 @Override 3928 public boolean isPackageAvailable(String packageName, int userId) { 3929 if (!sUserManager.exists(userId)) return false; 3930 final int callingUid = Binder.getCallingUid(); 3931 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3932 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3933 synchronized (mPackages) { 3934 PackageParser.Package p = mPackages.get(packageName); 3935 if (p != null) { 3936 final PackageSetting ps = (PackageSetting) p.mExtras; 3937 if (filterAppAccessLPr(ps, callingUid, userId)) { 3938 return false; 3939 } 3940 if (ps != null) { 3941 final PackageUserState state = ps.readUserState(userId); 3942 if (state != null) { 3943 return PackageParser.isAvailable(state); 3944 } 3945 } 3946 } 3947 } 3948 return false; 3949 } 3950 3951 @Override 3952 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3953 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3954 flags, Binder.getCallingUid(), userId); 3955 } 3956 3957 @Override 3958 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3959 int flags, int userId) { 3960 return getPackageInfoInternal(versionedPackage.getPackageName(), 3961 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3962 } 3963 3964 /** 3965 * Important: The provided filterCallingUid is used exclusively to filter out packages 3966 * that can be seen based on user state. It's typically the original caller uid prior 3967 * to clearing. Because it can only be provided by trusted code, it's value can be 3968 * trusted and will be used as-is; unlike userId which will be validated by this method. 3969 */ 3970 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3971 int flags, int filterCallingUid, int userId) { 3972 if (!sUserManager.exists(userId)) return null; 3973 flags = updateFlagsForPackage(flags, userId, packageName); 3974 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3975 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3976 3977 // reader 3978 synchronized (mPackages) { 3979 // Normalize package name to handle renamed packages and static libs 3980 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3981 3982 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3983 if (matchFactoryOnly) { 3984 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3985 if (ps != null) { 3986 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3987 return null; 3988 } 3989 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3990 return null; 3991 } 3992 return generatePackageInfo(ps, flags, userId); 3993 } 3994 } 3995 3996 PackageParser.Package p = mPackages.get(packageName); 3997 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3998 return null; 3999 } 4000 if (DEBUG_PACKAGE_INFO) 4001 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4002 if (p != null) { 4003 final PackageSetting ps = (PackageSetting) p.mExtras; 4004 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4005 return null; 4006 } 4007 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4008 return null; 4009 } 4010 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4011 } 4012 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4013 final PackageSetting ps = mSettings.mPackages.get(packageName); 4014 if (ps == null) return null; 4015 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4016 return null; 4017 } 4018 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4019 return null; 4020 } 4021 return generatePackageInfo(ps, flags, userId); 4022 } 4023 } 4024 return null; 4025 } 4026 4027 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4028 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4029 return true; 4030 } 4031 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4032 return true; 4033 } 4034 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4035 return true; 4036 } 4037 return false; 4038 } 4039 4040 private boolean isComponentVisibleToInstantApp( 4041 @Nullable ComponentName component, @ComponentType int type) { 4042 if (type == TYPE_ACTIVITY) { 4043 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4044 return activity != null 4045 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4046 : false; 4047 } else if (type == TYPE_RECEIVER) { 4048 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4049 return activity != null 4050 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4051 : false; 4052 } else if (type == TYPE_SERVICE) { 4053 final PackageParser.Service service = mServices.mServices.get(component); 4054 return service != null 4055 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4056 : false; 4057 } else if (type == TYPE_PROVIDER) { 4058 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4059 return provider != null 4060 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4061 : false; 4062 } else if (type == TYPE_UNKNOWN) { 4063 return isComponentVisibleToInstantApp(component); 4064 } 4065 return false; 4066 } 4067 4068 /** 4069 * Returns whether or not access to the application should be filtered. 4070 * <p> 4071 * Access may be limited based upon whether the calling or target applications 4072 * are instant applications. 4073 * 4074 * @see #canAccessInstantApps(int) 4075 */ 4076 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4077 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4078 // if we're in an isolated process, get the real calling UID 4079 if (Process.isIsolated(callingUid)) { 4080 callingUid = mIsolatedOwners.get(callingUid); 4081 } 4082 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4083 final boolean callerIsInstantApp = instantAppPkgName != null; 4084 if (ps == null) { 4085 if (callerIsInstantApp) { 4086 // pretend the application exists, but, needs to be filtered 4087 return true; 4088 } 4089 return false; 4090 } 4091 // if the target and caller are the same application, don't filter 4092 if (isCallerSameApp(ps.name, callingUid)) { 4093 return false; 4094 } 4095 if (callerIsInstantApp) { 4096 // request for a specific component; if it hasn't been explicitly exposed, filter 4097 if (component != null) { 4098 return !isComponentVisibleToInstantApp(component, componentType); 4099 } 4100 // request for application; if no components have been explicitly exposed, filter 4101 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4102 } 4103 if (ps.getInstantApp(userId)) { 4104 // caller can see all components of all instant applications, don't filter 4105 if (canViewInstantApps(callingUid, userId)) { 4106 return false; 4107 } 4108 // request for a specific instant application component, filter 4109 if (component != null) { 4110 return true; 4111 } 4112 // request for an instant application; if the caller hasn't been granted access, filter 4113 return !mInstantAppRegistry.isInstantAccessGranted( 4114 userId, UserHandle.getAppId(callingUid), ps.appId); 4115 } 4116 return false; 4117 } 4118 4119 /** 4120 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4121 */ 4122 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4123 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4124 } 4125 4126 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4127 int flags) { 4128 // Callers can access only the libs they depend on, otherwise they need to explicitly 4129 // ask for the shared libraries given the caller is allowed to access all static libs. 4130 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4131 // System/shell/root get to see all static libs 4132 final int appId = UserHandle.getAppId(uid); 4133 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4134 || appId == Process.ROOT_UID) { 4135 return false; 4136 } 4137 } 4138 4139 // No package means no static lib as it is always on internal storage 4140 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4141 return false; 4142 } 4143 4144 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4145 ps.pkg.staticSharedLibVersion); 4146 if (libEntry == null) { 4147 return false; 4148 } 4149 4150 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4151 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4152 if (uidPackageNames == null) { 4153 return true; 4154 } 4155 4156 for (String uidPackageName : uidPackageNames) { 4157 if (ps.name.equals(uidPackageName)) { 4158 return false; 4159 } 4160 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4161 if (uidPs != null) { 4162 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4163 libEntry.info.getName()); 4164 if (index < 0) { 4165 continue; 4166 } 4167 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4168 return false; 4169 } 4170 } 4171 } 4172 return true; 4173 } 4174 4175 @Override 4176 public String[] currentToCanonicalPackageNames(String[] names) { 4177 final int callingUid = Binder.getCallingUid(); 4178 if (getInstantAppPackageName(callingUid) != null) { 4179 return names; 4180 } 4181 final String[] out = new String[names.length]; 4182 // reader 4183 synchronized (mPackages) { 4184 final int callingUserId = UserHandle.getUserId(callingUid); 4185 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4186 for (int i=names.length-1; i>=0; i--) { 4187 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4188 boolean translateName = false; 4189 if (ps != null && ps.realName != null) { 4190 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4191 translateName = !targetIsInstantApp 4192 || canViewInstantApps 4193 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4194 UserHandle.getAppId(callingUid), ps.appId); 4195 } 4196 out[i] = translateName ? ps.realName : names[i]; 4197 } 4198 } 4199 return out; 4200 } 4201 4202 @Override 4203 public String[] canonicalToCurrentPackageNames(String[] names) { 4204 final int callingUid = Binder.getCallingUid(); 4205 if (getInstantAppPackageName(callingUid) != null) { 4206 return names; 4207 } 4208 final String[] out = new String[names.length]; 4209 // reader 4210 synchronized (mPackages) { 4211 final int callingUserId = UserHandle.getUserId(callingUid); 4212 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4213 for (int i=names.length-1; i>=0; i--) { 4214 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4215 boolean translateName = false; 4216 if (cur != null) { 4217 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4218 final boolean targetIsInstantApp = 4219 ps != null && ps.getInstantApp(callingUserId); 4220 translateName = !targetIsInstantApp 4221 || canViewInstantApps 4222 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4223 UserHandle.getAppId(callingUid), ps.appId); 4224 } 4225 out[i] = translateName ? cur : names[i]; 4226 } 4227 } 4228 return out; 4229 } 4230 4231 @Override 4232 public int getPackageUid(String packageName, int flags, int userId) { 4233 if (!sUserManager.exists(userId)) return -1; 4234 final int callingUid = Binder.getCallingUid(); 4235 flags = updateFlagsForPackage(flags, userId, packageName); 4236 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4237 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4238 4239 // reader 4240 synchronized (mPackages) { 4241 final PackageParser.Package p = mPackages.get(packageName); 4242 if (p != null && p.isMatch(flags)) { 4243 PackageSetting ps = (PackageSetting) p.mExtras; 4244 if (filterAppAccessLPr(ps, callingUid, userId)) { 4245 return -1; 4246 } 4247 return UserHandle.getUid(userId, p.applicationInfo.uid); 4248 } 4249 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4250 final PackageSetting ps = mSettings.mPackages.get(packageName); 4251 if (ps != null && ps.isMatch(flags) 4252 && !filterAppAccessLPr(ps, callingUid, userId)) { 4253 return UserHandle.getUid(userId, ps.appId); 4254 } 4255 } 4256 } 4257 4258 return -1; 4259 } 4260 4261 @Override 4262 public int[] getPackageGids(String packageName, int flags, int userId) { 4263 if (!sUserManager.exists(userId)) return null; 4264 final int callingUid = Binder.getCallingUid(); 4265 flags = updateFlagsForPackage(flags, userId, packageName); 4266 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4267 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4268 4269 // reader 4270 synchronized (mPackages) { 4271 final PackageParser.Package p = mPackages.get(packageName); 4272 if (p != null && p.isMatch(flags)) { 4273 PackageSetting ps = (PackageSetting) p.mExtras; 4274 if (filterAppAccessLPr(ps, callingUid, userId)) { 4275 return null; 4276 } 4277 // TODO: Shouldn't this be checking for package installed state for userId and 4278 // return null? 4279 return ps.getPermissionsState().computeGids(userId); 4280 } 4281 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4282 final PackageSetting ps = mSettings.mPackages.get(packageName); 4283 if (ps != null && ps.isMatch(flags) 4284 && !filterAppAccessLPr(ps, callingUid, userId)) { 4285 return ps.getPermissionsState().computeGids(userId); 4286 } 4287 } 4288 } 4289 4290 return null; 4291 } 4292 4293 @Override 4294 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4295 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4296 } 4297 4298 @Override 4299 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4300 int flags) { 4301 final List<PermissionInfo> permissionList = 4302 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4303 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4304 } 4305 4306 @Override 4307 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4308 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4309 } 4310 4311 @Override 4312 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4313 final List<PermissionGroupInfo> permissionList = 4314 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4315 return (permissionList == null) 4316 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4317 } 4318 4319 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4320 int filterCallingUid, int userId) { 4321 if (!sUserManager.exists(userId)) return null; 4322 PackageSetting ps = mSettings.mPackages.get(packageName); 4323 if (ps != null) { 4324 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4325 return null; 4326 } 4327 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4328 return null; 4329 } 4330 if (ps.pkg == null) { 4331 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4332 if (pInfo != null) { 4333 return pInfo.applicationInfo; 4334 } 4335 return null; 4336 } 4337 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4338 ps.readUserState(userId), userId); 4339 if (ai != null) { 4340 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4341 } 4342 return ai; 4343 } 4344 return null; 4345 } 4346 4347 @Override 4348 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4349 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4350 } 4351 4352 /** 4353 * Important: The provided filterCallingUid is used exclusively to filter out applications 4354 * that can be seen based on user state. It's typically the original caller uid prior 4355 * to clearing. Because it can only be provided by trusted code, it's value can be 4356 * trusted and will be used as-is; unlike userId which will be validated by this method. 4357 */ 4358 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4359 int filterCallingUid, int userId) { 4360 if (!sUserManager.exists(userId)) return null; 4361 flags = updateFlagsForApplication(flags, userId, packageName); 4362 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4363 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4364 4365 // writer 4366 synchronized (mPackages) { 4367 // Normalize package name to handle renamed packages and static libs 4368 packageName = resolveInternalPackageNameLPr(packageName, 4369 PackageManager.VERSION_CODE_HIGHEST); 4370 4371 PackageParser.Package p = mPackages.get(packageName); 4372 if (DEBUG_PACKAGE_INFO) Log.v( 4373 TAG, "getApplicationInfo " + packageName 4374 + ": " + p); 4375 if (p != null) { 4376 PackageSetting ps = mSettings.mPackages.get(packageName); 4377 if (ps == null) return null; 4378 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4379 return null; 4380 } 4381 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4382 return null; 4383 } 4384 // Note: isEnabledLP() does not apply here - always return info 4385 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4386 p, flags, ps.readUserState(userId), userId); 4387 if (ai != null) { 4388 ai.packageName = resolveExternalPackageNameLPr(p); 4389 } 4390 return ai; 4391 } 4392 if ("android".equals(packageName)||"system".equals(packageName)) { 4393 return mAndroidApplication; 4394 } 4395 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4396 // Already generates the external package name 4397 return generateApplicationInfoFromSettingsLPw(packageName, 4398 flags, filterCallingUid, userId); 4399 } 4400 } 4401 return null; 4402 } 4403 4404 private String normalizePackageNameLPr(String packageName) { 4405 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4406 return normalizedPackageName != null ? normalizedPackageName : packageName; 4407 } 4408 4409 @Override 4410 public void deletePreloadsFileCache() { 4411 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4412 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4413 } 4414 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4415 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4416 FileUtils.deleteContents(dir); 4417 } 4418 4419 @Override 4420 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4421 final int storageFlags, final IPackageDataObserver observer) { 4422 mContext.enforceCallingOrSelfPermission( 4423 android.Manifest.permission.CLEAR_APP_CACHE, null); 4424 mHandler.post(() -> { 4425 boolean success = false; 4426 try { 4427 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4428 success = true; 4429 } catch (IOException e) { 4430 Slog.w(TAG, e); 4431 } 4432 if (observer != null) { 4433 try { 4434 observer.onRemoveCompleted(null, success); 4435 } catch (RemoteException e) { 4436 Slog.w(TAG, e); 4437 } 4438 } 4439 }); 4440 } 4441 4442 @Override 4443 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4444 final int storageFlags, final IntentSender pi) { 4445 mContext.enforceCallingOrSelfPermission( 4446 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4447 mHandler.post(() -> { 4448 boolean success = false; 4449 try { 4450 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4451 success = true; 4452 } catch (IOException e) { 4453 Slog.w(TAG, e); 4454 } 4455 if (pi != null) { 4456 try { 4457 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4458 } catch (SendIntentException e) { 4459 Slog.w(TAG, e); 4460 } 4461 } 4462 }); 4463 } 4464 4465 /** 4466 * Blocking call to clear various types of cached data across the system 4467 * until the requested bytes are available. 4468 */ 4469 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4470 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4471 final File file = storage.findPathForUuid(volumeUuid); 4472 if (file.getUsableSpace() >= bytes) return; 4473 4474 if (ENABLE_FREE_CACHE_V2) { 4475 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4476 volumeUuid); 4477 final boolean aggressive = (storageFlags 4478 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4479 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4480 4481 // 1. Pre-flight to determine if we have any chance to succeed 4482 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4483 if (internalVolume && (aggressive || SystemProperties 4484 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4485 deletePreloadsFileCache(); 4486 if (file.getUsableSpace() >= bytes) return; 4487 } 4488 4489 // 3. Consider parsed APK data (aggressive only) 4490 if (internalVolume && aggressive) { 4491 FileUtils.deleteContents(mCacheDir); 4492 if (file.getUsableSpace() >= bytes) return; 4493 } 4494 4495 // 4. Consider cached app data (above quotas) 4496 try { 4497 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4498 Installer.FLAG_FREE_CACHE_V2); 4499 } catch (InstallerException ignored) { 4500 } 4501 if (file.getUsableSpace() >= bytes) return; 4502 4503 // 5. Consider shared libraries with refcount=0 and age>min cache period 4504 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4505 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4506 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4507 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4508 return; 4509 } 4510 4511 // 6. Consider dexopt output (aggressive only) 4512 // TODO: Implement 4513 4514 // 7. Consider installed instant apps unused longer than min cache period 4515 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4516 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4517 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4518 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4519 return; 4520 } 4521 4522 // 8. Consider cached app data (below quotas) 4523 try { 4524 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4525 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4526 } catch (InstallerException ignored) { 4527 } 4528 if (file.getUsableSpace() >= bytes) return; 4529 4530 // 9. Consider DropBox entries 4531 // TODO: Implement 4532 4533 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4534 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4535 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4536 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4537 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4538 return; 4539 } 4540 } else { 4541 try { 4542 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4543 } catch (InstallerException ignored) { 4544 } 4545 if (file.getUsableSpace() >= bytes) return; 4546 } 4547 4548 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4549 } 4550 4551 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4552 throws IOException { 4553 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4554 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4555 4556 List<VersionedPackage> packagesToDelete = null; 4557 final long now = System.currentTimeMillis(); 4558 4559 synchronized (mPackages) { 4560 final int[] allUsers = sUserManager.getUserIds(); 4561 final int libCount = mSharedLibraries.size(); 4562 for (int i = 0; i < libCount; i++) { 4563 final LongSparseArray<SharedLibraryEntry> versionedLib 4564 = mSharedLibraries.valueAt(i); 4565 if (versionedLib == null) { 4566 continue; 4567 } 4568 final int versionCount = versionedLib.size(); 4569 for (int j = 0; j < versionCount; j++) { 4570 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4571 // Skip packages that are not static shared libs. 4572 if (!libInfo.isStatic()) { 4573 break; 4574 } 4575 // Important: We skip static shared libs used for some user since 4576 // in such a case we need to keep the APK on the device. The check for 4577 // a lib being used for any user is performed by the uninstall call. 4578 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4579 // Resolve the package name - we use synthetic package names internally 4580 final String internalPackageName = resolveInternalPackageNameLPr( 4581 declaringPackage.getPackageName(), 4582 declaringPackage.getLongVersionCode()); 4583 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4584 // Skip unused static shared libs cached less than the min period 4585 // to prevent pruning a lib needed by a subsequently installed package. 4586 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4587 continue; 4588 } 4589 if (packagesToDelete == null) { 4590 packagesToDelete = new ArrayList<>(); 4591 } 4592 packagesToDelete.add(new VersionedPackage(internalPackageName, 4593 declaringPackage.getLongVersionCode())); 4594 } 4595 } 4596 } 4597 4598 if (packagesToDelete != null) { 4599 final int packageCount = packagesToDelete.size(); 4600 for (int i = 0; i < packageCount; i++) { 4601 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4602 // Delete the package synchronously (will fail of the lib used for any user). 4603 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4604 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4605 == PackageManager.DELETE_SUCCEEDED) { 4606 if (volume.getUsableSpace() >= neededSpace) { 4607 return true; 4608 } 4609 } 4610 } 4611 } 4612 4613 return false; 4614 } 4615 4616 /** 4617 * Update given flags based on encryption status of current user. 4618 */ 4619 private int updateFlags(int flags, int userId) { 4620 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4621 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4622 // Caller expressed an explicit opinion about what encryption 4623 // aware/unaware components they want to see, so fall through and 4624 // give them what they want 4625 } else { 4626 // Caller expressed no opinion, so match based on user state 4627 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4628 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4629 } else { 4630 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4631 } 4632 } 4633 return flags; 4634 } 4635 4636 private UserManagerInternal getUserManagerInternal() { 4637 if (mUserManagerInternal == null) { 4638 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4639 } 4640 return mUserManagerInternal; 4641 } 4642 4643 private ActivityManagerInternal getActivityManagerInternal() { 4644 if (mActivityManagerInternal == null) { 4645 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4646 } 4647 return mActivityManagerInternal; 4648 } 4649 4650 4651 private DeviceIdleController.LocalService getDeviceIdleController() { 4652 if (mDeviceIdleController == null) { 4653 mDeviceIdleController = 4654 LocalServices.getService(DeviceIdleController.LocalService.class); 4655 } 4656 return mDeviceIdleController; 4657 } 4658 4659 /** 4660 * Update given flags when being used to request {@link PackageInfo}. 4661 */ 4662 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4663 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4664 boolean triaged = true; 4665 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4666 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4667 // Caller is asking for component details, so they'd better be 4668 // asking for specific encryption matching behavior, or be triaged 4669 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4670 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4671 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4672 triaged = false; 4673 } 4674 } 4675 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4676 | PackageManager.MATCH_SYSTEM_ONLY 4677 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4678 triaged = false; 4679 } 4680 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4681 mPermissionManager.enforceCrossUserPermission( 4682 Binder.getCallingUid(), userId, false, false, 4683 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4684 + Debug.getCallers(5)); 4685 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4686 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4687 // If the caller wants all packages and has a restricted profile associated with it, 4688 // then match all users. This is to make sure that launchers that need to access work 4689 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4690 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4691 flags |= PackageManager.MATCH_ANY_USER; 4692 } 4693 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4694 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4695 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4696 } 4697 return updateFlags(flags, userId); 4698 } 4699 4700 /** 4701 * Update given flags when being used to request {@link ApplicationInfo}. 4702 */ 4703 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4704 return updateFlagsForPackage(flags, userId, cookie); 4705 } 4706 4707 /** 4708 * Update given flags when being used to request {@link ComponentInfo}. 4709 */ 4710 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4711 if (cookie instanceof Intent) { 4712 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4713 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4714 } 4715 } 4716 4717 boolean triaged = true; 4718 // Caller is asking for component details, so they'd better be 4719 // asking for specific encryption matching behavior, or be triaged 4720 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4721 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4722 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4723 triaged = false; 4724 } 4725 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4726 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4727 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4728 } 4729 4730 return updateFlags(flags, userId); 4731 } 4732 4733 /** 4734 * Update given intent when being used to request {@link ResolveInfo}. 4735 */ 4736 private Intent updateIntentForResolve(Intent intent) { 4737 if (intent.getSelector() != null) { 4738 intent = intent.getSelector(); 4739 } 4740 if (DEBUG_PREFERRED) { 4741 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4742 } 4743 return intent; 4744 } 4745 4746 /** 4747 * Update given flags when being used to request {@link ResolveInfo}. 4748 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4749 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4750 * flag set. However, this flag is only honoured in three circumstances: 4751 * <ul> 4752 * <li>when called from a system process</li> 4753 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4754 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4755 * action and a {@code android.intent.category.BROWSABLE} category</li> 4756 * </ul> 4757 */ 4758 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4759 return updateFlagsForResolve(flags, userId, intent, callingUid, 4760 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4761 } 4762 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4763 boolean wantInstantApps) { 4764 return updateFlagsForResolve(flags, userId, intent, callingUid, 4765 wantInstantApps, false /*onlyExposedExplicitly*/); 4766 } 4767 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4768 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4769 // Safe mode means we shouldn't match any third-party components 4770 if (mSafeMode) { 4771 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4772 } 4773 if (getInstantAppPackageName(callingUid) != null) { 4774 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4775 if (onlyExposedExplicitly) { 4776 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4777 } 4778 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4779 flags |= PackageManager.MATCH_INSTANT; 4780 } else { 4781 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4782 final boolean allowMatchInstant = 4783 (wantInstantApps 4784 && Intent.ACTION_VIEW.equals(intent.getAction()) 4785 && hasWebURI(intent)) 4786 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4787 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4788 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4789 if (!allowMatchInstant) { 4790 flags &= ~PackageManager.MATCH_INSTANT; 4791 } 4792 } 4793 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4794 } 4795 4796 @Override 4797 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4798 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4799 } 4800 4801 /** 4802 * Important: The provided filterCallingUid is used exclusively to filter out activities 4803 * that can be seen based on user state. It's typically the original caller uid prior 4804 * to clearing. Because it can only be provided by trusted code, it's value can be 4805 * trusted and will be used as-is; unlike userId which will be validated by this method. 4806 */ 4807 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4808 int filterCallingUid, int userId) { 4809 if (!sUserManager.exists(userId)) return null; 4810 flags = updateFlagsForComponent(flags, userId, component); 4811 4812 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4813 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4814 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4815 } 4816 4817 synchronized (mPackages) { 4818 PackageParser.Activity a = mActivities.mActivities.get(component); 4819 4820 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4821 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4822 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4823 if (ps == null) return null; 4824 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4825 return null; 4826 } 4827 return PackageParser.generateActivityInfo( 4828 a, flags, ps.readUserState(userId), userId); 4829 } 4830 if (mResolveComponentName.equals(component)) { 4831 return PackageParser.generateActivityInfo( 4832 mResolveActivity, flags, new PackageUserState(), userId); 4833 } 4834 } 4835 return null; 4836 } 4837 4838 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4839 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4840 return false; 4841 } 4842 final long token = Binder.clearCallingIdentity(); 4843 try { 4844 final int callingUserId = UserHandle.getUserId(callingUid); 4845 if (ActivityManager.getCurrentUser() != callingUserId) { 4846 return false; 4847 } 4848 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4849 } finally { 4850 Binder.restoreCallingIdentity(token); 4851 } 4852 } 4853 4854 @Override 4855 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4856 String resolvedType) { 4857 synchronized (mPackages) { 4858 if (component.equals(mResolveComponentName)) { 4859 // The resolver supports EVERYTHING! 4860 return true; 4861 } 4862 final int callingUid = Binder.getCallingUid(); 4863 final int callingUserId = UserHandle.getUserId(callingUid); 4864 PackageParser.Activity a = mActivities.mActivities.get(component); 4865 if (a == null) { 4866 return false; 4867 } 4868 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4869 if (ps == null) { 4870 return false; 4871 } 4872 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4873 return false; 4874 } 4875 for (int i=0; i<a.intents.size(); i++) { 4876 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4877 intent.getData(), intent.getCategories(), TAG) >= 0) { 4878 return true; 4879 } 4880 } 4881 return false; 4882 } 4883 } 4884 4885 @Override 4886 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4887 if (!sUserManager.exists(userId)) return null; 4888 final int callingUid = Binder.getCallingUid(); 4889 flags = updateFlagsForComponent(flags, userId, component); 4890 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4891 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4892 synchronized (mPackages) { 4893 PackageParser.Activity a = mReceivers.mActivities.get(component); 4894 if (DEBUG_PACKAGE_INFO) Log.v( 4895 TAG, "getReceiverInfo " + component + ": " + a); 4896 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4897 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4898 if (ps == null) return null; 4899 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4900 return null; 4901 } 4902 return PackageParser.generateActivityInfo( 4903 a, flags, ps.readUserState(userId), userId); 4904 } 4905 } 4906 return null; 4907 } 4908 4909 @Override 4910 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4911 int flags, int userId) { 4912 if (!sUserManager.exists(userId)) return null; 4913 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4914 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4915 return null; 4916 } 4917 4918 flags = updateFlagsForPackage(flags, userId, null); 4919 4920 final boolean canSeeStaticLibraries = 4921 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4922 == PERMISSION_GRANTED 4923 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4924 == PERMISSION_GRANTED 4925 || canRequestPackageInstallsInternal(packageName, 4926 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4927 false /* throwIfPermNotDeclared*/) 4928 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4929 == PERMISSION_GRANTED; 4930 4931 synchronized (mPackages) { 4932 List<SharedLibraryInfo> result = null; 4933 4934 final int libCount = mSharedLibraries.size(); 4935 for (int i = 0; i < libCount; i++) { 4936 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4937 if (versionedLib == null) { 4938 continue; 4939 } 4940 4941 final int versionCount = versionedLib.size(); 4942 for (int j = 0; j < versionCount; j++) { 4943 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4944 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4945 break; 4946 } 4947 final long identity = Binder.clearCallingIdentity(); 4948 try { 4949 PackageInfo packageInfo = getPackageInfoVersioned( 4950 libInfo.getDeclaringPackage(), flags 4951 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4952 if (packageInfo == null) { 4953 continue; 4954 } 4955 } finally { 4956 Binder.restoreCallingIdentity(identity); 4957 } 4958 4959 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4960 libInfo.getLongVersion(), libInfo.getType(), 4961 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4962 flags, userId)); 4963 4964 if (result == null) { 4965 result = new ArrayList<>(); 4966 } 4967 result.add(resLibInfo); 4968 } 4969 } 4970 4971 return result != null ? new ParceledListSlice<>(result) : null; 4972 } 4973 } 4974 4975 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4976 SharedLibraryInfo libInfo, int flags, int userId) { 4977 List<VersionedPackage> versionedPackages = null; 4978 final int packageCount = mSettings.mPackages.size(); 4979 for (int i = 0; i < packageCount; i++) { 4980 PackageSetting ps = mSettings.mPackages.valueAt(i); 4981 4982 if (ps == null) { 4983 continue; 4984 } 4985 4986 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4987 continue; 4988 } 4989 4990 final String libName = libInfo.getName(); 4991 if (libInfo.isStatic()) { 4992 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4993 if (libIdx < 0) { 4994 continue; 4995 } 4996 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4997 continue; 4998 } 4999 if (versionedPackages == null) { 5000 versionedPackages = new ArrayList<>(); 5001 } 5002 // If the dependent is a static shared lib, use the public package name 5003 String dependentPackageName = ps.name; 5004 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5005 dependentPackageName = ps.pkg.manifestPackageName; 5006 } 5007 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5008 } else if (ps.pkg != null) { 5009 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5010 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5011 if (versionedPackages == null) { 5012 versionedPackages = new ArrayList<>(); 5013 } 5014 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5015 } 5016 } 5017 } 5018 5019 return versionedPackages; 5020 } 5021 5022 @Override 5023 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5024 if (!sUserManager.exists(userId)) return null; 5025 final int callingUid = Binder.getCallingUid(); 5026 flags = updateFlagsForComponent(flags, userId, component); 5027 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5028 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5029 synchronized (mPackages) { 5030 PackageParser.Service s = mServices.mServices.get(component); 5031 if (DEBUG_PACKAGE_INFO) Log.v( 5032 TAG, "getServiceInfo " + component + ": " + s); 5033 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5034 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5035 if (ps == null) return null; 5036 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5037 return null; 5038 } 5039 return PackageParser.generateServiceInfo( 5040 s, flags, ps.readUserState(userId), userId); 5041 } 5042 } 5043 return null; 5044 } 5045 5046 @Override 5047 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5048 if (!sUserManager.exists(userId)) return null; 5049 final int callingUid = Binder.getCallingUid(); 5050 flags = updateFlagsForComponent(flags, userId, component); 5051 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5052 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5053 synchronized (mPackages) { 5054 PackageParser.Provider p = mProviders.mProviders.get(component); 5055 if (DEBUG_PACKAGE_INFO) Log.v( 5056 TAG, "getProviderInfo " + component + ": " + p); 5057 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5058 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5059 if (ps == null) return null; 5060 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5061 return null; 5062 } 5063 return PackageParser.generateProviderInfo( 5064 p, flags, ps.readUserState(userId), userId); 5065 } 5066 } 5067 return null; 5068 } 5069 5070 @Override 5071 public String[] getSystemSharedLibraryNames() { 5072 // allow instant applications 5073 synchronized (mPackages) { 5074 Set<String> libs = null; 5075 final int libCount = mSharedLibraries.size(); 5076 for (int i = 0; i < libCount; i++) { 5077 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5078 if (versionedLib == null) { 5079 continue; 5080 } 5081 final int versionCount = versionedLib.size(); 5082 for (int j = 0; j < versionCount; j++) { 5083 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5084 if (!libEntry.info.isStatic()) { 5085 if (libs == null) { 5086 libs = new ArraySet<>(); 5087 } 5088 libs.add(libEntry.info.getName()); 5089 break; 5090 } 5091 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5092 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5093 UserHandle.getUserId(Binder.getCallingUid()), 5094 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5095 if (libs == null) { 5096 libs = new ArraySet<>(); 5097 } 5098 libs.add(libEntry.info.getName()); 5099 break; 5100 } 5101 } 5102 } 5103 5104 if (libs != null) { 5105 String[] libsArray = new String[libs.size()]; 5106 libs.toArray(libsArray); 5107 return libsArray; 5108 } 5109 5110 return null; 5111 } 5112 } 5113 5114 @Override 5115 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5116 // allow instant applications 5117 synchronized (mPackages) { 5118 return mServicesSystemSharedLibraryPackageName; 5119 } 5120 } 5121 5122 @Override 5123 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5124 // allow instant applications 5125 synchronized (mPackages) { 5126 return mSharedSystemSharedLibraryPackageName; 5127 } 5128 } 5129 5130 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5131 for (int i = userList.length - 1; i >= 0; --i) { 5132 final int userId = userList[i]; 5133 // don't add instant app to the list of updates 5134 if (pkgSetting.getInstantApp(userId)) { 5135 continue; 5136 } 5137 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5138 if (changedPackages == null) { 5139 changedPackages = new SparseArray<>(); 5140 mChangedPackages.put(userId, changedPackages); 5141 } 5142 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5143 if (sequenceNumbers == null) { 5144 sequenceNumbers = new HashMap<>(); 5145 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5146 } 5147 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5148 if (sequenceNumber != null) { 5149 changedPackages.remove(sequenceNumber); 5150 } 5151 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5152 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5153 } 5154 mChangedPackagesSequenceNumber++; 5155 } 5156 5157 @Override 5158 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5159 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5160 return null; 5161 } 5162 synchronized (mPackages) { 5163 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5164 return null; 5165 } 5166 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5167 if (changedPackages == null) { 5168 return null; 5169 } 5170 final List<String> packageNames = 5171 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5172 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5173 final String packageName = changedPackages.get(i); 5174 if (packageName != null) { 5175 packageNames.add(packageName); 5176 } 5177 } 5178 return packageNames.isEmpty() 5179 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5180 } 5181 } 5182 5183 @Override 5184 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5185 // allow instant applications 5186 ArrayList<FeatureInfo> res; 5187 synchronized (mAvailableFeatures) { 5188 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5189 res.addAll(mAvailableFeatures.values()); 5190 } 5191 final FeatureInfo fi = new FeatureInfo(); 5192 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5193 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5194 res.add(fi); 5195 5196 return new ParceledListSlice<>(res); 5197 } 5198 5199 @Override 5200 public boolean hasSystemFeature(String name, int version) { 5201 // allow instant applications 5202 synchronized (mAvailableFeatures) { 5203 final FeatureInfo feat = mAvailableFeatures.get(name); 5204 if (feat == null) { 5205 return false; 5206 } else { 5207 return feat.version >= version; 5208 } 5209 } 5210 } 5211 5212 @Override 5213 public int checkPermission(String permName, String pkgName, int userId) { 5214 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5215 } 5216 5217 @Override 5218 public int checkUidPermission(String permName, int uid) { 5219 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5220 } 5221 5222 @Override 5223 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5224 if (UserHandle.getCallingUserId() != userId) { 5225 mContext.enforceCallingPermission( 5226 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5227 "isPermissionRevokedByPolicy for user " + userId); 5228 } 5229 5230 if (checkPermission(permission, packageName, userId) 5231 == PackageManager.PERMISSION_GRANTED) { 5232 return false; 5233 } 5234 5235 final int callingUid = Binder.getCallingUid(); 5236 if (getInstantAppPackageName(callingUid) != null) { 5237 if (!isCallerSameApp(packageName, callingUid)) { 5238 return false; 5239 } 5240 } else { 5241 if (isInstantApp(packageName, userId)) { 5242 return false; 5243 } 5244 } 5245 5246 final long identity = Binder.clearCallingIdentity(); 5247 try { 5248 final int flags = getPermissionFlags(permission, packageName, userId); 5249 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5250 } finally { 5251 Binder.restoreCallingIdentity(identity); 5252 } 5253 } 5254 5255 @Override 5256 public String getPermissionControllerPackageName() { 5257 synchronized (mPackages) { 5258 return mRequiredInstallerPackage; 5259 } 5260 } 5261 5262 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5263 return mPermissionManager.addDynamicPermission( 5264 info, async, getCallingUid(), new PermissionCallback() { 5265 @Override 5266 public void onPermissionChanged() { 5267 if (!async) { 5268 mSettings.writeLPr(); 5269 } else { 5270 scheduleWriteSettingsLocked(); 5271 } 5272 } 5273 }); 5274 } 5275 5276 @Override 5277 public boolean addPermission(PermissionInfo info) { 5278 synchronized (mPackages) { 5279 return addDynamicPermission(info, false); 5280 } 5281 } 5282 5283 @Override 5284 public boolean addPermissionAsync(PermissionInfo info) { 5285 synchronized (mPackages) { 5286 return addDynamicPermission(info, true); 5287 } 5288 } 5289 5290 @Override 5291 public void removePermission(String permName) { 5292 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5293 } 5294 5295 @Override 5296 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5297 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5298 getCallingUid(), userId, mPermissionCallback); 5299 } 5300 5301 @Override 5302 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5303 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5304 getCallingUid(), userId, mPermissionCallback); 5305 } 5306 5307 @Override 5308 public void resetRuntimePermissions() { 5309 mContext.enforceCallingOrSelfPermission( 5310 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5311 "revokeRuntimePermission"); 5312 5313 int callingUid = Binder.getCallingUid(); 5314 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5315 mContext.enforceCallingOrSelfPermission( 5316 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5317 "resetRuntimePermissions"); 5318 } 5319 5320 synchronized (mPackages) { 5321 mPermissionManager.updateAllPermissions( 5322 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5323 mPermissionCallback); 5324 for (int userId : UserManagerService.getInstance().getUserIds()) { 5325 final int packageCount = mPackages.size(); 5326 for (int i = 0; i < packageCount; i++) { 5327 PackageParser.Package pkg = mPackages.valueAt(i); 5328 if (!(pkg.mExtras instanceof PackageSetting)) { 5329 continue; 5330 } 5331 PackageSetting ps = (PackageSetting) pkg.mExtras; 5332 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5333 } 5334 } 5335 } 5336 } 5337 5338 @Override 5339 public int getPermissionFlags(String permName, String packageName, int userId) { 5340 return mPermissionManager.getPermissionFlags( 5341 permName, packageName, getCallingUid(), userId); 5342 } 5343 5344 @Override 5345 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5346 int flagValues, int userId) { 5347 mPermissionManager.updatePermissionFlags( 5348 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5349 mPermissionCallback); 5350 } 5351 5352 /** 5353 * Update the permission flags for all packages and runtime permissions of a user in order 5354 * to allow device or profile owner to remove POLICY_FIXED. 5355 */ 5356 @Override 5357 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5358 synchronized (mPackages) { 5359 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5360 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5361 mPermissionCallback); 5362 if (changed) { 5363 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5364 } 5365 } 5366 } 5367 5368 @Override 5369 public boolean shouldShowRequestPermissionRationale(String permissionName, 5370 String packageName, int userId) { 5371 if (UserHandle.getCallingUserId() != userId) { 5372 mContext.enforceCallingPermission( 5373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5374 "canShowRequestPermissionRationale for user " + userId); 5375 } 5376 5377 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5378 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5379 return false; 5380 } 5381 5382 if (checkPermission(permissionName, packageName, userId) 5383 == PackageManager.PERMISSION_GRANTED) { 5384 return false; 5385 } 5386 5387 final int flags; 5388 5389 final long identity = Binder.clearCallingIdentity(); 5390 try { 5391 flags = getPermissionFlags(permissionName, 5392 packageName, userId); 5393 } finally { 5394 Binder.restoreCallingIdentity(identity); 5395 } 5396 5397 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5398 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5399 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5400 5401 if ((flags & fixedFlags) != 0) { 5402 return false; 5403 } 5404 5405 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5406 } 5407 5408 @Override 5409 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5410 mContext.enforceCallingOrSelfPermission( 5411 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5412 "addOnPermissionsChangeListener"); 5413 5414 synchronized (mPackages) { 5415 mOnPermissionChangeListeners.addListenerLocked(listener); 5416 } 5417 } 5418 5419 @Override 5420 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5421 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5422 throw new SecurityException("Instant applications don't have access to this method"); 5423 } 5424 synchronized (mPackages) { 5425 mOnPermissionChangeListeners.removeListenerLocked(listener); 5426 } 5427 } 5428 5429 @Override 5430 public boolean isProtectedBroadcast(String actionName) { 5431 // allow instant applications 5432 synchronized (mProtectedBroadcasts) { 5433 if (mProtectedBroadcasts.contains(actionName)) { 5434 return true; 5435 } else if (actionName != null) { 5436 // TODO: remove these terrible hacks 5437 if (actionName.startsWith("android.net.netmon.lingerExpired") 5438 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5439 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5440 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5441 return true; 5442 } 5443 } 5444 } 5445 return false; 5446 } 5447 5448 @Override 5449 public int checkSignatures(String pkg1, String pkg2) { 5450 synchronized (mPackages) { 5451 final PackageParser.Package p1 = mPackages.get(pkg1); 5452 final PackageParser.Package p2 = mPackages.get(pkg2); 5453 if (p1 == null || p1.mExtras == null 5454 || p2 == null || p2.mExtras == null) { 5455 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5456 } 5457 final int callingUid = Binder.getCallingUid(); 5458 final int callingUserId = UserHandle.getUserId(callingUid); 5459 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5460 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5461 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5462 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5463 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5464 } 5465 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5466 } 5467 } 5468 5469 @Override 5470 public int checkUidSignatures(int uid1, int uid2) { 5471 final int callingUid = Binder.getCallingUid(); 5472 final int callingUserId = UserHandle.getUserId(callingUid); 5473 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5474 // Map to base uids. 5475 uid1 = UserHandle.getAppId(uid1); 5476 uid2 = UserHandle.getAppId(uid2); 5477 // reader 5478 synchronized (mPackages) { 5479 Signature[] s1; 5480 Signature[] s2; 5481 Object obj = mSettings.getUserIdLPr(uid1); 5482 if (obj != null) { 5483 if (obj instanceof SharedUserSetting) { 5484 if (isCallerInstantApp) { 5485 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5486 } 5487 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5488 } else if (obj instanceof PackageSetting) { 5489 final PackageSetting ps = (PackageSetting) obj; 5490 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5491 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5492 } 5493 s1 = ps.signatures.mSigningDetails.signatures; 5494 } else { 5495 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5496 } 5497 } else { 5498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5499 } 5500 obj = mSettings.getUserIdLPr(uid2); 5501 if (obj != null) { 5502 if (obj instanceof SharedUserSetting) { 5503 if (isCallerInstantApp) { 5504 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5505 } 5506 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5507 } else if (obj instanceof PackageSetting) { 5508 final PackageSetting ps = (PackageSetting) obj; 5509 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5510 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5511 } 5512 s2 = ps.signatures.mSigningDetails.signatures; 5513 } else { 5514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5515 } 5516 } else { 5517 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5518 } 5519 return compareSignatures(s1, s2); 5520 } 5521 } 5522 5523 @Override 5524 public boolean hasSigningCertificate( 5525 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5526 5527 synchronized (mPackages) { 5528 final PackageParser.Package p = mPackages.get(packageName); 5529 if (p == null || p.mExtras == null) { 5530 return false; 5531 } 5532 final int callingUid = Binder.getCallingUid(); 5533 final int callingUserId = UserHandle.getUserId(callingUid); 5534 final PackageSetting ps = (PackageSetting) p.mExtras; 5535 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5536 return false; 5537 } 5538 switch (type) { 5539 case CERT_INPUT_RAW_X509: 5540 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5541 case CERT_INPUT_SHA256: 5542 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5543 default: 5544 return false; 5545 } 5546 } 5547 } 5548 5549 @Override 5550 public boolean hasUidSigningCertificate( 5551 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5552 final int callingUid = Binder.getCallingUid(); 5553 final int callingUserId = UserHandle.getUserId(callingUid); 5554 // Map to base uids. 5555 uid = UserHandle.getAppId(uid); 5556 // reader 5557 synchronized (mPackages) { 5558 final PackageParser.SigningDetails signingDetails; 5559 final Object obj = mSettings.getUserIdLPr(uid); 5560 if (obj != null) { 5561 if (obj instanceof SharedUserSetting) { 5562 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5563 if (isCallerInstantApp) { 5564 return false; 5565 } 5566 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5567 } else if (obj instanceof PackageSetting) { 5568 final PackageSetting ps = (PackageSetting) obj; 5569 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5570 return false; 5571 } 5572 signingDetails = ps.signatures.mSigningDetails; 5573 } else { 5574 return false; 5575 } 5576 } else { 5577 return false; 5578 } 5579 switch (type) { 5580 case CERT_INPUT_RAW_X509: 5581 return signingDetailsHasCertificate(certificate, signingDetails); 5582 case CERT_INPUT_SHA256: 5583 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5584 default: 5585 return false; 5586 } 5587 } 5588 } 5589 5590 /** 5591 * This method should typically only be used when granting or revoking 5592 * permissions, since the app may immediately restart after this call. 5593 * <p> 5594 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5595 * guard your work against the app being relaunched. 5596 */ 5597 private void killUid(int appId, int userId, String reason) { 5598 final long identity = Binder.clearCallingIdentity(); 5599 try { 5600 IActivityManager am = ActivityManager.getService(); 5601 if (am != null) { 5602 try { 5603 am.killUid(appId, userId, reason); 5604 } catch (RemoteException e) { 5605 /* ignore - same process */ 5606 } 5607 } 5608 } finally { 5609 Binder.restoreCallingIdentity(identity); 5610 } 5611 } 5612 5613 /** 5614 * If the database version for this type of package (internal storage or 5615 * external storage) is less than the version where package signatures 5616 * were updated, return true. 5617 */ 5618 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5619 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5620 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5621 } 5622 5623 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5624 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5625 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5626 } 5627 5628 @Override 5629 public List<String> getAllPackages() { 5630 final int callingUid = Binder.getCallingUid(); 5631 final int callingUserId = UserHandle.getUserId(callingUid); 5632 synchronized (mPackages) { 5633 if (canViewInstantApps(callingUid, callingUserId)) { 5634 return new ArrayList<String>(mPackages.keySet()); 5635 } 5636 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5637 final List<String> result = new ArrayList<>(); 5638 if (instantAppPkgName != null) { 5639 // caller is an instant application; filter unexposed applications 5640 for (PackageParser.Package pkg : mPackages.values()) { 5641 if (!pkg.visibleToInstantApps) { 5642 continue; 5643 } 5644 result.add(pkg.packageName); 5645 } 5646 } else { 5647 // caller is a normal application; filter instant applications 5648 for (PackageParser.Package pkg : mPackages.values()) { 5649 final PackageSetting ps = 5650 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5651 if (ps != null 5652 && ps.getInstantApp(callingUserId) 5653 && !mInstantAppRegistry.isInstantAccessGranted( 5654 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5655 continue; 5656 } 5657 result.add(pkg.packageName); 5658 } 5659 } 5660 return result; 5661 } 5662 } 5663 5664 @Override 5665 public String[] getPackagesForUid(int uid) { 5666 final int callingUid = Binder.getCallingUid(); 5667 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5668 final int userId = UserHandle.getUserId(uid); 5669 uid = UserHandle.getAppId(uid); 5670 // reader 5671 synchronized (mPackages) { 5672 Object obj = mSettings.getUserIdLPr(uid); 5673 if (obj instanceof SharedUserSetting) { 5674 if (isCallerInstantApp) { 5675 return null; 5676 } 5677 final SharedUserSetting sus = (SharedUserSetting) obj; 5678 final int N = sus.packages.size(); 5679 String[] res = new String[N]; 5680 final Iterator<PackageSetting> it = sus.packages.iterator(); 5681 int i = 0; 5682 while (it.hasNext()) { 5683 PackageSetting ps = it.next(); 5684 if (ps.getInstalled(userId)) { 5685 res[i++] = ps.name; 5686 } else { 5687 res = ArrayUtils.removeElement(String.class, res, res[i]); 5688 } 5689 } 5690 return res; 5691 } else if (obj instanceof PackageSetting) { 5692 final PackageSetting ps = (PackageSetting) obj; 5693 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5694 return new String[]{ps.name}; 5695 } 5696 } 5697 } 5698 return null; 5699 } 5700 5701 @Override 5702 public String getNameForUid(int uid) { 5703 final int callingUid = Binder.getCallingUid(); 5704 if (getInstantAppPackageName(callingUid) != null) { 5705 return null; 5706 } 5707 synchronized (mPackages) { 5708 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5709 if (obj instanceof SharedUserSetting) { 5710 final SharedUserSetting sus = (SharedUserSetting) obj; 5711 return sus.name + ":" + sus.userId; 5712 } else if (obj instanceof PackageSetting) { 5713 final PackageSetting ps = (PackageSetting) obj; 5714 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5715 return null; 5716 } 5717 return ps.name; 5718 } 5719 return null; 5720 } 5721 } 5722 5723 @Override 5724 public String[] getNamesForUids(int[] uids) { 5725 if (uids == null || uids.length == 0) { 5726 return null; 5727 } 5728 final int callingUid = Binder.getCallingUid(); 5729 if (getInstantAppPackageName(callingUid) != null) { 5730 return null; 5731 } 5732 final String[] names = new String[uids.length]; 5733 synchronized (mPackages) { 5734 for (int i = uids.length - 1; i >= 0; i--) { 5735 final int uid = uids[i]; 5736 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5737 if (obj instanceof SharedUserSetting) { 5738 final SharedUserSetting sus = (SharedUserSetting) obj; 5739 names[i] = "shared:" + sus.name; 5740 } else if (obj instanceof PackageSetting) { 5741 final PackageSetting ps = (PackageSetting) obj; 5742 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5743 names[i] = null; 5744 } else { 5745 names[i] = ps.name; 5746 } 5747 } else { 5748 names[i] = null; 5749 } 5750 } 5751 } 5752 return names; 5753 } 5754 5755 @Override 5756 public int getUidForSharedUser(String sharedUserName) { 5757 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5758 return -1; 5759 } 5760 if (sharedUserName == null) { 5761 return -1; 5762 } 5763 // reader 5764 synchronized (mPackages) { 5765 SharedUserSetting suid; 5766 try { 5767 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5768 if (suid != null) { 5769 return suid.userId; 5770 } 5771 } catch (PackageManagerException ignore) { 5772 // can't happen, but, still need to catch it 5773 } 5774 return -1; 5775 } 5776 } 5777 5778 @Override 5779 public int getFlagsForUid(int uid) { 5780 final int callingUid = Binder.getCallingUid(); 5781 if (getInstantAppPackageName(callingUid) != null) { 5782 return 0; 5783 } 5784 synchronized (mPackages) { 5785 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5786 if (obj instanceof SharedUserSetting) { 5787 final SharedUserSetting sus = (SharedUserSetting) obj; 5788 return sus.pkgFlags; 5789 } else if (obj instanceof PackageSetting) { 5790 final PackageSetting ps = (PackageSetting) obj; 5791 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5792 return 0; 5793 } 5794 return ps.pkgFlags; 5795 } 5796 } 5797 return 0; 5798 } 5799 5800 @Override 5801 public int getPrivateFlagsForUid(int uid) { 5802 final int callingUid = Binder.getCallingUid(); 5803 if (getInstantAppPackageName(callingUid) != null) { 5804 return 0; 5805 } 5806 synchronized (mPackages) { 5807 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5808 if (obj instanceof SharedUserSetting) { 5809 final SharedUserSetting sus = (SharedUserSetting) obj; 5810 return sus.pkgPrivateFlags; 5811 } else if (obj instanceof PackageSetting) { 5812 final PackageSetting ps = (PackageSetting) obj; 5813 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5814 return 0; 5815 } 5816 return ps.pkgPrivateFlags; 5817 } 5818 } 5819 return 0; 5820 } 5821 5822 @Override 5823 public boolean isUidPrivileged(int uid) { 5824 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5825 return false; 5826 } 5827 uid = UserHandle.getAppId(uid); 5828 // reader 5829 synchronized (mPackages) { 5830 Object obj = mSettings.getUserIdLPr(uid); 5831 if (obj instanceof SharedUserSetting) { 5832 final SharedUserSetting sus = (SharedUserSetting) obj; 5833 final Iterator<PackageSetting> it = sus.packages.iterator(); 5834 while (it.hasNext()) { 5835 if (it.next().isPrivileged()) { 5836 return true; 5837 } 5838 } 5839 } else if (obj instanceof PackageSetting) { 5840 final PackageSetting ps = (PackageSetting) obj; 5841 return ps.isPrivileged(); 5842 } 5843 } 5844 return false; 5845 } 5846 5847 @Override 5848 public String[] getAppOpPermissionPackages(String permName) { 5849 return mPermissionManager.getAppOpPermissionPackages(permName); 5850 } 5851 5852 @Override 5853 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5854 int flags, int userId) { 5855 return resolveIntentInternal( 5856 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5857 } 5858 5859 /** 5860 * Normally instant apps can only be resolved when they're visible to the caller. 5861 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5862 * since we need to allow the system to start any installed application. 5863 */ 5864 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5865 int flags, int userId, boolean resolveForStart) { 5866 try { 5867 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5868 5869 if (!sUserManager.exists(userId)) return null; 5870 final int callingUid = Binder.getCallingUid(); 5871 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5872 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5873 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5874 5875 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5876 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5877 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5879 5880 final ResolveInfo bestChoice = 5881 chooseBestActivity(intent, resolvedType, flags, query, userId); 5882 return bestChoice; 5883 } finally { 5884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5885 } 5886 } 5887 5888 @Override 5889 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5890 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5891 throw new SecurityException( 5892 "findPersistentPreferredActivity can only be run by the system"); 5893 } 5894 if (!sUserManager.exists(userId)) { 5895 return null; 5896 } 5897 final int callingUid = Binder.getCallingUid(); 5898 intent = updateIntentForResolve(intent); 5899 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5900 final int flags = updateFlagsForResolve( 5901 0, userId, intent, callingUid, false /*includeInstantApps*/); 5902 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5903 userId); 5904 synchronized (mPackages) { 5905 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5906 userId); 5907 } 5908 } 5909 5910 @Override 5911 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5912 IntentFilter filter, int match, ComponentName activity) { 5913 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5914 return; 5915 } 5916 final int userId = UserHandle.getCallingUserId(); 5917 if (DEBUG_PREFERRED) { 5918 Log.v(TAG, "setLastChosenActivity intent=" + intent 5919 + " resolvedType=" + resolvedType 5920 + " flags=" + flags 5921 + " filter=" + filter 5922 + " match=" + match 5923 + " activity=" + activity); 5924 filter.dump(new PrintStreamPrinter(System.out), " "); 5925 } 5926 intent.setComponent(null); 5927 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5928 userId); 5929 // Find any earlier preferred or last chosen entries and nuke them 5930 findPreferredActivity(intent, resolvedType, 5931 flags, query, 0, false, true, false, userId); 5932 // Add the new activity as the last chosen for this filter 5933 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5934 "Setting last chosen"); 5935 } 5936 5937 @Override 5938 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5939 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5940 return null; 5941 } 5942 final int userId = UserHandle.getCallingUserId(); 5943 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5944 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5945 userId); 5946 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5947 false, false, false, userId); 5948 } 5949 5950 /** 5951 * Returns whether or not instant apps have been disabled remotely. 5952 */ 5953 private boolean isEphemeralDisabled() { 5954 return mEphemeralAppsDisabled; 5955 } 5956 5957 private boolean isInstantAppAllowed( 5958 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5959 boolean skipPackageCheck) { 5960 if (mInstantAppResolverConnection == null) { 5961 return false; 5962 } 5963 if (mInstantAppInstallerActivity == null) { 5964 return false; 5965 } 5966 if (intent.getComponent() != null) { 5967 return false; 5968 } 5969 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5970 return false; 5971 } 5972 if (!skipPackageCheck && intent.getPackage() != null) { 5973 return false; 5974 } 5975 final boolean isWebUri = hasWebURI(intent); 5976 if (!isWebUri || intent.getData().getHost() == null) { 5977 return false; 5978 } 5979 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5980 // Or if there's already an ephemeral app installed that handles the action 5981 synchronized (mPackages) { 5982 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5983 for (int n = 0; n < count; n++) { 5984 final ResolveInfo info = resolvedActivities.get(n); 5985 final String packageName = info.activityInfo.packageName; 5986 final PackageSetting ps = mSettings.mPackages.get(packageName); 5987 if (ps != null) { 5988 // only check domain verification status if the app is not a browser 5989 if (!info.handleAllWebDataURI) { 5990 // Try to get the status from User settings first 5991 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5992 final int status = (int) (packedStatus >> 32); 5993 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5994 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5995 if (DEBUG_EPHEMERAL) { 5996 Slog.v(TAG, "DENY instant app;" 5997 + " pkg: " + packageName + ", status: " + status); 5998 } 5999 return false; 6000 } 6001 } 6002 if (ps.getInstantApp(userId)) { 6003 if (DEBUG_EPHEMERAL) { 6004 Slog.v(TAG, "DENY instant app installed;" 6005 + " pkg: " + packageName); 6006 } 6007 return false; 6008 } 6009 } 6010 } 6011 } 6012 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6013 return true; 6014 } 6015 6016 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6017 Intent origIntent, String resolvedType, String callingPackage, 6018 Bundle verificationBundle, int userId) { 6019 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6020 new InstantAppRequest(responseObj, origIntent, resolvedType, 6021 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6022 mHandler.sendMessage(msg); 6023 } 6024 6025 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6026 int flags, List<ResolveInfo> query, int userId) { 6027 if (query != null) { 6028 final int N = query.size(); 6029 if (N == 1) { 6030 return query.get(0); 6031 } else if (N > 1) { 6032 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6033 // If there is more than one activity with the same priority, 6034 // then let the user decide between them. 6035 ResolveInfo r0 = query.get(0); 6036 ResolveInfo r1 = query.get(1); 6037 if (DEBUG_INTENT_MATCHING || debug) { 6038 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6039 + r1.activityInfo.name + "=" + r1.priority); 6040 } 6041 // If the first activity has a higher priority, or a different 6042 // default, then it is always desirable to pick it. 6043 if (r0.priority != r1.priority 6044 || r0.preferredOrder != r1.preferredOrder 6045 || r0.isDefault != r1.isDefault) { 6046 return query.get(0); 6047 } 6048 // If we have saved a preference for a preferred activity for 6049 // this Intent, use that. 6050 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6051 flags, query, r0.priority, true, false, debug, userId); 6052 if (ri != null) { 6053 return ri; 6054 } 6055 // If we have an ephemeral app, use it 6056 for (int i = 0; i < N; i++) { 6057 ri = query.get(i); 6058 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6059 final String packageName = ri.activityInfo.packageName; 6060 final PackageSetting ps = mSettings.mPackages.get(packageName); 6061 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6062 final int status = (int)(packedStatus >> 32); 6063 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6064 return ri; 6065 } 6066 } 6067 } 6068 ri = new ResolveInfo(mResolveInfo); 6069 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6070 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6071 // If all of the options come from the same package, show the application's 6072 // label and icon instead of the generic resolver's. 6073 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6074 // and then throw away the ResolveInfo itself, meaning that the caller loses 6075 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6076 // a fallback for this case; we only set the target package's resources on 6077 // the ResolveInfo, not the ActivityInfo. 6078 final String intentPackage = intent.getPackage(); 6079 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6080 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6081 ri.resolvePackageName = intentPackage; 6082 if (userNeedsBadging(userId)) { 6083 ri.noResourceId = true; 6084 } else { 6085 ri.icon = appi.icon; 6086 } 6087 ri.iconResourceId = appi.icon; 6088 ri.labelRes = appi.labelRes; 6089 } 6090 ri.activityInfo.applicationInfo = new ApplicationInfo( 6091 ri.activityInfo.applicationInfo); 6092 if (userId != 0) { 6093 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6094 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6095 } 6096 // Make sure that the resolver is displayable in car mode 6097 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6098 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6099 return ri; 6100 } 6101 } 6102 return null; 6103 } 6104 6105 /** 6106 * Return true if the given list is not empty and all of its contents have 6107 * an activityInfo with the given package name. 6108 */ 6109 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6110 if (ArrayUtils.isEmpty(list)) { 6111 return false; 6112 } 6113 for (int i = 0, N = list.size(); i < N; i++) { 6114 final ResolveInfo ri = list.get(i); 6115 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6116 if (ai == null || !packageName.equals(ai.packageName)) { 6117 return false; 6118 } 6119 } 6120 return true; 6121 } 6122 6123 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6124 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6125 final int N = query.size(); 6126 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6127 .get(userId); 6128 // Get the list of persistent preferred activities that handle the intent 6129 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6130 List<PersistentPreferredActivity> pprefs = ppir != null 6131 ? ppir.queryIntent(intent, resolvedType, 6132 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6133 userId) 6134 : null; 6135 if (pprefs != null && pprefs.size() > 0) { 6136 final int M = pprefs.size(); 6137 for (int i=0; i<M; i++) { 6138 final PersistentPreferredActivity ppa = pprefs.get(i); 6139 if (DEBUG_PREFERRED || debug) { 6140 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6141 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6142 + "\n component=" + ppa.mComponent); 6143 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6144 } 6145 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6146 flags | MATCH_DISABLED_COMPONENTS, userId); 6147 if (DEBUG_PREFERRED || debug) { 6148 Slog.v(TAG, "Found persistent preferred activity:"); 6149 if (ai != null) { 6150 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6151 } else { 6152 Slog.v(TAG, " null"); 6153 } 6154 } 6155 if (ai == null) { 6156 // This previously registered persistent preferred activity 6157 // component is no longer known. Ignore it and do NOT remove it. 6158 continue; 6159 } 6160 for (int j=0; j<N; j++) { 6161 final ResolveInfo ri = query.get(j); 6162 if (!ri.activityInfo.applicationInfo.packageName 6163 .equals(ai.applicationInfo.packageName)) { 6164 continue; 6165 } 6166 if (!ri.activityInfo.name.equals(ai.name)) { 6167 continue; 6168 } 6169 // Found a persistent preference that can handle the intent. 6170 if (DEBUG_PREFERRED || debug) { 6171 Slog.v(TAG, "Returning persistent preferred activity: " + 6172 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6173 } 6174 return ri; 6175 } 6176 } 6177 } 6178 return null; 6179 } 6180 6181 // TODO: handle preferred activities missing while user has amnesia 6182 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6183 List<ResolveInfo> query, int priority, boolean always, 6184 boolean removeMatches, boolean debug, int userId) { 6185 if (!sUserManager.exists(userId)) return null; 6186 final int callingUid = Binder.getCallingUid(); 6187 flags = updateFlagsForResolve( 6188 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6189 intent = updateIntentForResolve(intent); 6190 // writer 6191 synchronized (mPackages) { 6192 // Try to find a matching persistent preferred activity. 6193 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6194 debug, userId); 6195 6196 // If a persistent preferred activity matched, use it. 6197 if (pri != null) { 6198 return pri; 6199 } 6200 6201 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6202 // Get the list of preferred activities that handle the intent 6203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6204 List<PreferredActivity> prefs = pir != null 6205 ? pir.queryIntent(intent, resolvedType, 6206 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6207 userId) 6208 : null; 6209 if (prefs != null && prefs.size() > 0) { 6210 boolean changed = false; 6211 try { 6212 // First figure out how good the original match set is. 6213 // We will only allow preferred activities that came 6214 // from the same match quality. 6215 int match = 0; 6216 6217 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6218 6219 final int N = query.size(); 6220 for (int j=0; j<N; j++) { 6221 final ResolveInfo ri = query.get(j); 6222 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6223 + ": 0x" + Integer.toHexString(match)); 6224 if (ri.match > match) { 6225 match = ri.match; 6226 } 6227 } 6228 6229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6230 + Integer.toHexString(match)); 6231 6232 match &= IntentFilter.MATCH_CATEGORY_MASK; 6233 final int M = prefs.size(); 6234 for (int i=0; i<M; i++) { 6235 final PreferredActivity pa = prefs.get(i); 6236 if (DEBUG_PREFERRED || debug) { 6237 Slog.v(TAG, "Checking PreferredActivity ds=" 6238 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6239 + "\n component=" + pa.mPref.mComponent); 6240 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6241 } 6242 if (pa.mPref.mMatch != match) { 6243 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6244 + Integer.toHexString(pa.mPref.mMatch)); 6245 continue; 6246 } 6247 // If it's not an "always" type preferred activity and that's what we're 6248 // looking for, skip it. 6249 if (always && !pa.mPref.mAlways) { 6250 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6251 continue; 6252 } 6253 final ActivityInfo ai = getActivityInfo( 6254 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6255 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6256 userId); 6257 if (DEBUG_PREFERRED || debug) { 6258 Slog.v(TAG, "Found preferred activity:"); 6259 if (ai != null) { 6260 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6261 } else { 6262 Slog.v(TAG, " null"); 6263 } 6264 } 6265 if (ai == null) { 6266 // This previously registered preferred activity 6267 // component is no longer known. Most likely an update 6268 // to the app was installed and in the new version this 6269 // component no longer exists. Clean it up by removing 6270 // it from the preferred activities list, and skip it. 6271 Slog.w(TAG, "Removing dangling preferred activity: " 6272 + pa.mPref.mComponent); 6273 pir.removeFilter(pa); 6274 changed = true; 6275 continue; 6276 } 6277 for (int j=0; j<N; j++) { 6278 final ResolveInfo ri = query.get(j); 6279 if (!ri.activityInfo.applicationInfo.packageName 6280 .equals(ai.applicationInfo.packageName)) { 6281 continue; 6282 } 6283 if (!ri.activityInfo.name.equals(ai.name)) { 6284 continue; 6285 } 6286 6287 if (removeMatches) { 6288 pir.removeFilter(pa); 6289 changed = true; 6290 if (DEBUG_PREFERRED) { 6291 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6292 } 6293 break; 6294 } 6295 6296 // Okay we found a previously set preferred or last chosen app. 6297 // If the result set is different from when this 6298 // was created, and is not a subset of the preferred set, we need to 6299 // clear it and re-ask the user their preference, if we're looking for 6300 // an "always" type entry. 6301 if (always && !pa.mPref.sameSet(query)) { 6302 if (pa.mPref.isSuperset(query)) { 6303 // some components of the set are no longer present in 6304 // the query, but the preferred activity can still be reused 6305 if (DEBUG_PREFERRED) { 6306 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6307 + " still valid as only non-preferred components" 6308 + " were removed for " + intent + " type " 6309 + resolvedType); 6310 } 6311 // remove obsolete components and re-add the up-to-date filter 6312 PreferredActivity freshPa = new PreferredActivity(pa, 6313 pa.mPref.mMatch, 6314 pa.mPref.discardObsoleteComponents(query), 6315 pa.mPref.mComponent, 6316 pa.mPref.mAlways); 6317 pir.removeFilter(pa); 6318 pir.addFilter(freshPa); 6319 changed = true; 6320 } else { 6321 Slog.i(TAG, 6322 "Result set changed, dropping preferred activity for " 6323 + intent + " type " + resolvedType); 6324 if (DEBUG_PREFERRED) { 6325 Slog.v(TAG, "Removing preferred activity since set changed " 6326 + pa.mPref.mComponent); 6327 } 6328 pir.removeFilter(pa); 6329 // Re-add the filter as a "last chosen" entry (!always) 6330 PreferredActivity lastChosen = new PreferredActivity( 6331 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6332 pir.addFilter(lastChosen); 6333 changed = true; 6334 return null; 6335 } 6336 } 6337 6338 // Yay! Either the set matched or we're looking for the last chosen 6339 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6340 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6341 return ri; 6342 } 6343 } 6344 } finally { 6345 if (changed) { 6346 if (DEBUG_PREFERRED) { 6347 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6348 } 6349 scheduleWritePackageRestrictionsLocked(userId); 6350 } 6351 } 6352 } 6353 } 6354 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6355 return null; 6356 } 6357 6358 /* 6359 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6360 */ 6361 @Override 6362 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6363 int targetUserId) { 6364 mContext.enforceCallingOrSelfPermission( 6365 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6366 List<CrossProfileIntentFilter> matches = 6367 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6368 if (matches != null) { 6369 int size = matches.size(); 6370 for (int i = 0; i < size; i++) { 6371 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6372 } 6373 } 6374 if (hasWebURI(intent)) { 6375 // cross-profile app linking works only towards the parent. 6376 final int callingUid = Binder.getCallingUid(); 6377 final UserInfo parent = getProfileParent(sourceUserId); 6378 synchronized(mPackages) { 6379 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6380 false /*includeInstantApps*/); 6381 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6382 intent, resolvedType, flags, sourceUserId, parent.id); 6383 return xpDomainInfo != null; 6384 } 6385 } 6386 return false; 6387 } 6388 6389 private UserInfo getProfileParent(int userId) { 6390 final long identity = Binder.clearCallingIdentity(); 6391 try { 6392 return sUserManager.getProfileParent(userId); 6393 } finally { 6394 Binder.restoreCallingIdentity(identity); 6395 } 6396 } 6397 6398 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6399 String resolvedType, int userId) { 6400 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6401 if (resolver != null) { 6402 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6403 } 6404 return null; 6405 } 6406 6407 @Override 6408 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6409 String resolvedType, int flags, int userId) { 6410 try { 6411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6412 6413 return new ParceledListSlice<>( 6414 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6415 } finally { 6416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6417 } 6418 } 6419 6420 /** 6421 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6422 * instant, returns {@code null}. 6423 */ 6424 private String getInstantAppPackageName(int callingUid) { 6425 synchronized (mPackages) { 6426 // If the caller is an isolated app use the owner's uid for the lookup. 6427 if (Process.isIsolated(callingUid)) { 6428 callingUid = mIsolatedOwners.get(callingUid); 6429 } 6430 final int appId = UserHandle.getAppId(callingUid); 6431 final Object obj = mSettings.getUserIdLPr(appId); 6432 if (obj instanceof PackageSetting) { 6433 final PackageSetting ps = (PackageSetting) obj; 6434 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6435 return isInstantApp ? ps.pkg.packageName : null; 6436 } 6437 } 6438 return null; 6439 } 6440 6441 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6442 String resolvedType, int flags, int userId) { 6443 return queryIntentActivitiesInternal( 6444 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6445 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6446 } 6447 6448 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6449 String resolvedType, int flags, int filterCallingUid, int userId, 6450 boolean resolveForStart, boolean allowDynamicSplits) { 6451 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6452 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6453 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6454 false /* requireFullPermission */, false /* checkShell */, 6455 "query intent activities"); 6456 final String pkgName = intent.getPackage(); 6457 ComponentName comp = intent.getComponent(); 6458 if (comp == null) { 6459 if (intent.getSelector() != null) { 6460 intent = intent.getSelector(); 6461 comp = intent.getComponent(); 6462 } 6463 } 6464 6465 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6466 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6467 if (comp != null) { 6468 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6469 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6470 if (ai != null) { 6471 // When specifying an explicit component, we prevent the activity from being 6472 // used when either 1) the calling package is normal and the activity is within 6473 // an ephemeral application or 2) the calling package is ephemeral and the 6474 // activity is not visible to ephemeral applications. 6475 final boolean matchInstantApp = 6476 (flags & PackageManager.MATCH_INSTANT) != 0; 6477 final boolean matchVisibleToInstantAppOnly = 6478 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6479 final boolean matchExplicitlyVisibleOnly = 6480 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6481 final boolean isCallerInstantApp = 6482 instantAppPkgName != null; 6483 final boolean isTargetSameInstantApp = 6484 comp.getPackageName().equals(instantAppPkgName); 6485 final boolean isTargetInstantApp = 6486 (ai.applicationInfo.privateFlags 6487 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6488 final boolean isTargetVisibleToInstantApp = 6489 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6490 final boolean isTargetExplicitlyVisibleToInstantApp = 6491 isTargetVisibleToInstantApp 6492 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6493 final boolean isTargetHiddenFromInstantApp = 6494 !isTargetVisibleToInstantApp 6495 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6496 final boolean blockResolution = 6497 !isTargetSameInstantApp 6498 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6499 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6500 && isTargetHiddenFromInstantApp)); 6501 if (!blockResolution) { 6502 final ResolveInfo ri = new ResolveInfo(); 6503 ri.activityInfo = ai; 6504 list.add(ri); 6505 } 6506 } 6507 return applyPostResolutionFilter( 6508 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6509 } 6510 6511 // reader 6512 boolean sortResult = false; 6513 boolean addEphemeral = false; 6514 List<ResolveInfo> result; 6515 final boolean ephemeralDisabled = isEphemeralDisabled(); 6516 synchronized (mPackages) { 6517 if (pkgName == null) { 6518 List<CrossProfileIntentFilter> matchingFilters = 6519 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6520 // Check for results that need to skip the current profile. 6521 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6522 resolvedType, flags, userId); 6523 if (xpResolveInfo != null) { 6524 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6525 xpResult.add(xpResolveInfo); 6526 return applyPostResolutionFilter( 6527 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6528 allowDynamicSplits, filterCallingUid, userId); 6529 } 6530 6531 // Check for results in the current profile. 6532 result = filterIfNotSystemUser(mActivities.queryIntent( 6533 intent, resolvedType, flags, userId), userId); 6534 addEphemeral = !ephemeralDisabled 6535 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6536 // Check for cross profile results. 6537 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6538 xpResolveInfo = queryCrossProfileIntents( 6539 matchingFilters, intent, resolvedType, flags, userId, 6540 hasNonNegativePriorityResult); 6541 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6542 boolean isVisibleToUser = filterIfNotSystemUser( 6543 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6544 if (isVisibleToUser) { 6545 result.add(xpResolveInfo); 6546 sortResult = true; 6547 } 6548 } 6549 if (hasWebURI(intent)) { 6550 CrossProfileDomainInfo xpDomainInfo = null; 6551 final UserInfo parent = getProfileParent(userId); 6552 if (parent != null) { 6553 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6554 flags, userId, parent.id); 6555 } 6556 if (xpDomainInfo != null) { 6557 if (xpResolveInfo != null) { 6558 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6559 // in the result. 6560 result.remove(xpResolveInfo); 6561 } 6562 if (result.size() == 0 && !addEphemeral) { 6563 // No result in current profile, but found candidate in parent user. 6564 // And we are not going to add emphemeral app, so we can return the 6565 // result straight away. 6566 result.add(xpDomainInfo.resolveInfo); 6567 return applyPostResolutionFilter(result, instantAppPkgName, 6568 allowDynamicSplits, filterCallingUid, userId); 6569 } 6570 } else if (result.size() <= 1 && !addEphemeral) { 6571 // No result in parent user and <= 1 result in current profile, and we 6572 // are not going to add emphemeral app, so we can return the result without 6573 // further processing. 6574 return applyPostResolutionFilter(result, instantAppPkgName, 6575 allowDynamicSplits, filterCallingUid, userId); 6576 } 6577 // We have more than one candidate (combining results from current and parent 6578 // profile), so we need filtering and sorting. 6579 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6580 intent, flags, result, xpDomainInfo, userId); 6581 sortResult = true; 6582 } 6583 } else { 6584 final PackageParser.Package pkg = mPackages.get(pkgName); 6585 result = null; 6586 if (pkg != null) { 6587 result = filterIfNotSystemUser( 6588 mActivities.queryIntentForPackage( 6589 intent, resolvedType, flags, pkg.activities, userId), 6590 userId); 6591 } 6592 if (result == null || result.size() == 0) { 6593 // the caller wants to resolve for a particular package; however, there 6594 // were no installed results, so, try to find an ephemeral result 6595 addEphemeral = !ephemeralDisabled 6596 && isInstantAppAllowed( 6597 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6598 if (result == null) { 6599 result = new ArrayList<>(); 6600 } 6601 } 6602 } 6603 } 6604 if (addEphemeral) { 6605 result = maybeAddInstantAppInstaller( 6606 result, intent, resolvedType, flags, userId, resolveForStart); 6607 } 6608 if (sortResult) { 6609 Collections.sort(result, mResolvePrioritySorter); 6610 } 6611 return applyPostResolutionFilter( 6612 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6613 } 6614 6615 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6616 String resolvedType, int flags, int userId, boolean resolveForStart) { 6617 // first, check to see if we've got an instant app already installed 6618 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6619 ResolveInfo localInstantApp = null; 6620 boolean blockResolution = false; 6621 if (!alreadyResolvedLocally) { 6622 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6623 flags 6624 | PackageManager.GET_RESOLVED_FILTER 6625 | PackageManager.MATCH_INSTANT 6626 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6627 userId); 6628 for (int i = instantApps.size() - 1; i >= 0; --i) { 6629 final ResolveInfo info = instantApps.get(i); 6630 final String packageName = info.activityInfo.packageName; 6631 final PackageSetting ps = mSettings.mPackages.get(packageName); 6632 if (ps.getInstantApp(userId)) { 6633 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6634 final int status = (int)(packedStatus >> 32); 6635 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6636 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6637 // there's a local instant application installed, but, the user has 6638 // chosen to never use it; skip resolution and don't acknowledge 6639 // an instant application is even available 6640 if (DEBUG_EPHEMERAL) { 6641 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6642 } 6643 blockResolution = true; 6644 break; 6645 } else { 6646 // we have a locally installed instant application; skip resolution 6647 // but acknowledge there's an instant application available 6648 if (DEBUG_EPHEMERAL) { 6649 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6650 } 6651 localInstantApp = info; 6652 break; 6653 } 6654 } 6655 } 6656 } 6657 // no app installed, let's see if one's available 6658 AuxiliaryResolveInfo auxiliaryResponse = null; 6659 if (!blockResolution) { 6660 if (localInstantApp == null) { 6661 // we don't have an instant app locally, resolve externally 6662 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6663 final InstantAppRequest requestObject = new InstantAppRequest( 6664 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6665 null /*callingPackage*/, userId, null /*verificationBundle*/, 6666 resolveForStart); 6667 auxiliaryResponse = 6668 InstantAppResolver.doInstantAppResolutionPhaseOne( 6669 mContext, mInstantAppResolverConnection, requestObject); 6670 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6671 } else { 6672 // we have an instant application locally, but, we can't admit that since 6673 // callers shouldn't be able to determine prior browsing. create a dummy 6674 // auxiliary response so the downstream code behaves as if there's an 6675 // instant application available externally. when it comes time to start 6676 // the instant application, we'll do the right thing. 6677 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6678 auxiliaryResponse = new AuxiliaryResolveInfo( 6679 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6680 ai.versionCode, null /*failureIntent*/); 6681 } 6682 } 6683 if (auxiliaryResponse != null) { 6684 if (DEBUG_EPHEMERAL) { 6685 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6686 } 6687 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6688 final PackageSetting ps = 6689 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6690 if (ps != null) { 6691 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6692 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6693 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6694 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6695 // make sure this resolver is the default 6696 ephemeralInstaller.isDefault = true; 6697 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6698 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6699 // add a non-generic filter 6700 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6701 ephemeralInstaller.filter.addDataPath( 6702 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6703 ephemeralInstaller.isInstantAppAvailable = true; 6704 result.add(ephemeralInstaller); 6705 } 6706 } 6707 return result; 6708 } 6709 6710 private static class CrossProfileDomainInfo { 6711 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6712 ResolveInfo resolveInfo; 6713 /* Best domain verification status of the activities found in the other profile */ 6714 int bestDomainVerificationStatus; 6715 } 6716 6717 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6718 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6719 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6720 sourceUserId)) { 6721 return null; 6722 } 6723 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6724 resolvedType, flags, parentUserId); 6725 6726 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6727 return null; 6728 } 6729 CrossProfileDomainInfo result = null; 6730 int size = resultTargetUser.size(); 6731 for (int i = 0; i < size; i++) { 6732 ResolveInfo riTargetUser = resultTargetUser.get(i); 6733 // Intent filter verification is only for filters that specify a host. So don't return 6734 // those that handle all web uris. 6735 if (riTargetUser.handleAllWebDataURI) { 6736 continue; 6737 } 6738 String packageName = riTargetUser.activityInfo.packageName; 6739 PackageSetting ps = mSettings.mPackages.get(packageName); 6740 if (ps == null) { 6741 continue; 6742 } 6743 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6744 int status = (int)(verificationState >> 32); 6745 if (result == null) { 6746 result = new CrossProfileDomainInfo(); 6747 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6748 sourceUserId, parentUserId); 6749 result.bestDomainVerificationStatus = status; 6750 } else { 6751 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6752 result.bestDomainVerificationStatus); 6753 } 6754 } 6755 // Don't consider matches with status NEVER across profiles. 6756 if (result != null && result.bestDomainVerificationStatus 6757 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6758 return null; 6759 } 6760 return result; 6761 } 6762 6763 /** 6764 * Verification statuses are ordered from the worse to the best, except for 6765 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6766 */ 6767 private int bestDomainVerificationStatus(int status1, int status2) { 6768 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6769 return status2; 6770 } 6771 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6772 return status1; 6773 } 6774 return (int) MathUtils.max(status1, status2); 6775 } 6776 6777 private boolean isUserEnabled(int userId) { 6778 long callingId = Binder.clearCallingIdentity(); 6779 try { 6780 UserInfo userInfo = sUserManager.getUserInfo(userId); 6781 return userInfo != null && userInfo.isEnabled(); 6782 } finally { 6783 Binder.restoreCallingIdentity(callingId); 6784 } 6785 } 6786 6787 /** 6788 * Filter out activities with systemUserOnly flag set, when current user is not System. 6789 * 6790 * @return filtered list 6791 */ 6792 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6793 if (userId == UserHandle.USER_SYSTEM) { 6794 return resolveInfos; 6795 } 6796 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6797 ResolveInfo info = resolveInfos.get(i); 6798 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6799 resolveInfos.remove(i); 6800 } 6801 } 6802 return resolveInfos; 6803 } 6804 6805 /** 6806 * Filters out ephemeral activities. 6807 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6808 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6809 * 6810 * @param resolveInfos The pre-filtered list of resolved activities 6811 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6812 * is performed. 6813 * @return A filtered list of resolved activities. 6814 */ 6815 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6816 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6817 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6818 final ResolveInfo info = resolveInfos.get(i); 6819 // allow activities that are defined in the provided package 6820 if (allowDynamicSplits 6821 && info.activityInfo.splitName != null 6822 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6823 info.activityInfo.splitName)) { 6824 if (mInstantAppInstallerInfo == null) { 6825 if (DEBUG_INSTALL) { 6826 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6827 } 6828 resolveInfos.remove(i); 6829 continue; 6830 } 6831 // requested activity is defined in a split that hasn't been installed yet. 6832 // add the installer to the resolve list 6833 if (DEBUG_INSTALL) { 6834 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6835 } 6836 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6837 final ComponentName installFailureActivity = findInstallFailureActivity( 6838 info.activityInfo.packageName, filterCallingUid, userId); 6839 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6840 info.activityInfo.packageName, info.activityInfo.splitName, 6841 installFailureActivity, 6842 info.activityInfo.applicationInfo.versionCode, 6843 null /*failureIntent*/); 6844 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6845 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6846 // add a non-generic filter 6847 installerInfo.filter = new IntentFilter(); 6848 6849 // This resolve info may appear in the chooser UI, so let us make it 6850 // look as the one it replaces as far as the user is concerned which 6851 // requires loading the correct label and icon for the resolve info. 6852 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6853 installerInfo.labelRes = info.resolveLabelResId(); 6854 installerInfo.icon = info.resolveIconResId(); 6855 6856 // propagate priority/preferred order/default 6857 installerInfo.priority = info.priority; 6858 installerInfo.preferredOrder = info.preferredOrder; 6859 installerInfo.isDefault = info.isDefault; 6860 resolveInfos.set(i, installerInfo); 6861 continue; 6862 } 6863 // caller is a full app, don't need to apply any other filtering 6864 if (ephemeralPkgName == null) { 6865 continue; 6866 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6867 // caller is same app; don't need to apply any other filtering 6868 continue; 6869 } 6870 // allow activities that have been explicitly exposed to ephemeral apps 6871 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6872 if (!isEphemeralApp 6873 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6874 continue; 6875 } 6876 resolveInfos.remove(i); 6877 } 6878 return resolveInfos; 6879 } 6880 6881 /** 6882 * Returns the activity component that can handle install failures. 6883 * <p>By default, the instant application installer handles failures. However, an 6884 * application may want to handle failures on its own. Applications do this by 6885 * creating an activity with an intent filter that handles the action 6886 * {@link Intent#ACTION_INSTALL_FAILURE}. 6887 */ 6888 private @Nullable ComponentName findInstallFailureActivity( 6889 String packageName, int filterCallingUid, int userId) { 6890 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6891 failureActivityIntent.setPackage(packageName); 6892 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6893 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6894 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6895 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6896 final int NR = result.size(); 6897 if (NR > 0) { 6898 for (int i = 0; i < NR; i++) { 6899 final ResolveInfo info = result.get(i); 6900 if (info.activityInfo.splitName != null) { 6901 continue; 6902 } 6903 return new ComponentName(packageName, info.activityInfo.name); 6904 } 6905 } 6906 return null; 6907 } 6908 6909 /** 6910 * @param resolveInfos list of resolve infos in descending priority order 6911 * @return if the list contains a resolve info with non-negative priority 6912 */ 6913 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6914 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6915 } 6916 6917 private static boolean hasWebURI(Intent intent) { 6918 if (intent.getData() == null) { 6919 return false; 6920 } 6921 final String scheme = intent.getScheme(); 6922 if (TextUtils.isEmpty(scheme)) { 6923 return false; 6924 } 6925 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6926 } 6927 6928 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6929 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6930 int userId) { 6931 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6932 6933 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6934 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6935 candidates.size()); 6936 } 6937 6938 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6939 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6940 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6941 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6942 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6943 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6944 6945 synchronized (mPackages) { 6946 final int count = candidates.size(); 6947 // First, try to use linked apps. Partition the candidates into four lists: 6948 // one for the final results, one for the "do not use ever", one for "undefined status" 6949 // and finally one for "browser app type". 6950 for (int n=0; n<count; n++) { 6951 ResolveInfo info = candidates.get(n); 6952 String packageName = info.activityInfo.packageName; 6953 PackageSetting ps = mSettings.mPackages.get(packageName); 6954 if (ps != null) { 6955 // Add to the special match all list (Browser use case) 6956 if (info.handleAllWebDataURI) { 6957 matchAllList.add(info); 6958 continue; 6959 } 6960 // Try to get the status from User settings first 6961 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6962 int status = (int)(packedStatus >> 32); 6963 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6964 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6965 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6966 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6967 + " : linkgen=" + linkGeneration); 6968 } 6969 // Use link-enabled generation as preferredOrder, i.e. 6970 // prefer newly-enabled over earlier-enabled. 6971 info.preferredOrder = linkGeneration; 6972 alwaysList.add(info); 6973 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6974 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6975 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6976 } 6977 neverList.add(info); 6978 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6979 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6980 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6981 } 6982 alwaysAskList.add(info); 6983 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6984 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6985 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6986 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6987 } 6988 undefinedList.add(info); 6989 } 6990 } 6991 } 6992 6993 // We'll want to include browser possibilities in a few cases 6994 boolean includeBrowser = false; 6995 6996 // First try to add the "always" resolution(s) for the current user, if any 6997 if (alwaysList.size() > 0) { 6998 result.addAll(alwaysList); 6999 } else { 7000 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7001 result.addAll(undefinedList); 7002 // Maybe add one for the other profile. 7003 if (xpDomainInfo != null && ( 7004 xpDomainInfo.bestDomainVerificationStatus 7005 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7006 result.add(xpDomainInfo.resolveInfo); 7007 } 7008 includeBrowser = true; 7009 } 7010 7011 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7012 // If there were 'always' entries their preferred order has been set, so we also 7013 // back that off to make the alternatives equivalent 7014 if (alwaysAskList.size() > 0) { 7015 for (ResolveInfo i : result) { 7016 i.preferredOrder = 0; 7017 } 7018 result.addAll(alwaysAskList); 7019 includeBrowser = true; 7020 } 7021 7022 if (includeBrowser) { 7023 // Also add browsers (all of them or only the default one) 7024 if (DEBUG_DOMAIN_VERIFICATION) { 7025 Slog.v(TAG, " ...including browsers in candidate set"); 7026 } 7027 if ((matchFlags & MATCH_ALL) != 0) { 7028 result.addAll(matchAllList); 7029 } else { 7030 // Browser/generic handling case. If there's a default browser, go straight 7031 // to that (but only if there is no other higher-priority match). 7032 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7033 int maxMatchPrio = 0; 7034 ResolveInfo defaultBrowserMatch = null; 7035 final int numCandidates = matchAllList.size(); 7036 for (int n = 0; n < numCandidates; n++) { 7037 ResolveInfo info = matchAllList.get(n); 7038 // track the highest overall match priority... 7039 if (info.priority > maxMatchPrio) { 7040 maxMatchPrio = info.priority; 7041 } 7042 // ...and the highest-priority default browser match 7043 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7044 if (defaultBrowserMatch == null 7045 || (defaultBrowserMatch.priority < info.priority)) { 7046 if (debug) { 7047 Slog.v(TAG, "Considering default browser match " + info); 7048 } 7049 defaultBrowserMatch = info; 7050 } 7051 } 7052 } 7053 if (defaultBrowserMatch != null 7054 && defaultBrowserMatch.priority >= maxMatchPrio 7055 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7056 { 7057 if (debug) { 7058 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7059 } 7060 result.add(defaultBrowserMatch); 7061 } else { 7062 result.addAll(matchAllList); 7063 } 7064 } 7065 7066 // If there is nothing selected, add all candidates and remove the ones that the user 7067 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7068 if (result.size() == 0) { 7069 result.addAll(candidates); 7070 result.removeAll(neverList); 7071 } 7072 } 7073 } 7074 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7075 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7076 result.size()); 7077 for (ResolveInfo info : result) { 7078 Slog.v(TAG, " + " + info.activityInfo); 7079 } 7080 } 7081 return result; 7082 } 7083 7084 // Returns a packed value as a long: 7085 // 7086 // high 'int'-sized word: link status: undefined/ask/never/always. 7087 // low 'int'-sized word: relative priority among 'always' results. 7088 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7089 long result = ps.getDomainVerificationStatusForUser(userId); 7090 // if none available, get the master status 7091 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7092 if (ps.getIntentFilterVerificationInfo() != null) { 7093 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7094 } 7095 } 7096 return result; 7097 } 7098 7099 private ResolveInfo querySkipCurrentProfileIntents( 7100 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7101 int flags, int sourceUserId) { 7102 if (matchingFilters != null) { 7103 int size = matchingFilters.size(); 7104 for (int i = 0; i < size; i ++) { 7105 CrossProfileIntentFilter filter = matchingFilters.get(i); 7106 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7107 // Checking if there are activities in the target user that can handle the 7108 // intent. 7109 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7110 resolvedType, flags, sourceUserId); 7111 if (resolveInfo != null) { 7112 return resolveInfo; 7113 } 7114 } 7115 } 7116 } 7117 return null; 7118 } 7119 7120 // Return matching ResolveInfo in target user if any. 7121 private ResolveInfo queryCrossProfileIntents( 7122 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7123 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7124 if (matchingFilters != null) { 7125 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7126 // match the same intent. For performance reasons, it is better not to 7127 // run queryIntent twice for the same userId 7128 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7129 int size = matchingFilters.size(); 7130 for (int i = 0; i < size; i++) { 7131 CrossProfileIntentFilter filter = matchingFilters.get(i); 7132 int targetUserId = filter.getTargetUserId(); 7133 boolean skipCurrentProfile = 7134 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7135 boolean skipCurrentProfileIfNoMatchFound = 7136 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7137 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7138 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7139 // Checking if there are activities in the target user that can handle the 7140 // intent. 7141 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7142 resolvedType, flags, sourceUserId); 7143 if (resolveInfo != null) return resolveInfo; 7144 alreadyTriedUserIds.put(targetUserId, true); 7145 } 7146 } 7147 } 7148 return null; 7149 } 7150 7151 /** 7152 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7153 * will forward the intent to the filter's target user. 7154 * Otherwise, returns null. 7155 */ 7156 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7157 String resolvedType, int flags, int sourceUserId) { 7158 int targetUserId = filter.getTargetUserId(); 7159 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7160 resolvedType, flags, targetUserId); 7161 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7162 // If all the matches in the target profile are suspended, return null. 7163 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7164 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7165 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7166 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7167 targetUserId); 7168 } 7169 } 7170 } 7171 return null; 7172 } 7173 7174 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7175 int sourceUserId, int targetUserId) { 7176 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7177 long ident = Binder.clearCallingIdentity(); 7178 boolean targetIsProfile; 7179 try { 7180 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7181 } finally { 7182 Binder.restoreCallingIdentity(ident); 7183 } 7184 String className; 7185 if (targetIsProfile) { 7186 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7187 } else { 7188 className = FORWARD_INTENT_TO_PARENT; 7189 } 7190 ComponentName forwardingActivityComponentName = new ComponentName( 7191 mAndroidApplication.packageName, className); 7192 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7193 sourceUserId); 7194 if (!targetIsProfile) { 7195 forwardingActivityInfo.showUserIcon = targetUserId; 7196 forwardingResolveInfo.noResourceId = true; 7197 } 7198 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7199 forwardingResolveInfo.priority = 0; 7200 forwardingResolveInfo.preferredOrder = 0; 7201 forwardingResolveInfo.match = 0; 7202 forwardingResolveInfo.isDefault = true; 7203 forwardingResolveInfo.filter = filter; 7204 forwardingResolveInfo.targetUserId = targetUserId; 7205 return forwardingResolveInfo; 7206 } 7207 7208 @Override 7209 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7210 Intent[] specifics, String[] specificTypes, Intent intent, 7211 String resolvedType, int flags, int userId) { 7212 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7213 specificTypes, intent, resolvedType, flags, userId)); 7214 } 7215 7216 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7217 Intent[] specifics, String[] specificTypes, Intent intent, 7218 String resolvedType, int flags, int userId) { 7219 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7220 final int callingUid = Binder.getCallingUid(); 7221 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7222 false /*includeInstantApps*/); 7223 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7224 false /*requireFullPermission*/, false /*checkShell*/, 7225 "query intent activity options"); 7226 final String resultsAction = intent.getAction(); 7227 7228 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7229 | PackageManager.GET_RESOLVED_FILTER, userId); 7230 7231 if (DEBUG_INTENT_MATCHING) { 7232 Log.v(TAG, "Query " + intent + ": " + results); 7233 } 7234 7235 int specificsPos = 0; 7236 int N; 7237 7238 // todo: note that the algorithm used here is O(N^2). This 7239 // isn't a problem in our current environment, but if we start running 7240 // into situations where we have more than 5 or 10 matches then this 7241 // should probably be changed to something smarter... 7242 7243 // First we go through and resolve each of the specific items 7244 // that were supplied, taking care of removing any corresponding 7245 // duplicate items in the generic resolve list. 7246 if (specifics != null) { 7247 for (int i=0; i<specifics.length; i++) { 7248 final Intent sintent = specifics[i]; 7249 if (sintent == null) { 7250 continue; 7251 } 7252 7253 if (DEBUG_INTENT_MATCHING) { 7254 Log.v(TAG, "Specific #" + i + ": " + sintent); 7255 } 7256 7257 String action = sintent.getAction(); 7258 if (resultsAction != null && resultsAction.equals(action)) { 7259 // If this action was explicitly requested, then don't 7260 // remove things that have it. 7261 action = null; 7262 } 7263 7264 ResolveInfo ri = null; 7265 ActivityInfo ai = null; 7266 7267 ComponentName comp = sintent.getComponent(); 7268 if (comp == null) { 7269 ri = resolveIntent( 7270 sintent, 7271 specificTypes != null ? specificTypes[i] : null, 7272 flags, userId); 7273 if (ri == null) { 7274 continue; 7275 } 7276 if (ri == mResolveInfo) { 7277 // ACK! Must do something better with this. 7278 } 7279 ai = ri.activityInfo; 7280 comp = new ComponentName(ai.applicationInfo.packageName, 7281 ai.name); 7282 } else { 7283 ai = getActivityInfo(comp, flags, userId); 7284 if (ai == null) { 7285 continue; 7286 } 7287 } 7288 7289 // Look for any generic query activities that are duplicates 7290 // of this specific one, and remove them from the results. 7291 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7292 N = results.size(); 7293 int j; 7294 for (j=specificsPos; j<N; j++) { 7295 ResolveInfo sri = results.get(j); 7296 if ((sri.activityInfo.name.equals(comp.getClassName()) 7297 && sri.activityInfo.applicationInfo.packageName.equals( 7298 comp.getPackageName())) 7299 || (action != null && sri.filter.matchAction(action))) { 7300 results.remove(j); 7301 if (DEBUG_INTENT_MATCHING) Log.v( 7302 TAG, "Removing duplicate item from " + j 7303 + " due to specific " + specificsPos); 7304 if (ri == null) { 7305 ri = sri; 7306 } 7307 j--; 7308 N--; 7309 } 7310 } 7311 7312 // Add this specific item to its proper place. 7313 if (ri == null) { 7314 ri = new ResolveInfo(); 7315 ri.activityInfo = ai; 7316 } 7317 results.add(specificsPos, ri); 7318 ri.specificIndex = i; 7319 specificsPos++; 7320 } 7321 } 7322 7323 // Now we go through the remaining generic results and remove any 7324 // duplicate actions that are found here. 7325 N = results.size(); 7326 for (int i=specificsPos; i<N-1; i++) { 7327 final ResolveInfo rii = results.get(i); 7328 if (rii.filter == null) { 7329 continue; 7330 } 7331 7332 // Iterate over all of the actions of this result's intent 7333 // filter... typically this should be just one. 7334 final Iterator<String> it = rii.filter.actionsIterator(); 7335 if (it == null) { 7336 continue; 7337 } 7338 while (it.hasNext()) { 7339 final String action = it.next(); 7340 if (resultsAction != null && resultsAction.equals(action)) { 7341 // If this action was explicitly requested, then don't 7342 // remove things that have it. 7343 continue; 7344 } 7345 for (int j=i+1; j<N; j++) { 7346 final ResolveInfo rij = results.get(j); 7347 if (rij.filter != null && rij.filter.hasAction(action)) { 7348 results.remove(j); 7349 if (DEBUG_INTENT_MATCHING) Log.v( 7350 TAG, "Removing duplicate item from " + j 7351 + " due to action " + action + " at " + i); 7352 j--; 7353 N--; 7354 } 7355 } 7356 } 7357 7358 // If the caller didn't request filter information, drop it now 7359 // so we don't have to marshall/unmarshall it. 7360 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7361 rii.filter = null; 7362 } 7363 } 7364 7365 // Filter out the caller activity if so requested. 7366 if (caller != null) { 7367 N = results.size(); 7368 for (int i=0; i<N; i++) { 7369 ActivityInfo ainfo = results.get(i).activityInfo; 7370 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7371 && caller.getClassName().equals(ainfo.name)) { 7372 results.remove(i); 7373 break; 7374 } 7375 } 7376 } 7377 7378 // If the caller didn't request filter information, 7379 // drop them now so we don't have to 7380 // marshall/unmarshall it. 7381 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7382 N = results.size(); 7383 for (int i=0; i<N; i++) { 7384 results.get(i).filter = null; 7385 } 7386 } 7387 7388 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7389 return results; 7390 } 7391 7392 @Override 7393 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7394 String resolvedType, int flags, int userId) { 7395 return new ParceledListSlice<>( 7396 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7397 false /*allowDynamicSplits*/)); 7398 } 7399 7400 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7401 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7402 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7403 final int callingUid = Binder.getCallingUid(); 7404 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7405 false /*requireFullPermission*/, false /*checkShell*/, 7406 "query intent receivers"); 7407 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7408 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7409 false /*includeInstantApps*/); 7410 ComponentName comp = intent.getComponent(); 7411 if (comp == null) { 7412 if (intent.getSelector() != null) { 7413 intent = intent.getSelector(); 7414 comp = intent.getComponent(); 7415 } 7416 } 7417 if (comp != null) { 7418 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7419 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7420 if (ai != null) { 7421 // When specifying an explicit component, we prevent the activity from being 7422 // used when either 1) the calling package is normal and the activity is within 7423 // an instant application or 2) the calling package is ephemeral and the 7424 // activity is not visible to instant applications. 7425 final boolean matchInstantApp = 7426 (flags & PackageManager.MATCH_INSTANT) != 0; 7427 final boolean matchVisibleToInstantAppOnly = 7428 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7429 final boolean matchExplicitlyVisibleOnly = 7430 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7431 final boolean isCallerInstantApp = 7432 instantAppPkgName != null; 7433 final boolean isTargetSameInstantApp = 7434 comp.getPackageName().equals(instantAppPkgName); 7435 final boolean isTargetInstantApp = 7436 (ai.applicationInfo.privateFlags 7437 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7438 final boolean isTargetVisibleToInstantApp = 7439 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7440 final boolean isTargetExplicitlyVisibleToInstantApp = 7441 isTargetVisibleToInstantApp 7442 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7443 final boolean isTargetHiddenFromInstantApp = 7444 !isTargetVisibleToInstantApp 7445 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7446 final boolean blockResolution = 7447 !isTargetSameInstantApp 7448 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7449 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7450 && isTargetHiddenFromInstantApp)); 7451 if (!blockResolution) { 7452 ResolveInfo ri = new ResolveInfo(); 7453 ri.activityInfo = ai; 7454 list.add(ri); 7455 } 7456 } 7457 return applyPostResolutionFilter( 7458 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7459 } 7460 7461 // reader 7462 synchronized (mPackages) { 7463 String pkgName = intent.getPackage(); 7464 if (pkgName == null) { 7465 final List<ResolveInfo> result = 7466 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7467 return applyPostResolutionFilter( 7468 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7469 } 7470 final PackageParser.Package pkg = mPackages.get(pkgName); 7471 if (pkg != null) { 7472 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7473 intent, resolvedType, flags, pkg.receivers, userId); 7474 return applyPostResolutionFilter( 7475 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7476 } 7477 return Collections.emptyList(); 7478 } 7479 } 7480 7481 @Override 7482 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7483 final int callingUid = Binder.getCallingUid(); 7484 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7485 } 7486 7487 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7488 int userId, int callingUid) { 7489 if (!sUserManager.exists(userId)) return null; 7490 flags = updateFlagsForResolve( 7491 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7492 List<ResolveInfo> query = queryIntentServicesInternal( 7493 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7494 if (query != null) { 7495 if (query.size() >= 1) { 7496 // If there is more than one service with the same priority, 7497 // just arbitrarily pick the first one. 7498 return query.get(0); 7499 } 7500 } 7501 return null; 7502 } 7503 7504 @Override 7505 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7506 String resolvedType, int flags, int userId) { 7507 final int callingUid = Binder.getCallingUid(); 7508 return new ParceledListSlice<>(queryIntentServicesInternal( 7509 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7510 } 7511 7512 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7513 String resolvedType, int flags, int userId, int callingUid, 7514 boolean includeInstantApps) { 7515 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7516 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7517 false /*requireFullPermission*/, false /*checkShell*/, 7518 "query intent receivers"); 7519 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7520 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7521 ComponentName comp = intent.getComponent(); 7522 if (comp == null) { 7523 if (intent.getSelector() != null) { 7524 intent = intent.getSelector(); 7525 comp = intent.getComponent(); 7526 } 7527 } 7528 if (comp != null) { 7529 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7530 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7531 if (si != null) { 7532 // When specifying an explicit component, we prevent the service from being 7533 // used when either 1) the service is in an instant application and the 7534 // caller is not the same instant application or 2) the calling package is 7535 // ephemeral and the activity is not visible to ephemeral applications. 7536 final boolean matchInstantApp = 7537 (flags & PackageManager.MATCH_INSTANT) != 0; 7538 final boolean matchVisibleToInstantAppOnly = 7539 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7540 final boolean isCallerInstantApp = 7541 instantAppPkgName != null; 7542 final boolean isTargetSameInstantApp = 7543 comp.getPackageName().equals(instantAppPkgName); 7544 final boolean isTargetInstantApp = 7545 (si.applicationInfo.privateFlags 7546 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7547 final boolean isTargetHiddenFromInstantApp = 7548 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7549 final boolean blockResolution = 7550 !isTargetSameInstantApp 7551 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7552 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7553 && isTargetHiddenFromInstantApp)); 7554 if (!blockResolution) { 7555 final ResolveInfo ri = new ResolveInfo(); 7556 ri.serviceInfo = si; 7557 list.add(ri); 7558 } 7559 } 7560 return list; 7561 } 7562 7563 // reader 7564 synchronized (mPackages) { 7565 String pkgName = intent.getPackage(); 7566 if (pkgName == null) { 7567 return applyPostServiceResolutionFilter( 7568 mServices.queryIntent(intent, resolvedType, flags, userId), 7569 instantAppPkgName); 7570 } 7571 final PackageParser.Package pkg = mPackages.get(pkgName); 7572 if (pkg != null) { 7573 return applyPostServiceResolutionFilter( 7574 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7575 userId), 7576 instantAppPkgName); 7577 } 7578 return Collections.emptyList(); 7579 } 7580 } 7581 7582 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7583 String instantAppPkgName) { 7584 if (instantAppPkgName == null) { 7585 return resolveInfos; 7586 } 7587 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7588 final ResolveInfo info = resolveInfos.get(i); 7589 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7590 // allow services that are defined in the provided package 7591 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7592 if (info.serviceInfo.splitName != null 7593 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7594 info.serviceInfo.splitName)) { 7595 // requested service is defined in a split that hasn't been installed yet. 7596 // add the installer to the resolve list 7597 if (DEBUG_EPHEMERAL) { 7598 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7599 } 7600 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7601 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7602 info.serviceInfo.packageName, info.serviceInfo.splitName, 7603 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7604 null /*failureIntent*/); 7605 // make sure this resolver is the default 7606 installerInfo.isDefault = true; 7607 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7608 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7609 // add a non-generic filter 7610 installerInfo.filter = new IntentFilter(); 7611 // load resources from the correct package 7612 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7613 resolveInfos.set(i, installerInfo); 7614 } 7615 continue; 7616 } 7617 // allow services that have been explicitly exposed to ephemeral apps 7618 if (!isEphemeralApp 7619 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7620 continue; 7621 } 7622 resolveInfos.remove(i); 7623 } 7624 return resolveInfos; 7625 } 7626 7627 @Override 7628 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7629 String resolvedType, int flags, int userId) { 7630 return new ParceledListSlice<>( 7631 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7632 } 7633 7634 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7635 Intent intent, String resolvedType, int flags, int userId) { 7636 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7637 final int callingUid = Binder.getCallingUid(); 7638 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7639 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7640 false /*includeInstantApps*/); 7641 ComponentName comp = intent.getComponent(); 7642 if (comp == null) { 7643 if (intent.getSelector() != null) { 7644 intent = intent.getSelector(); 7645 comp = intent.getComponent(); 7646 } 7647 } 7648 if (comp != null) { 7649 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7650 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7651 if (pi != null) { 7652 // When specifying an explicit component, we prevent the provider from being 7653 // used when either 1) the provider is in an instant application and the 7654 // caller is not the same instant application or 2) the calling package is an 7655 // instant application and the provider is not visible to instant applications. 7656 final boolean matchInstantApp = 7657 (flags & PackageManager.MATCH_INSTANT) != 0; 7658 final boolean matchVisibleToInstantAppOnly = 7659 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7660 final boolean isCallerInstantApp = 7661 instantAppPkgName != null; 7662 final boolean isTargetSameInstantApp = 7663 comp.getPackageName().equals(instantAppPkgName); 7664 final boolean isTargetInstantApp = 7665 (pi.applicationInfo.privateFlags 7666 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7667 final boolean isTargetHiddenFromInstantApp = 7668 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7669 final boolean blockResolution = 7670 !isTargetSameInstantApp 7671 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7672 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7673 && isTargetHiddenFromInstantApp)); 7674 if (!blockResolution) { 7675 final ResolveInfo ri = new ResolveInfo(); 7676 ri.providerInfo = pi; 7677 list.add(ri); 7678 } 7679 } 7680 return list; 7681 } 7682 7683 // reader 7684 synchronized (mPackages) { 7685 String pkgName = intent.getPackage(); 7686 if (pkgName == null) { 7687 return applyPostContentProviderResolutionFilter( 7688 mProviders.queryIntent(intent, resolvedType, flags, userId), 7689 instantAppPkgName); 7690 } 7691 final PackageParser.Package pkg = mPackages.get(pkgName); 7692 if (pkg != null) { 7693 return applyPostContentProviderResolutionFilter( 7694 mProviders.queryIntentForPackage( 7695 intent, resolvedType, flags, pkg.providers, userId), 7696 instantAppPkgName); 7697 } 7698 return Collections.emptyList(); 7699 } 7700 } 7701 7702 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7703 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7704 if (instantAppPkgName == null) { 7705 return resolveInfos; 7706 } 7707 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7708 final ResolveInfo info = resolveInfos.get(i); 7709 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7710 // allow providers that are defined in the provided package 7711 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7712 if (info.providerInfo.splitName != null 7713 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7714 info.providerInfo.splitName)) { 7715 // requested provider is defined in a split that hasn't been installed yet. 7716 // add the installer to the resolve list 7717 if (DEBUG_EPHEMERAL) { 7718 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7719 } 7720 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7721 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7722 info.providerInfo.packageName, info.providerInfo.splitName, 7723 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7724 null /*failureIntent*/); 7725 // make sure this resolver is the default 7726 installerInfo.isDefault = true; 7727 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7728 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7729 // add a non-generic filter 7730 installerInfo.filter = new IntentFilter(); 7731 // load resources from the correct package 7732 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7733 resolveInfos.set(i, installerInfo); 7734 } 7735 continue; 7736 } 7737 // allow providers that have been explicitly exposed to instant applications 7738 if (!isEphemeralApp 7739 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7740 continue; 7741 } 7742 resolveInfos.remove(i); 7743 } 7744 return resolveInfos; 7745 } 7746 7747 @Override 7748 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7749 final int callingUid = Binder.getCallingUid(); 7750 if (getInstantAppPackageName(callingUid) != null) { 7751 return ParceledListSlice.emptyList(); 7752 } 7753 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7754 flags = updateFlagsForPackage(flags, userId, null); 7755 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7756 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7757 true /* requireFullPermission */, false /* checkShell */, 7758 "get installed packages"); 7759 7760 // writer 7761 synchronized (mPackages) { 7762 ArrayList<PackageInfo> list; 7763 if (listUninstalled) { 7764 list = new ArrayList<>(mSettings.mPackages.size()); 7765 for (PackageSetting ps : mSettings.mPackages.values()) { 7766 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7767 continue; 7768 } 7769 if (filterAppAccessLPr(ps, callingUid, userId)) { 7770 continue; 7771 } 7772 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7773 if (pi != null) { 7774 list.add(pi); 7775 } 7776 } 7777 } else { 7778 list = new ArrayList<>(mPackages.size()); 7779 for (PackageParser.Package p : mPackages.values()) { 7780 final PackageSetting ps = (PackageSetting) p.mExtras; 7781 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7782 continue; 7783 } 7784 if (filterAppAccessLPr(ps, callingUid, userId)) { 7785 continue; 7786 } 7787 final PackageInfo pi = generatePackageInfo((PackageSetting) 7788 p.mExtras, flags, userId); 7789 if (pi != null) { 7790 list.add(pi); 7791 } 7792 } 7793 } 7794 7795 return new ParceledListSlice<>(list); 7796 } 7797 } 7798 7799 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7800 String[] permissions, boolean[] tmp, int flags, int userId) { 7801 int numMatch = 0; 7802 final PermissionsState permissionsState = ps.getPermissionsState(); 7803 for (int i=0; i<permissions.length; i++) { 7804 final String permission = permissions[i]; 7805 if (permissionsState.hasPermission(permission, userId)) { 7806 tmp[i] = true; 7807 numMatch++; 7808 } else { 7809 tmp[i] = false; 7810 } 7811 } 7812 if (numMatch == 0) { 7813 return; 7814 } 7815 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7816 7817 // The above might return null in cases of uninstalled apps or install-state 7818 // skew across users/profiles. 7819 if (pi != null) { 7820 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7821 if (numMatch == permissions.length) { 7822 pi.requestedPermissions = permissions; 7823 } else { 7824 pi.requestedPermissions = new String[numMatch]; 7825 numMatch = 0; 7826 for (int i=0; i<permissions.length; i++) { 7827 if (tmp[i]) { 7828 pi.requestedPermissions[numMatch] = permissions[i]; 7829 numMatch++; 7830 } 7831 } 7832 } 7833 } 7834 list.add(pi); 7835 } 7836 } 7837 7838 @Override 7839 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7840 String[] permissions, int flags, int userId) { 7841 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7842 flags = updateFlagsForPackage(flags, userId, permissions); 7843 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7844 true /* requireFullPermission */, false /* checkShell */, 7845 "get packages holding permissions"); 7846 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7847 7848 // writer 7849 synchronized (mPackages) { 7850 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7851 boolean[] tmpBools = new boolean[permissions.length]; 7852 if (listUninstalled) { 7853 for (PackageSetting ps : mSettings.mPackages.values()) { 7854 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7855 userId); 7856 } 7857 } else { 7858 for (PackageParser.Package pkg : mPackages.values()) { 7859 PackageSetting ps = (PackageSetting)pkg.mExtras; 7860 if (ps != null) { 7861 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7862 userId); 7863 } 7864 } 7865 } 7866 7867 return new ParceledListSlice<PackageInfo>(list); 7868 } 7869 } 7870 7871 @Override 7872 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7873 final int callingUid = Binder.getCallingUid(); 7874 if (getInstantAppPackageName(callingUid) != null) { 7875 return ParceledListSlice.emptyList(); 7876 } 7877 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7878 flags = updateFlagsForApplication(flags, userId, null); 7879 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7880 7881 // writer 7882 synchronized (mPackages) { 7883 ArrayList<ApplicationInfo> list; 7884 if (listUninstalled) { 7885 list = new ArrayList<>(mSettings.mPackages.size()); 7886 for (PackageSetting ps : mSettings.mPackages.values()) { 7887 ApplicationInfo ai; 7888 int effectiveFlags = flags; 7889 if (ps.isSystem()) { 7890 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7891 } 7892 if (ps.pkg != null) { 7893 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7894 continue; 7895 } 7896 if (filterAppAccessLPr(ps, callingUid, userId)) { 7897 continue; 7898 } 7899 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7900 ps.readUserState(userId), userId); 7901 if (ai != null) { 7902 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7903 } 7904 } else { 7905 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7906 // and already converts to externally visible package name 7907 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7908 callingUid, effectiveFlags, userId); 7909 } 7910 if (ai != null) { 7911 list.add(ai); 7912 } 7913 } 7914 } else { 7915 list = new ArrayList<>(mPackages.size()); 7916 for (PackageParser.Package p : mPackages.values()) { 7917 if (p.mExtras != null) { 7918 PackageSetting ps = (PackageSetting) p.mExtras; 7919 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7920 continue; 7921 } 7922 if (filterAppAccessLPr(ps, callingUid, userId)) { 7923 continue; 7924 } 7925 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7926 ps.readUserState(userId), userId); 7927 if (ai != null) { 7928 ai.packageName = resolveExternalPackageNameLPr(p); 7929 list.add(ai); 7930 } 7931 } 7932 } 7933 } 7934 7935 return new ParceledListSlice<>(list); 7936 } 7937 } 7938 7939 @Override 7940 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7941 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7942 return null; 7943 } 7944 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7945 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7946 "getEphemeralApplications"); 7947 } 7948 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7949 true /* requireFullPermission */, false /* checkShell */, 7950 "getEphemeralApplications"); 7951 synchronized (mPackages) { 7952 List<InstantAppInfo> instantApps = mInstantAppRegistry 7953 .getInstantAppsLPr(userId); 7954 if (instantApps != null) { 7955 return new ParceledListSlice<>(instantApps); 7956 } 7957 } 7958 return null; 7959 } 7960 7961 @Override 7962 public boolean isInstantApp(String packageName, int userId) { 7963 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7964 true /* requireFullPermission */, false /* checkShell */, 7965 "isInstantApp"); 7966 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7967 return false; 7968 } 7969 7970 synchronized (mPackages) { 7971 int callingUid = Binder.getCallingUid(); 7972 if (Process.isIsolated(callingUid)) { 7973 callingUid = mIsolatedOwners.get(callingUid); 7974 } 7975 final PackageSetting ps = mSettings.mPackages.get(packageName); 7976 PackageParser.Package pkg = mPackages.get(packageName); 7977 final boolean returnAllowed = 7978 ps != null 7979 && (isCallerSameApp(packageName, callingUid) 7980 || canViewInstantApps(callingUid, userId) 7981 || mInstantAppRegistry.isInstantAccessGranted( 7982 userId, UserHandle.getAppId(callingUid), ps.appId)); 7983 if (returnAllowed) { 7984 return ps.getInstantApp(userId); 7985 } 7986 } 7987 return false; 7988 } 7989 7990 @Override 7991 public byte[] getInstantAppCookie(String packageName, int userId) { 7992 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7993 return null; 7994 } 7995 7996 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7997 true /* requireFullPermission */, false /* checkShell */, 7998 "getInstantAppCookie"); 7999 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8000 return null; 8001 } 8002 synchronized (mPackages) { 8003 return mInstantAppRegistry.getInstantAppCookieLPw( 8004 packageName, userId); 8005 } 8006 } 8007 8008 @Override 8009 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8010 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8011 return true; 8012 } 8013 8014 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8015 true /* requireFullPermission */, true /* checkShell */, 8016 "setInstantAppCookie"); 8017 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8018 return false; 8019 } 8020 synchronized (mPackages) { 8021 return mInstantAppRegistry.setInstantAppCookieLPw( 8022 packageName, cookie, userId); 8023 } 8024 } 8025 8026 @Override 8027 public Bitmap getInstantAppIcon(String packageName, int userId) { 8028 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8029 return null; 8030 } 8031 8032 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8033 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8034 "getInstantAppIcon"); 8035 } 8036 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8037 true /* requireFullPermission */, false /* checkShell */, 8038 "getInstantAppIcon"); 8039 8040 synchronized (mPackages) { 8041 return mInstantAppRegistry.getInstantAppIconLPw( 8042 packageName, userId); 8043 } 8044 } 8045 8046 private boolean isCallerSameApp(String packageName, int uid) { 8047 PackageParser.Package pkg = mPackages.get(packageName); 8048 return pkg != null 8049 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8050 } 8051 8052 @Override 8053 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8054 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8055 return ParceledListSlice.emptyList(); 8056 } 8057 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8058 } 8059 8060 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8061 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8062 8063 // reader 8064 synchronized (mPackages) { 8065 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8066 final int userId = UserHandle.getCallingUserId(); 8067 while (i.hasNext()) { 8068 final PackageParser.Package p = i.next(); 8069 if (p.applicationInfo == null) continue; 8070 8071 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8072 && !p.applicationInfo.isDirectBootAware(); 8073 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8074 && p.applicationInfo.isDirectBootAware(); 8075 8076 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8077 && (!mSafeMode || isSystemApp(p)) 8078 && (matchesUnaware || matchesAware)) { 8079 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8080 if (ps != null) { 8081 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8082 ps.readUserState(userId), userId); 8083 if (ai != null) { 8084 finalList.add(ai); 8085 } 8086 } 8087 } 8088 } 8089 } 8090 8091 return finalList; 8092 } 8093 8094 @Override 8095 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8096 return resolveContentProviderInternal(name, flags, userId); 8097 } 8098 8099 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8100 if (!sUserManager.exists(userId)) return null; 8101 flags = updateFlagsForComponent(flags, userId, name); 8102 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8103 // reader 8104 synchronized (mPackages) { 8105 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8106 PackageSetting ps = provider != null 8107 ? mSettings.mPackages.get(provider.owner.packageName) 8108 : null; 8109 if (ps != null) { 8110 final boolean isInstantApp = ps.getInstantApp(userId); 8111 // normal application; filter out instant application provider 8112 if (instantAppPkgName == null && isInstantApp) { 8113 return null; 8114 } 8115 // instant application; filter out other instant applications 8116 if (instantAppPkgName != null 8117 && isInstantApp 8118 && !provider.owner.packageName.equals(instantAppPkgName)) { 8119 return null; 8120 } 8121 // instant application; filter out non-exposed provider 8122 if (instantAppPkgName != null 8123 && !isInstantApp 8124 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8125 return null; 8126 } 8127 // provider not enabled 8128 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8129 return null; 8130 } 8131 return PackageParser.generateProviderInfo( 8132 provider, flags, ps.readUserState(userId), userId); 8133 } 8134 return null; 8135 } 8136 } 8137 8138 /** 8139 * @deprecated 8140 */ 8141 @Deprecated 8142 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8143 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8144 return; 8145 } 8146 // reader 8147 synchronized (mPackages) { 8148 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8149 .entrySet().iterator(); 8150 final int userId = UserHandle.getCallingUserId(); 8151 while (i.hasNext()) { 8152 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8153 PackageParser.Provider p = entry.getValue(); 8154 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8155 8156 if (ps != null && p.syncable 8157 && (!mSafeMode || (p.info.applicationInfo.flags 8158 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8159 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8160 ps.readUserState(userId), userId); 8161 if (info != null) { 8162 outNames.add(entry.getKey()); 8163 outInfo.add(info); 8164 } 8165 } 8166 } 8167 } 8168 } 8169 8170 @Override 8171 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8172 int uid, int flags, String metaDataKey) { 8173 final int callingUid = Binder.getCallingUid(); 8174 final int userId = processName != null ? UserHandle.getUserId(uid) 8175 : UserHandle.getCallingUserId(); 8176 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8177 flags = updateFlagsForComponent(flags, userId, processName); 8178 ArrayList<ProviderInfo> finalList = null; 8179 // reader 8180 synchronized (mPackages) { 8181 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8182 while (i.hasNext()) { 8183 final PackageParser.Provider p = i.next(); 8184 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8185 if (ps != null && p.info.authority != null 8186 && (processName == null 8187 || (p.info.processName.equals(processName) 8188 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8189 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8190 8191 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8192 // parameter. 8193 if (metaDataKey != null 8194 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8195 continue; 8196 } 8197 final ComponentName component = 8198 new ComponentName(p.info.packageName, p.info.name); 8199 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8200 continue; 8201 } 8202 if (finalList == null) { 8203 finalList = new ArrayList<ProviderInfo>(3); 8204 } 8205 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8206 ps.readUserState(userId), userId); 8207 if (info != null) { 8208 finalList.add(info); 8209 } 8210 } 8211 } 8212 } 8213 8214 if (finalList != null) { 8215 Collections.sort(finalList, mProviderInitOrderSorter); 8216 return new ParceledListSlice<ProviderInfo>(finalList); 8217 } 8218 8219 return ParceledListSlice.emptyList(); 8220 } 8221 8222 @Override 8223 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8224 // reader 8225 synchronized (mPackages) { 8226 final int callingUid = Binder.getCallingUid(); 8227 final int callingUserId = UserHandle.getUserId(callingUid); 8228 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8229 if (ps == null) return null; 8230 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8231 return null; 8232 } 8233 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8234 return PackageParser.generateInstrumentationInfo(i, flags); 8235 } 8236 } 8237 8238 @Override 8239 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8240 String targetPackage, int flags) { 8241 final int callingUid = Binder.getCallingUid(); 8242 final int callingUserId = UserHandle.getUserId(callingUid); 8243 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8244 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8245 return ParceledListSlice.emptyList(); 8246 } 8247 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8248 } 8249 8250 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8251 int flags) { 8252 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8253 8254 // reader 8255 synchronized (mPackages) { 8256 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8257 while (i.hasNext()) { 8258 final PackageParser.Instrumentation p = i.next(); 8259 if (targetPackage == null 8260 || targetPackage.equals(p.info.targetPackage)) { 8261 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8262 flags); 8263 if (ii != null) { 8264 finalList.add(ii); 8265 } 8266 } 8267 } 8268 } 8269 8270 return finalList; 8271 } 8272 8273 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8274 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8275 try { 8276 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8277 } finally { 8278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8279 } 8280 } 8281 8282 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8283 final File[] files = scanDir.listFiles(); 8284 if (ArrayUtils.isEmpty(files)) { 8285 Log.d(TAG, "No files in app dir " + scanDir); 8286 return; 8287 } 8288 8289 if (DEBUG_PACKAGE_SCANNING) { 8290 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8291 + " flags=0x" + Integer.toHexString(parseFlags)); 8292 } 8293 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8294 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8295 mParallelPackageParserCallback)) { 8296 // Submit files for parsing in parallel 8297 int fileCount = 0; 8298 for (File file : files) { 8299 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8300 && !PackageInstallerService.isStageName(file.getName()); 8301 if (!isPackage) { 8302 // Ignore entries which are not packages 8303 continue; 8304 } 8305 parallelPackageParser.submit(file, parseFlags); 8306 fileCount++; 8307 } 8308 8309 // Process results one by one 8310 for (; fileCount > 0; fileCount--) { 8311 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8312 Throwable throwable = parseResult.throwable; 8313 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8314 8315 if (throwable == null) { 8316 // TODO(toddke): move lower in the scan chain 8317 // Static shared libraries have synthetic package names 8318 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8319 renameStaticSharedLibraryPackage(parseResult.pkg); 8320 } 8321 try { 8322 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8323 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8324 currentTime, null); 8325 } 8326 } catch (PackageManagerException e) { 8327 errorCode = e.error; 8328 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8329 } 8330 } else if (throwable instanceof PackageParser.PackageParserException) { 8331 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8332 throwable; 8333 errorCode = e.error; 8334 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8335 } else { 8336 throw new IllegalStateException("Unexpected exception occurred while parsing " 8337 + parseResult.scanFile, throwable); 8338 } 8339 8340 // Delete invalid userdata apps 8341 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8342 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8343 logCriticalInfo(Log.WARN, 8344 "Deleting invalid package at " + parseResult.scanFile); 8345 removeCodePathLI(parseResult.scanFile); 8346 } 8347 } 8348 } 8349 } 8350 8351 public static void reportSettingsProblem(int priority, String msg) { 8352 logCriticalInfo(priority, msg); 8353 } 8354 8355 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8356 boolean forceCollect) throws PackageManagerException { 8357 // When upgrading from pre-N MR1, verify the package time stamp using the package 8358 // directory and not the APK file. 8359 final long lastModifiedTime = mIsPreNMR1Upgrade 8360 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8361 // Note that currently skipVerify skips verification on both base and splits for simplicity. 8362 final boolean skipVerify = forceCollect && canSkipFullPackageVerification(pkg); 8363 if (ps != null && !forceCollect 8364 && ps.codePathString.equals(pkg.codePath) 8365 && ps.timeStamp == lastModifiedTime 8366 && !isCompatSignatureUpdateNeeded(pkg) 8367 && !isRecoverSignatureUpdateNeeded(pkg)) { 8368 if (ps.signatures.mSigningDetails.signatures != null 8369 && ps.signatures.mSigningDetails.signatures.length != 0 8370 && ps.signatures.mSigningDetails.signatureSchemeVersion 8371 != SignatureSchemeVersion.UNKNOWN) { 8372 // Optimization: reuse the existing cached signing data 8373 // if the package appears to be unchanged. 8374 pkg.mSigningDetails = 8375 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8376 return; 8377 } 8378 8379 Slog.w(TAG, "PackageSetting for " + ps.name 8380 + " is missing signatures. Collecting certs again to recover them."); 8381 } else { 8382 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8383 (forceCollect ? " (forced)" : "")); 8384 } 8385 8386 try { 8387 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8388 PackageParser.collectCertificates(pkg, skipVerify); 8389 } catch (PackageParserException e) { 8390 throw PackageManagerException.from(e); 8391 } finally { 8392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8393 } 8394 } 8395 8396 /** 8397 * Traces a package scan. 8398 * @see #scanPackageLI(File, int, int, long, UserHandle) 8399 */ 8400 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8401 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8402 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8403 try { 8404 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8405 } finally { 8406 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8407 } 8408 } 8409 8410 /** 8411 * Scans a package and returns the newly parsed package. 8412 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8413 */ 8414 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8415 long currentTime, UserHandle user) throws PackageManagerException { 8416 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8417 PackageParser pp = new PackageParser(); 8418 pp.setSeparateProcesses(mSeparateProcesses); 8419 pp.setOnlyCoreApps(mOnlyCore); 8420 pp.setDisplayMetrics(mMetrics); 8421 pp.setCallback(mPackageParserCallback); 8422 8423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8424 final PackageParser.Package pkg; 8425 try { 8426 pkg = pp.parsePackage(scanFile, parseFlags); 8427 } catch (PackageParserException e) { 8428 throw PackageManagerException.from(e); 8429 } finally { 8430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8431 } 8432 8433 // Static shared libraries have synthetic package names 8434 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8435 renameStaticSharedLibraryPackage(pkg); 8436 } 8437 8438 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8439 } 8440 8441 /** 8442 * Scans a package and returns the newly parsed package. 8443 * @throws PackageManagerException on a parse error. 8444 */ 8445 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8446 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8447 @Nullable UserHandle user) 8448 throws PackageManagerException { 8449 // If the package has children and this is the first dive in the function 8450 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8451 // packages (parent and children) would be successfully scanned before the 8452 // actual scan since scanning mutates internal state and we want to atomically 8453 // install the package and its children. 8454 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8455 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8456 scanFlags |= SCAN_CHECK_ONLY; 8457 } 8458 } else { 8459 scanFlags &= ~SCAN_CHECK_ONLY; 8460 } 8461 8462 // Scan the parent 8463 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8464 scanFlags, currentTime, user); 8465 8466 // Scan the children 8467 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8468 for (int i = 0; i < childCount; i++) { 8469 PackageParser.Package childPackage = pkg.childPackages.get(i); 8470 addForInitLI(childPackage, parseFlags, scanFlags, 8471 currentTime, user); 8472 } 8473 8474 8475 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8476 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8477 } 8478 8479 return scannedPkg; 8480 } 8481 8482 /** 8483 * Returns if full apk verification can be skipped for the whole package, including the splits. 8484 */ 8485 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8486 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8487 return false; 8488 } 8489 // TODO: Allow base and splits to be verified individually. 8490 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8491 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8492 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8493 return false; 8494 } 8495 } 8496 } 8497 return true; 8498 } 8499 8500 /** 8501 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8502 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8503 * match one in a trusted source, and should be done separately. 8504 */ 8505 private boolean canSkipFullApkVerification(String apkPath) { 8506 byte[] rootHashObserved = null; 8507 try { 8508 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8509 if (rootHashObserved == null) { 8510 return false; // APK does not contain Merkle tree root hash. 8511 } 8512 synchronized (mInstallLock) { 8513 // Returns whether the observed root hash matches what kernel has. 8514 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8515 return true; 8516 } 8517 } catch (InstallerException | IOException | DigestException | 8518 NoSuchAlgorithmException e) { 8519 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8520 } 8521 return false; 8522 } 8523 8524 // Temporary to catch potential issues with refactoring 8525 private static boolean REFACTOR_DEBUG = true; 8526 /** 8527 * Adds a new package to the internal data structures during platform initialization. 8528 * <p>After adding, the package is known to the system and available for querying. 8529 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8530 * etc...], additional checks are performed. Basic verification [such as ensuring 8531 * matching signatures, checking version codes, etc...] occurs if the package is 8532 * identical to a previously known package. If the package fails a signature check, 8533 * the version installed on /data will be removed. If the version of the new package 8534 * is less than or equal than the version on /data, it will be ignored. 8535 * <p>Regardless of the package location, the results are applied to the internal 8536 * structures and the package is made available to the rest of the system. 8537 * <p>NOTE: The return value should be removed. It's the passed in package object. 8538 */ 8539 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8540 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8541 @Nullable UserHandle user) 8542 throws PackageManagerException { 8543 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8544 final String renamedPkgName; 8545 final PackageSetting disabledPkgSetting; 8546 final boolean isSystemPkgUpdated; 8547 final boolean pkgAlreadyExists; 8548 PackageSetting pkgSetting; 8549 8550 // NOTE: installPackageLI() has the same code to setup the package's 8551 // application info. This probably should be done lower in the call 8552 // stack [such as scanPackageOnly()]. However, we verify the application 8553 // info prior to that [in scanPackageNew()] and thus have to setup 8554 // the application info early. 8555 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8556 pkg.setApplicationInfoCodePath(pkg.codePath); 8557 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8558 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8559 pkg.setApplicationInfoResourcePath(pkg.codePath); 8560 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8561 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8562 8563 synchronized (mPackages) { 8564 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8565 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8566if (REFACTOR_DEBUG) { 8567Slog.e("TODD", 8568 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8569} 8570 if (realPkgName != null) { 8571 ensurePackageRenamed(pkg, renamedPkgName); 8572 } 8573 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8574 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8575 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8576 pkgAlreadyExists = pkgSetting != null; 8577 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8578 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8579 isSystemPkgUpdated = disabledPkgSetting != null; 8580 8581 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8582 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8583 } 8584if (REFACTOR_DEBUG) { 8585Slog.e("TODD", 8586 "SSP? " + scanSystemPartition 8587 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8588 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8589} 8590 8591 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8592 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8593 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8594 : null; 8595 if (DEBUG_PACKAGE_SCANNING 8596 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8597 && sharedUserSetting != null) { 8598 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8599 + " (uid=" + sharedUserSetting.userId + "):" 8600 + " packages=" + sharedUserSetting.packages); 8601if (REFACTOR_DEBUG) { 8602Slog.e("TODD", 8603 "Shared UserID " + pkg.mSharedUserId 8604 + " (uid=" + sharedUserSetting.userId + "):" 8605 + " packages=" + sharedUserSetting.packages); 8606} 8607 } 8608 8609 if (scanSystemPartition) { 8610 // Potentially prune child packages. If the application on the /system 8611 // partition has been updated via OTA, but, is still disabled by a 8612 // version on /data, cycle through all of its children packages and 8613 // remove children that are no longer defined. 8614 if (isSystemPkgUpdated) { 8615if (REFACTOR_DEBUG) { 8616Slog.e("TODD", 8617 "Disable child packages"); 8618} 8619 final int scannedChildCount = (pkg.childPackages != null) 8620 ? pkg.childPackages.size() : 0; 8621 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8622 ? disabledPkgSetting.childPackageNames.size() : 0; 8623 for (int i = 0; i < disabledChildCount; i++) { 8624 String disabledChildPackageName = 8625 disabledPkgSetting.childPackageNames.get(i); 8626 boolean disabledPackageAvailable = false; 8627 for (int j = 0; j < scannedChildCount; j++) { 8628 PackageParser.Package childPkg = pkg.childPackages.get(j); 8629 if (childPkg.packageName.equals(disabledChildPackageName)) { 8630if (REFACTOR_DEBUG) { 8631Slog.e("TODD", 8632 "Ignore " + disabledChildPackageName); 8633} 8634 disabledPackageAvailable = true; 8635 break; 8636 } 8637 } 8638 if (!disabledPackageAvailable) { 8639if (REFACTOR_DEBUG) { 8640Slog.e("TODD", 8641 "Disable " + disabledChildPackageName); 8642} 8643 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8644 } 8645 } 8646 // we're updating the disabled package, so, scan it as the package setting 8647 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8648 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8649 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8650 (pkg == mPlatformPackage), user); 8651if (REFACTOR_DEBUG) { 8652Slog.e("TODD", 8653 "Scan disabled system package"); 8654Slog.e("TODD", 8655 "Pre: " + request.pkgSetting.dumpState_temp()); 8656} 8657final ScanResult result = 8658 scanPackageOnlyLI(request, mFactoryTest, -1L); 8659if (REFACTOR_DEBUG) { 8660Slog.e("TODD", 8661 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8662} 8663 } 8664 } 8665 } 8666 8667 final boolean newPkgChangedPaths = 8668 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8669if (REFACTOR_DEBUG) { 8670Slog.e("TODD", 8671 "paths changed? " + newPkgChangedPaths 8672 + "; old: " + pkg.codePath 8673 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8674} 8675 final boolean newPkgVersionGreater = 8676 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8677if (REFACTOR_DEBUG) { 8678Slog.e("TODD", 8679 "version greater? " + newPkgVersionGreater 8680 + "; old: " + pkg.getLongVersionCode() 8681 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8682} 8683 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8684 && newPkgChangedPaths && newPkgVersionGreater; 8685if (REFACTOR_DEBUG) { 8686 Slog.e("TODD", 8687 "system better? " + isSystemPkgBetter); 8688} 8689 if (isSystemPkgBetter) { 8690 // The version of the application on /system is greater than the version on 8691 // /data. Switch back to the application on /system. 8692 // It's safe to assume the application on /system will correctly scan. If not, 8693 // there won't be a working copy of the application. 8694 synchronized (mPackages) { 8695 // just remove the loaded entries from package lists 8696 mPackages.remove(pkgSetting.name); 8697 } 8698 8699 logCriticalInfo(Log.WARN, 8700 "System package updated;" 8701 + " name: " + pkgSetting.name 8702 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8703 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8704if (REFACTOR_DEBUG) { 8705Slog.e("TODD", 8706 "System package changed;" 8707 + " name: " + pkgSetting.name 8708 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8709 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8710} 8711 8712 final InstallArgs args = createInstallArgsForExisting( 8713 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8714 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8715 args.cleanUpResourcesLI(); 8716 synchronized (mPackages) { 8717 mSettings.enableSystemPackageLPw(pkgSetting.name); 8718 } 8719 } 8720 8721 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8722if (REFACTOR_DEBUG) { 8723Slog.e("TODD", 8724 "THROW exception; system pkg version not good enough"); 8725} 8726 // The version of the application on the /system partition is less than or 8727 // equal to the version on the /data partition. Throw an exception and use 8728 // the application already installed on the /data partition. 8729 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8730 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8731 + " better than this " + pkg.getLongVersionCode()); 8732 } 8733 8734 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8735 // force re-collecting certificate. Full apk verification will happen unless apk verity is 8736 // set up for the file. In that case, only small part of the apk is verified upfront. 8737 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8738 disabledPkgSetting); 8739 collectCertificatesLI(pkgSetting, pkg, forceCollect); 8740 8741 boolean shouldHideSystemApp = false; 8742 // A new application appeared on /system, but, we already have a copy of 8743 // the application installed on /data. 8744 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8745 && !pkgSetting.isSystem()) { 8746 // if the signatures don't match, wipe the installed application and its data 8747 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8748 pkg.mSigningDetails.signatures) 8749 != PackageManager.SIGNATURE_MATCH) { 8750 logCriticalInfo(Log.WARN, 8751 "System package signature mismatch;" 8752 + " name: " + pkgSetting.name); 8753if (REFACTOR_DEBUG) { 8754Slog.e("TODD", 8755 "System package signature mismatch;" 8756 + " name: " + pkgSetting.name); 8757} 8758 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8759 "scanPackageInternalLI")) { 8760 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8761 } 8762 pkgSetting = null; 8763 } else if (newPkgVersionGreater) { 8764 // The application on /system is newer than the application on /data. 8765 // Simply remove the application on /data [keeping application data] 8766 // and replace it with the version on /system. 8767 logCriticalInfo(Log.WARN, 8768 "System package enabled;" 8769 + " name: " + pkgSetting.name 8770 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8771 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8772if (REFACTOR_DEBUG) { 8773Slog.e("TODD", 8774 "System package enabled;" 8775 + " name: " + pkgSetting.name 8776 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8777 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8778} 8779 InstallArgs args = createInstallArgsForExisting( 8780 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8781 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8782 synchronized (mInstallLock) { 8783 args.cleanUpResourcesLI(); 8784 } 8785 } else { 8786 // The application on /system is older than the application on /data. Hide 8787 // the application on /system and the version on /data will be scanned later 8788 // and re-added like an update. 8789 shouldHideSystemApp = true; 8790 logCriticalInfo(Log.INFO, 8791 "System package disabled;" 8792 + " name: " + pkgSetting.name 8793 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8794 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8795if (REFACTOR_DEBUG) { 8796Slog.e("TODD", 8797 "System package disabled;" 8798 + " name: " + pkgSetting.name 8799 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8800 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8801} 8802 } 8803 } 8804 8805if (REFACTOR_DEBUG) { 8806Slog.e("TODD", 8807 "Scan package"); 8808Slog.e("TODD", 8809 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8810} 8811 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8812 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8813if (REFACTOR_DEBUG) { 8814pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8815Slog.e("TODD", 8816 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8817} 8818 8819 if (shouldHideSystemApp) { 8820if (REFACTOR_DEBUG) { 8821Slog.e("TODD", 8822 "Disable package: " + pkg.packageName); 8823} 8824 synchronized (mPackages) { 8825 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8826 } 8827 } 8828 return scannedPkg; 8829 } 8830 8831 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8832 // Derive the new package synthetic package name 8833 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8834 + pkg.staticSharedLibVersion); 8835 } 8836 8837 private static String fixProcessName(String defProcessName, 8838 String processName) { 8839 if (processName == null) { 8840 return defProcessName; 8841 } 8842 return processName; 8843 } 8844 8845 /** 8846 * Enforces that only the system UID or root's UID can call a method exposed 8847 * via Binder. 8848 * 8849 * @param message used as message if SecurityException is thrown 8850 * @throws SecurityException if the caller is not system or root 8851 */ 8852 private static final void enforceSystemOrRoot(String message) { 8853 final int uid = Binder.getCallingUid(); 8854 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8855 throw new SecurityException(message); 8856 } 8857 } 8858 8859 @Override 8860 public void performFstrimIfNeeded() { 8861 enforceSystemOrRoot("Only the system can request fstrim"); 8862 8863 // Before everything else, see whether we need to fstrim. 8864 try { 8865 IStorageManager sm = PackageHelper.getStorageManager(); 8866 if (sm != null) { 8867 boolean doTrim = false; 8868 final long interval = android.provider.Settings.Global.getLong( 8869 mContext.getContentResolver(), 8870 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8871 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8872 if (interval > 0) { 8873 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8874 if (timeSinceLast > interval) { 8875 doTrim = true; 8876 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8877 + "; running immediately"); 8878 } 8879 } 8880 if (doTrim) { 8881 final boolean dexOptDialogShown; 8882 synchronized (mPackages) { 8883 dexOptDialogShown = mDexOptDialogShown; 8884 } 8885 if (!isFirstBoot() && dexOptDialogShown) { 8886 try { 8887 ActivityManager.getService().showBootMessage( 8888 mContext.getResources().getString( 8889 R.string.android_upgrading_fstrim), true); 8890 } catch (RemoteException e) { 8891 } 8892 } 8893 sm.runMaintenance(); 8894 } 8895 } else { 8896 Slog.e(TAG, "storageManager service unavailable!"); 8897 } 8898 } catch (RemoteException e) { 8899 // Can't happen; StorageManagerService is local 8900 } 8901 } 8902 8903 @Override 8904 public void updatePackagesIfNeeded() { 8905 enforceSystemOrRoot("Only the system can request package update"); 8906 8907 // We need to re-extract after an OTA. 8908 boolean causeUpgrade = isUpgrade(); 8909 8910 // First boot or factory reset. 8911 // Note: we also handle devices that are upgrading to N right now as if it is their 8912 // first boot, as they do not have profile data. 8913 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8914 8915 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8916 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8917 8918 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8919 return; 8920 } 8921 8922 List<PackageParser.Package> pkgs; 8923 synchronized (mPackages) { 8924 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8925 } 8926 8927 final long startTime = System.nanoTime(); 8928 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8929 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8930 false /* bootComplete */); 8931 8932 final int elapsedTimeSeconds = 8933 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8934 8935 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8936 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8937 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8938 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8939 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8940 } 8941 8942 /* 8943 * Return the prebuilt profile path given a package base code path. 8944 */ 8945 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8946 return pkg.baseCodePath + ".prof"; 8947 } 8948 8949 /** 8950 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8951 * containing statistics about the invocation. The array consists of three elements, 8952 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8953 * and {@code numberOfPackagesFailed}. 8954 */ 8955 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8956 final String compilerFilter, boolean bootComplete) { 8957 8958 int numberOfPackagesVisited = 0; 8959 int numberOfPackagesOptimized = 0; 8960 int numberOfPackagesSkipped = 0; 8961 int numberOfPackagesFailed = 0; 8962 final int numberOfPackagesToDexopt = pkgs.size(); 8963 8964 for (PackageParser.Package pkg : pkgs) { 8965 numberOfPackagesVisited++; 8966 8967 boolean useProfileForDexopt = false; 8968 8969 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8970 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8971 // that are already compiled. 8972 File profileFile = new File(getPrebuildProfilePath(pkg)); 8973 // Copy profile if it exists. 8974 if (profileFile.exists()) { 8975 try { 8976 // We could also do this lazily before calling dexopt in 8977 // PackageDexOptimizer to prevent this happening on first boot. The issue 8978 // is that we don't have a good way to say "do this only once". 8979 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8980 pkg.applicationInfo.uid, pkg.packageName, 8981 ArtManager.getProfileName(null))) { 8982 Log.e(TAG, "Installer failed to copy system profile!"); 8983 } else { 8984 // Disabled as this causes speed-profile compilation during first boot 8985 // even if things are already compiled. 8986 // useProfileForDexopt = true; 8987 } 8988 } catch (Exception e) { 8989 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8990 e); 8991 } 8992 } else { 8993 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8994 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8995 // minimize the number off apps being speed-profile compiled during first boot. 8996 // The other paths will not change the filter. 8997 if (disabledPs != null && disabledPs.pkg.isStub) { 8998 // The package is the stub one, remove the stub suffix to get the normal 8999 // package and APK names. 9000 String systemProfilePath = 9001 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9002 profileFile = new File(systemProfilePath); 9003 // If we have a profile for a compressed APK, copy it to the reference 9004 // location. 9005 // Note that copying the profile here will cause it to override the 9006 // reference profile every OTA even though the existing reference profile 9007 // may have more data. We can't copy during decompression since the 9008 // directories are not set up at that point. 9009 if (profileFile.exists()) { 9010 try { 9011 // We could also do this lazily before calling dexopt in 9012 // PackageDexOptimizer to prevent this happening on first boot. The 9013 // issue is that we don't have a good way to say "do this only 9014 // once". 9015 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9016 pkg.applicationInfo.uid, pkg.packageName, 9017 ArtManager.getProfileName(null))) { 9018 Log.e(TAG, "Failed to copy system profile for stub package!"); 9019 } else { 9020 useProfileForDexopt = true; 9021 } 9022 } catch (Exception e) { 9023 Log.e(TAG, "Failed to copy profile " + 9024 profileFile.getAbsolutePath() + " ", e); 9025 } 9026 } 9027 } 9028 } 9029 } 9030 9031 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9032 if (DEBUG_DEXOPT) { 9033 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9034 } 9035 numberOfPackagesSkipped++; 9036 continue; 9037 } 9038 9039 if (DEBUG_DEXOPT) { 9040 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9041 numberOfPackagesToDexopt + ": " + pkg.packageName); 9042 } 9043 9044 if (showDialog) { 9045 try { 9046 ActivityManager.getService().showBootMessage( 9047 mContext.getResources().getString(R.string.android_upgrading_apk, 9048 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9049 } catch (RemoteException e) { 9050 } 9051 synchronized (mPackages) { 9052 mDexOptDialogShown = true; 9053 } 9054 } 9055 9056 String pkgCompilerFilter = compilerFilter; 9057 if (useProfileForDexopt) { 9058 // Use background dexopt mode to try and use the profile. Note that this does not 9059 // guarantee usage of the profile. 9060 pkgCompilerFilter = 9061 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9062 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9063 } 9064 9065 // checkProfiles is false to avoid merging profiles during boot which 9066 // might interfere with background compilation (b/28612421). 9067 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9068 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9069 // trade-off worth doing to save boot time work. 9070 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9071 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9072 pkg.packageName, 9073 pkgCompilerFilter, 9074 dexoptFlags)); 9075 9076 switch (primaryDexOptStaus) { 9077 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9078 numberOfPackagesOptimized++; 9079 break; 9080 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9081 numberOfPackagesSkipped++; 9082 break; 9083 case PackageDexOptimizer.DEX_OPT_FAILED: 9084 numberOfPackagesFailed++; 9085 break; 9086 default: 9087 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9088 break; 9089 } 9090 } 9091 9092 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9093 numberOfPackagesFailed }; 9094 } 9095 9096 @Override 9097 public void notifyPackageUse(String packageName, int reason) { 9098 synchronized (mPackages) { 9099 final int callingUid = Binder.getCallingUid(); 9100 final int callingUserId = UserHandle.getUserId(callingUid); 9101 if (getInstantAppPackageName(callingUid) != null) { 9102 if (!isCallerSameApp(packageName, callingUid)) { 9103 return; 9104 } 9105 } else { 9106 if (isInstantApp(packageName, callingUserId)) { 9107 return; 9108 } 9109 } 9110 notifyPackageUseLocked(packageName, reason); 9111 } 9112 } 9113 9114 private void notifyPackageUseLocked(String packageName, int reason) { 9115 final PackageParser.Package p = mPackages.get(packageName); 9116 if (p == null) { 9117 return; 9118 } 9119 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9120 } 9121 9122 @Override 9123 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9124 List<String> classPaths, String loaderIsa) { 9125 int userId = UserHandle.getCallingUserId(); 9126 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9127 if (ai == null) { 9128 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9129 + loadingPackageName + ", user=" + userId); 9130 return; 9131 } 9132 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9133 } 9134 9135 @Override 9136 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9137 IDexModuleRegisterCallback callback) { 9138 int userId = UserHandle.getCallingUserId(); 9139 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9140 DexManager.RegisterDexModuleResult result; 9141 if (ai == null) { 9142 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9143 " calling user. package=" + packageName + ", user=" + userId); 9144 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9145 } else { 9146 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9147 } 9148 9149 if (callback != null) { 9150 mHandler.post(() -> { 9151 try { 9152 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9153 } catch (RemoteException e) { 9154 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9155 } 9156 }); 9157 } 9158 } 9159 9160 /** 9161 * Ask the package manager to perform a dex-opt with the given compiler filter. 9162 * 9163 * Note: exposed only for the shell command to allow moving packages explicitly to a 9164 * definite state. 9165 */ 9166 @Override 9167 public boolean performDexOptMode(String packageName, 9168 boolean checkProfiles, String targetCompilerFilter, boolean force, 9169 boolean bootComplete, String splitName) { 9170 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9171 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9172 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9173 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9174 splitName, flags)); 9175 } 9176 9177 /** 9178 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9179 * secondary dex files belonging to the given package. 9180 * 9181 * Note: exposed only for the shell command to allow moving packages explicitly to a 9182 * definite state. 9183 */ 9184 @Override 9185 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9186 boolean force) { 9187 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9188 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9189 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9190 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9191 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9192 } 9193 9194 /*package*/ boolean performDexOpt(DexoptOptions options) { 9195 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9196 return false; 9197 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9198 return false; 9199 } 9200 9201 if (options.isDexoptOnlySecondaryDex()) { 9202 return mDexManager.dexoptSecondaryDex(options); 9203 } else { 9204 int dexoptStatus = performDexOptWithStatus(options); 9205 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9206 } 9207 } 9208 9209 /** 9210 * Perform dexopt on the given package and return one of following result: 9211 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9212 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9213 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9214 */ 9215 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9216 return performDexOptTraced(options); 9217 } 9218 9219 private int performDexOptTraced(DexoptOptions options) { 9220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9221 try { 9222 return performDexOptInternal(options); 9223 } finally { 9224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9225 } 9226 } 9227 9228 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9229 // if the package can now be considered up to date for the given filter. 9230 private int performDexOptInternal(DexoptOptions options) { 9231 PackageParser.Package p; 9232 synchronized (mPackages) { 9233 p = mPackages.get(options.getPackageName()); 9234 if (p == null) { 9235 // Package could not be found. Report failure. 9236 return PackageDexOptimizer.DEX_OPT_FAILED; 9237 } 9238 mPackageUsage.maybeWriteAsync(mPackages); 9239 mCompilerStats.maybeWriteAsync(); 9240 } 9241 long callingId = Binder.clearCallingIdentity(); 9242 try { 9243 synchronized (mInstallLock) { 9244 return performDexOptInternalWithDependenciesLI(p, options); 9245 } 9246 } finally { 9247 Binder.restoreCallingIdentity(callingId); 9248 } 9249 } 9250 9251 public ArraySet<String> getOptimizablePackages() { 9252 ArraySet<String> pkgs = new ArraySet<String>(); 9253 synchronized (mPackages) { 9254 for (PackageParser.Package p : mPackages.values()) { 9255 if (PackageDexOptimizer.canOptimizePackage(p)) { 9256 pkgs.add(p.packageName); 9257 } 9258 } 9259 } 9260 return pkgs; 9261 } 9262 9263 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9264 DexoptOptions options) { 9265 // Select the dex optimizer based on the force parameter. 9266 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9267 // allocate an object here. 9268 PackageDexOptimizer pdo = options.isForce() 9269 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9270 : mPackageDexOptimizer; 9271 9272 // Dexopt all dependencies first. Note: we ignore the return value and march on 9273 // on errors. 9274 // Note that we are going to call performDexOpt on those libraries as many times as 9275 // they are referenced in packages. When we do a batch of performDexOpt (for example 9276 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9277 // and the first package that uses the library will dexopt it. The 9278 // others will see that the compiled code for the library is up to date. 9279 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9280 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9281 if (!deps.isEmpty()) { 9282 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9283 options.getCompilerFilter(), options.getSplitName(), 9284 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9285 for (PackageParser.Package depPackage : deps) { 9286 // TODO: Analyze and investigate if we (should) profile libraries. 9287 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9288 getOrCreateCompilerPackageStats(depPackage), 9289 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9290 } 9291 } 9292 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9293 getOrCreateCompilerPackageStats(p), 9294 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9295 } 9296 9297 /** 9298 * Reconcile the information we have about the secondary dex files belonging to 9299 * {@code packagName} and the actual dex files. For all dex files that were 9300 * deleted, update the internal records and delete the generated oat files. 9301 */ 9302 @Override 9303 public void reconcileSecondaryDexFiles(String packageName) { 9304 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9305 return; 9306 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9307 return; 9308 } 9309 mDexManager.reconcileSecondaryDexFiles(packageName); 9310 } 9311 9312 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9313 // a reference there. 9314 /*package*/ DexManager getDexManager() { 9315 return mDexManager; 9316 } 9317 9318 /** 9319 * Execute the background dexopt job immediately. 9320 */ 9321 @Override 9322 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9323 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9324 return false; 9325 } 9326 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9327 } 9328 9329 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9330 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9331 || p.usesStaticLibraries != null) { 9332 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9333 Set<String> collectedNames = new HashSet<>(); 9334 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9335 9336 retValue.remove(p); 9337 9338 return retValue; 9339 } else { 9340 return Collections.emptyList(); 9341 } 9342 } 9343 9344 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9345 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9346 if (!collectedNames.contains(p.packageName)) { 9347 collectedNames.add(p.packageName); 9348 collected.add(p); 9349 9350 if (p.usesLibraries != null) { 9351 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9352 null, collected, collectedNames); 9353 } 9354 if (p.usesOptionalLibraries != null) { 9355 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9356 null, collected, collectedNames); 9357 } 9358 if (p.usesStaticLibraries != null) { 9359 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9360 p.usesStaticLibrariesVersions, collected, collectedNames); 9361 } 9362 } 9363 } 9364 9365 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9366 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9367 final int libNameCount = libs.size(); 9368 for (int i = 0; i < libNameCount; i++) { 9369 String libName = libs.get(i); 9370 long version = (versions != null && versions.length == libNameCount) 9371 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9372 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9373 if (libPkg != null) { 9374 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9375 } 9376 } 9377 } 9378 9379 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9380 synchronized (mPackages) { 9381 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9382 if (libEntry != null) { 9383 return mPackages.get(libEntry.apk); 9384 } 9385 return null; 9386 } 9387 } 9388 9389 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9390 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9391 if (versionedLib == null) { 9392 return null; 9393 } 9394 return versionedLib.get(version); 9395 } 9396 9397 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9398 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9399 pkg.staticSharedLibName); 9400 if (versionedLib == null) { 9401 return null; 9402 } 9403 long previousLibVersion = -1; 9404 final int versionCount = versionedLib.size(); 9405 for (int i = 0; i < versionCount; i++) { 9406 final long libVersion = versionedLib.keyAt(i); 9407 if (libVersion < pkg.staticSharedLibVersion) { 9408 previousLibVersion = Math.max(previousLibVersion, libVersion); 9409 } 9410 } 9411 if (previousLibVersion >= 0) { 9412 return versionedLib.get(previousLibVersion); 9413 } 9414 return null; 9415 } 9416 9417 public void shutdown() { 9418 mPackageUsage.writeNow(mPackages); 9419 mCompilerStats.writeNow(); 9420 mDexManager.writePackageDexUsageNow(); 9421 } 9422 9423 @Override 9424 public void dumpProfiles(String packageName) { 9425 PackageParser.Package pkg; 9426 synchronized (mPackages) { 9427 pkg = mPackages.get(packageName); 9428 if (pkg == null) { 9429 throw new IllegalArgumentException("Unknown package: " + packageName); 9430 } 9431 } 9432 /* Only the shell, root, or the app user should be able to dump profiles. */ 9433 int callingUid = Binder.getCallingUid(); 9434 if (callingUid != Process.SHELL_UID && 9435 callingUid != Process.ROOT_UID && 9436 callingUid != pkg.applicationInfo.uid) { 9437 throw new SecurityException("dumpProfiles"); 9438 } 9439 9440 synchronized (mInstallLock) { 9441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9442 mArtManagerService.dumpProfiles(pkg); 9443 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9444 } 9445 } 9446 9447 @Override 9448 public void forceDexOpt(String packageName) { 9449 enforceSystemOrRoot("forceDexOpt"); 9450 9451 PackageParser.Package pkg; 9452 synchronized (mPackages) { 9453 pkg = mPackages.get(packageName); 9454 if (pkg == null) { 9455 throw new IllegalArgumentException("Unknown package: " + packageName); 9456 } 9457 } 9458 9459 synchronized (mInstallLock) { 9460 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9461 9462 // Whoever is calling forceDexOpt wants a compiled package. 9463 // Don't use profiles since that may cause compilation to be skipped. 9464 final int res = performDexOptInternalWithDependenciesLI( 9465 pkg, 9466 new DexoptOptions(packageName, 9467 getDefaultCompilerFilter(), 9468 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9469 9470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9471 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9472 throw new IllegalStateException("Failed to dexopt: " + res); 9473 } 9474 } 9475 } 9476 9477 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9478 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9479 Slog.w(TAG, "Unable to update from " + oldPkg.name 9480 + " to " + newPkg.packageName 9481 + ": old package not in system partition"); 9482 return false; 9483 } else if (mPackages.get(oldPkg.name) != null) { 9484 Slog.w(TAG, "Unable to update from " + oldPkg.name 9485 + " to " + newPkg.packageName 9486 + ": old package still exists"); 9487 return false; 9488 } 9489 return true; 9490 } 9491 9492 void removeCodePathLI(File codePath) { 9493 if (codePath.isDirectory()) { 9494 try { 9495 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9496 } catch (InstallerException e) { 9497 Slog.w(TAG, "Failed to remove code path", e); 9498 } 9499 } else { 9500 codePath.delete(); 9501 } 9502 } 9503 9504 private int[] resolveUserIds(int userId) { 9505 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9506 } 9507 9508 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9509 if (pkg == null) { 9510 Slog.wtf(TAG, "Package was null!", new Throwable()); 9511 return; 9512 } 9513 clearAppDataLeafLIF(pkg, userId, flags); 9514 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9515 for (int i = 0; i < childCount; i++) { 9516 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9517 } 9518 9519 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9520 } 9521 9522 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9523 final PackageSetting ps; 9524 synchronized (mPackages) { 9525 ps = mSettings.mPackages.get(pkg.packageName); 9526 } 9527 for (int realUserId : resolveUserIds(userId)) { 9528 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9529 try { 9530 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9531 ceDataInode); 9532 } catch (InstallerException e) { 9533 Slog.w(TAG, String.valueOf(e)); 9534 } 9535 } 9536 } 9537 9538 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9539 if (pkg == null) { 9540 Slog.wtf(TAG, "Package was null!", new Throwable()); 9541 return; 9542 } 9543 destroyAppDataLeafLIF(pkg, userId, flags); 9544 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9545 for (int i = 0; i < childCount; i++) { 9546 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9547 } 9548 } 9549 9550 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9551 final PackageSetting ps; 9552 synchronized (mPackages) { 9553 ps = mSettings.mPackages.get(pkg.packageName); 9554 } 9555 for (int realUserId : resolveUserIds(userId)) { 9556 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9557 try { 9558 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9559 ceDataInode); 9560 } catch (InstallerException e) { 9561 Slog.w(TAG, String.valueOf(e)); 9562 } 9563 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9564 } 9565 } 9566 9567 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9568 if (pkg == null) { 9569 Slog.wtf(TAG, "Package was null!", new Throwable()); 9570 return; 9571 } 9572 destroyAppProfilesLeafLIF(pkg); 9573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9574 for (int i = 0; i < childCount; i++) { 9575 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9576 } 9577 } 9578 9579 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9580 try { 9581 mInstaller.destroyAppProfiles(pkg.packageName); 9582 } catch (InstallerException e) { 9583 Slog.w(TAG, String.valueOf(e)); 9584 } 9585 } 9586 9587 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9588 if (pkg == null) { 9589 Slog.wtf(TAG, "Package was null!", new Throwable()); 9590 return; 9591 } 9592 mArtManagerService.clearAppProfiles(pkg); 9593 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9594 for (int i = 0; i < childCount; i++) { 9595 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9596 } 9597 } 9598 9599 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9600 long lastUpdateTime) { 9601 // Set parent install/update time 9602 PackageSetting ps = (PackageSetting) pkg.mExtras; 9603 if (ps != null) { 9604 ps.firstInstallTime = firstInstallTime; 9605 ps.lastUpdateTime = lastUpdateTime; 9606 } 9607 // Set children install/update time 9608 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9609 for (int i = 0; i < childCount; i++) { 9610 PackageParser.Package childPkg = pkg.childPackages.get(i); 9611 ps = (PackageSetting) childPkg.mExtras; 9612 if (ps != null) { 9613 ps.firstInstallTime = firstInstallTime; 9614 ps.lastUpdateTime = lastUpdateTime; 9615 } 9616 } 9617 } 9618 9619 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9620 SharedLibraryEntry file, 9621 PackageParser.Package changingLib) { 9622 if (file.path != null) { 9623 usesLibraryFiles.add(file.path); 9624 return; 9625 } 9626 PackageParser.Package p = mPackages.get(file.apk); 9627 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9628 // If we are doing this while in the middle of updating a library apk, 9629 // then we need to make sure to use that new apk for determining the 9630 // dependencies here. (We haven't yet finished committing the new apk 9631 // to the package manager state.) 9632 if (p == null || p.packageName.equals(changingLib.packageName)) { 9633 p = changingLib; 9634 } 9635 } 9636 if (p != null) { 9637 usesLibraryFiles.addAll(p.getAllCodePaths()); 9638 if (p.usesLibraryFiles != null) { 9639 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9640 } 9641 } 9642 } 9643 9644 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9645 PackageParser.Package changingLib) throws PackageManagerException { 9646 if (pkg == null) { 9647 return; 9648 } 9649 // The collection used here must maintain the order of addition (so 9650 // that libraries are searched in the correct order) and must have no 9651 // duplicates. 9652 Set<String> usesLibraryFiles = null; 9653 if (pkg.usesLibraries != null) { 9654 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9655 null, null, pkg.packageName, changingLib, true, 9656 pkg.applicationInfo.targetSdkVersion, null); 9657 } 9658 if (pkg.usesStaticLibraries != null) { 9659 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9660 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9661 pkg.packageName, changingLib, true, 9662 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9663 } 9664 if (pkg.usesOptionalLibraries != null) { 9665 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9666 null, null, pkg.packageName, changingLib, false, 9667 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9668 } 9669 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9670 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9671 } else { 9672 pkg.usesLibraryFiles = null; 9673 } 9674 } 9675 9676 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9677 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9678 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9679 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9680 throws PackageManagerException { 9681 final int libCount = requestedLibraries.size(); 9682 for (int i = 0; i < libCount; i++) { 9683 final String libName = requestedLibraries.get(i); 9684 final long libVersion = requiredVersions != null ? requiredVersions[i] 9685 : SharedLibraryInfo.VERSION_UNDEFINED; 9686 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9687 if (libEntry == null) { 9688 if (required) { 9689 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9690 "Package " + packageName + " requires unavailable shared library " 9691 + libName + "; failing!"); 9692 } else if (DEBUG_SHARED_LIBRARIES) { 9693 Slog.i(TAG, "Package " + packageName 9694 + " desires unavailable shared library " 9695 + libName + "; ignoring!"); 9696 } 9697 } else { 9698 if (requiredVersions != null && requiredCertDigests != null) { 9699 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9700 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9701 "Package " + packageName + " requires unavailable static shared" 9702 + " library " + libName + " version " 9703 + libEntry.info.getLongVersion() + "; failing!"); 9704 } 9705 9706 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9707 if (libPkg == null) { 9708 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9709 "Package " + packageName + " requires unavailable static shared" 9710 + " library; failing!"); 9711 } 9712 9713 final String[] expectedCertDigests = requiredCertDigests[i]; 9714 // For apps targeting O MR1 we require explicit enumeration of all certs. 9715 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9716 ? PackageUtils.computeSignaturesSha256Digests( 9717 libPkg.mSigningDetails.signatures) 9718 : PackageUtils.computeSignaturesSha256Digests( 9719 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9720 9721 // Take a shortcut if sizes don't match. Note that if an app doesn't 9722 // target O we don't parse the "additional-certificate" tags similarly 9723 // how we only consider all certs only for apps targeting O (see above). 9724 // Therefore, the size check is safe to make. 9725 if (expectedCertDigests.length != libCertDigests.length) { 9726 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9727 "Package " + packageName + " requires differently signed" + 9728 " static shared library; failing!"); 9729 } 9730 9731 // Use a predictable order as signature order may vary 9732 Arrays.sort(libCertDigests); 9733 Arrays.sort(expectedCertDigests); 9734 9735 final int certCount = libCertDigests.length; 9736 for (int j = 0; j < certCount; j++) { 9737 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9738 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9739 "Package " + packageName + " requires differently signed" + 9740 " static shared library; failing!"); 9741 } 9742 } 9743 } 9744 9745 if (outUsedLibraries == null) { 9746 // Use LinkedHashSet to preserve the order of files added to 9747 // usesLibraryFiles while eliminating duplicates. 9748 outUsedLibraries = new LinkedHashSet<>(); 9749 } 9750 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9751 } 9752 } 9753 return outUsedLibraries; 9754 } 9755 9756 private static boolean hasString(List<String> list, List<String> which) { 9757 if (list == null) { 9758 return false; 9759 } 9760 for (int i=list.size()-1; i>=0; i--) { 9761 for (int j=which.size()-1; j>=0; j--) { 9762 if (which.get(j).equals(list.get(i))) { 9763 return true; 9764 } 9765 } 9766 } 9767 return false; 9768 } 9769 9770 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9771 PackageParser.Package changingPkg) { 9772 ArrayList<PackageParser.Package> res = null; 9773 for (PackageParser.Package pkg : mPackages.values()) { 9774 if (changingPkg != null 9775 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9776 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9777 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9778 changingPkg.staticSharedLibName)) { 9779 return null; 9780 } 9781 if (res == null) { 9782 res = new ArrayList<>(); 9783 } 9784 res.add(pkg); 9785 try { 9786 updateSharedLibrariesLPr(pkg, changingPkg); 9787 } catch (PackageManagerException e) { 9788 // If a system app update or an app and a required lib missing we 9789 // delete the package and for updated system apps keep the data as 9790 // it is better for the user to reinstall than to be in an limbo 9791 // state. Also libs disappearing under an app should never happen 9792 // - just in case. 9793 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9794 final int flags = pkg.isUpdatedSystemApp() 9795 ? PackageManager.DELETE_KEEP_DATA : 0; 9796 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9797 flags , null, true, null); 9798 } 9799 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9800 } 9801 } 9802 return res; 9803 } 9804 9805 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9806 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9807 @Nullable UserHandle user) throws PackageManagerException { 9808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9809 // If the package has children and this is the first dive in the function 9810 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9811 // whether all packages (parent and children) would be successfully scanned 9812 // before the actual scan since scanning mutates internal state and we want 9813 // to atomically install the package and its children. 9814 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9815 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9816 scanFlags |= SCAN_CHECK_ONLY; 9817 } 9818 } else { 9819 scanFlags &= ~SCAN_CHECK_ONLY; 9820 } 9821 9822 final PackageParser.Package scannedPkg; 9823 try { 9824 // Scan the parent 9825 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9826 // Scan the children 9827 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9828 for (int i = 0; i < childCount; i++) { 9829 PackageParser.Package childPkg = pkg.childPackages.get(i); 9830 scanPackageNewLI(childPkg, parseFlags, 9831 scanFlags, currentTime, user); 9832 } 9833 } finally { 9834 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9835 } 9836 9837 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9838 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9839 } 9840 9841 return scannedPkg; 9842 } 9843 9844 /** The result of a package scan. */ 9845 private static class ScanResult { 9846 /** Whether or not the package scan was successful */ 9847 public final boolean success; 9848 /** 9849 * The final package settings. This may be the same object passed in 9850 * the {@link ScanRequest}, but, with modified values. 9851 */ 9852 @Nullable public final PackageSetting pkgSetting; 9853 /** ABI code paths that have changed in the package scan */ 9854 @Nullable public final List<String> changedAbiCodePath; 9855 public ScanResult( 9856 boolean success, 9857 @Nullable PackageSetting pkgSetting, 9858 @Nullable List<String> changedAbiCodePath) { 9859 this.success = success; 9860 this.pkgSetting = pkgSetting; 9861 this.changedAbiCodePath = changedAbiCodePath; 9862 } 9863 } 9864 9865 /** A package to be scanned */ 9866 private static class ScanRequest { 9867 /** The parsed package */ 9868 @NonNull public final PackageParser.Package pkg; 9869 /** Shared user settings, if the package has a shared user */ 9870 @Nullable public final SharedUserSetting sharedUserSetting; 9871 /** 9872 * Package settings of the currently installed version. 9873 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9874 * during scan. 9875 */ 9876 @Nullable public final PackageSetting pkgSetting; 9877 /** A copy of the settings for the currently installed version */ 9878 @Nullable public final PackageSetting oldPkgSetting; 9879 /** Package settings for the disabled version on the /system partition */ 9880 @Nullable public final PackageSetting disabledPkgSetting; 9881 /** Package settings for the installed version under its original package name */ 9882 @Nullable public final PackageSetting originalPkgSetting; 9883 /** The real package name of a renamed application */ 9884 @Nullable public final String realPkgName; 9885 public final @ParseFlags int parseFlags; 9886 public final @ScanFlags int scanFlags; 9887 /** The user for which the package is being scanned */ 9888 @Nullable public final UserHandle user; 9889 /** Whether or not the platform package is being scanned */ 9890 public final boolean isPlatformPackage; 9891 public ScanRequest( 9892 @NonNull PackageParser.Package pkg, 9893 @Nullable SharedUserSetting sharedUserSetting, 9894 @Nullable PackageSetting pkgSetting, 9895 @Nullable PackageSetting disabledPkgSetting, 9896 @Nullable PackageSetting originalPkgSetting, 9897 @Nullable String realPkgName, 9898 @ParseFlags int parseFlags, 9899 @ScanFlags int scanFlags, 9900 boolean isPlatformPackage, 9901 @Nullable UserHandle user) { 9902 this.pkg = pkg; 9903 this.pkgSetting = pkgSetting; 9904 this.sharedUserSetting = sharedUserSetting; 9905 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9906 this.disabledPkgSetting = disabledPkgSetting; 9907 this.originalPkgSetting = originalPkgSetting; 9908 this.realPkgName = realPkgName; 9909 this.parseFlags = parseFlags; 9910 this.scanFlags = scanFlags; 9911 this.isPlatformPackage = isPlatformPackage; 9912 this.user = user; 9913 } 9914 } 9915 9916 /** 9917 * Returns the actual scan flags depending upon the state of the other settings. 9918 * <p>Updated system applications will not have the following flags set 9919 * by default and need to be adjusted after the fact: 9920 * <ul> 9921 * <li>{@link #SCAN_AS_SYSTEM}</li> 9922 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9923 * <li>{@link #SCAN_AS_OEM}</li> 9924 * <li>{@link #SCAN_AS_VENDOR}</li> 9925 * <li>{@link #SCAN_AS_PRODUCT}</li> 9926 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9927 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9928 * </ul> 9929 */ 9930 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9931 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9932 PackageParser.Package pkg) { 9933 if (disabledPkgSetting != null) { 9934 // updated system application, must at least have SCAN_AS_SYSTEM 9935 scanFlags |= SCAN_AS_SYSTEM; 9936 if ((disabledPkgSetting.pkgPrivateFlags 9937 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9938 scanFlags |= SCAN_AS_PRIVILEGED; 9939 } 9940 if ((disabledPkgSetting.pkgPrivateFlags 9941 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9942 scanFlags |= SCAN_AS_OEM; 9943 } 9944 if ((disabledPkgSetting.pkgPrivateFlags 9945 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9946 scanFlags |= SCAN_AS_VENDOR; 9947 } 9948 if ((disabledPkgSetting.pkgPrivateFlags 9949 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9950 scanFlags |= SCAN_AS_PRODUCT; 9951 } 9952 } 9953 if (pkgSetting != null) { 9954 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9955 if (pkgSetting.getInstantApp(userId)) { 9956 scanFlags |= SCAN_AS_INSTANT_APP; 9957 } 9958 if (pkgSetting.getVirtulalPreload(userId)) { 9959 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9960 } 9961 } 9962 9963 // Scan as privileged apps that share a user with a priv-app. 9964 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9965 && (pkg.mSharedUserId != null)) { 9966 SharedUserSetting sharedUserSetting = null; 9967 try { 9968 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9969 } catch (PackageManagerException ignore) {} 9970 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9971 // Exempt SharedUsers signed with the platform key. 9972 // TODO(b/72378145) Fix this exemption. Force signature apps 9973 // to whitelist their privileged permissions just like other 9974 // priv-apps. 9975 synchronized (mPackages) { 9976 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9977 if (!pkg.packageName.equals("android") 9978 && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9979 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9980 scanFlags |= SCAN_AS_PRIVILEGED; 9981 } 9982 } 9983 } 9984 } 9985 9986 return scanFlags; 9987 } 9988 9989 @GuardedBy("mInstallLock") 9990 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9991 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9992 @Nullable UserHandle user) throws PackageManagerException { 9993 9994 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9995 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9996 if (realPkgName != null) { 9997 ensurePackageRenamed(pkg, renamedPkgName); 9998 } 9999 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10000 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10001 final PackageSetting disabledPkgSetting = 10002 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10003 10004 if (mTransferedPackages.contains(pkg.packageName)) { 10005 Slog.w(TAG, "Package " + pkg.packageName 10006 + " was transferred to another, but its .apk remains"); 10007 } 10008 10009 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10010 synchronized (mPackages) { 10011 applyPolicy(pkg, parseFlags, scanFlags); 10012 assertPackageIsValid(pkg, parseFlags, scanFlags); 10013 10014 SharedUserSetting sharedUserSetting = null; 10015 if (pkg.mSharedUserId != null) { 10016 // SIDE EFFECTS; may potentially allocate a new shared user 10017 sharedUserSetting = mSettings.getSharedUserLPw( 10018 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10019 if (DEBUG_PACKAGE_SCANNING) { 10020 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10021 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10022 + " (uid=" + sharedUserSetting.userId + "):" 10023 + " packages=" + sharedUserSetting.packages); 10024 } 10025 } 10026 10027 boolean scanSucceeded = false; 10028 try { 10029 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10030 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10031 (pkg == mPlatformPackage), user); 10032 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10033 if (result.success) { 10034 commitScanResultsLocked(request, result); 10035 } 10036 scanSucceeded = true; 10037 } finally { 10038 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10039 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10040 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10041 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10042 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10043 } 10044 } 10045 } 10046 return pkg; 10047 } 10048 10049 /** 10050 * Commits the package scan and modifies system state. 10051 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10052 * of committing the package, leaving the system in an inconsistent state. 10053 * This needs to be fixed so, once we get to this point, no errors are 10054 * possible and the system is not left in an inconsistent state. 10055 */ 10056 @GuardedBy("mPackages") 10057 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10058 throws PackageManagerException { 10059 final PackageParser.Package pkg = request.pkg; 10060 final @ParseFlags int parseFlags = request.parseFlags; 10061 final @ScanFlags int scanFlags = request.scanFlags; 10062 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10063 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10064 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10065 final UserHandle user = request.user; 10066 final String realPkgName = request.realPkgName; 10067 final PackageSetting pkgSetting = result.pkgSetting; 10068 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10069 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10070 10071 if (newPkgSettingCreated) { 10072 if (originalPkgSetting != null) { 10073 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10074 } 10075 // THROWS: when we can't allocate a user id. add call to check if there's 10076 // enough space to ensure we won't throw; otherwise, don't modify state 10077 mSettings.addUserToSettingLPw(pkgSetting); 10078 10079 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10080 mTransferedPackages.add(originalPkgSetting.name); 10081 } 10082 } 10083 // TODO(toddke): Consider a method specifically for modifying the Package object 10084 // post scan; or, moving this stuff out of the Package object since it has nothing 10085 // to do with the package on disk. 10086 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10087 // for creating the application ID. If we did this earlier, we would be saving the 10088 // correct ID. 10089 pkg.applicationInfo.uid = pkgSetting.appId; 10090 10091 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10092 10093 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10094 mTransferedPackages.add(pkg.packageName); 10095 } 10096 10097 // THROWS: when requested libraries that can't be found. it only changes 10098 // the state of the passed in pkg object, so, move to the top of the method 10099 // and allow it to abort 10100 if ((scanFlags & SCAN_BOOTING) == 0 10101 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10102 // Check all shared libraries and map to their actual file path. 10103 // We only do this here for apps not on a system dir, because those 10104 // are the only ones that can fail an install due to this. We 10105 // will take care of the system apps by updating all of their 10106 // library paths after the scan is done. Also during the initial 10107 // scan don't update any libs as we do this wholesale after all 10108 // apps are scanned to avoid dependency based scanning. 10109 updateSharedLibrariesLPr(pkg, null); 10110 } 10111 10112 // All versions of a static shared library are referenced with the same 10113 // package name. Internally, we use a synthetic package name to allow 10114 // multiple versions of the same shared library to be installed. So, 10115 // we need to generate the synthetic package name of the latest shared 10116 // library in order to compare signatures. 10117 PackageSetting signatureCheckPs = pkgSetting; 10118 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10119 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10120 if (libraryEntry != null) { 10121 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10122 } 10123 } 10124 10125 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10126 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10127 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10128 // We just determined the app is signed correctly, so bring 10129 // over the latest parsed certs. 10130 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10131 } else { 10132 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10133 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10134 "Package " + pkg.packageName + " upgrade keys do not match the " 10135 + "previously installed version"); 10136 } else { 10137 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10138 String msg = "System package " + pkg.packageName 10139 + " signature changed; retaining data."; 10140 reportSettingsProblem(Log.WARN, msg); 10141 } 10142 } 10143 } else { 10144 try { 10145 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10146 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10147 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10148 pkg.mSigningDetails, compareCompat, compareRecover); 10149 // The new KeySets will be re-added later in the scanning process. 10150 if (compatMatch) { 10151 synchronized (mPackages) { 10152 ksms.removeAppKeySetDataLPw(pkg.packageName); 10153 } 10154 } 10155 // We just determined the app is signed correctly, so bring 10156 // over the latest parsed certs. 10157 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10158 } catch (PackageManagerException e) { 10159 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10160 throw e; 10161 } 10162 // The signature has changed, but this package is in the system 10163 // image... let's recover! 10164 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10165 // However... if this package is part of a shared user, but it 10166 // doesn't match the signature of the shared user, let's fail. 10167 // What this means is that you can't change the signatures 10168 // associated with an overall shared user, which doesn't seem all 10169 // that unreasonable. 10170 if (signatureCheckPs.sharedUser != null) { 10171 if (compareSignatures( 10172 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10173 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10174 throw new PackageManagerException( 10175 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10176 "Signature mismatch for shared user: " 10177 + pkgSetting.sharedUser); 10178 } 10179 } 10180 // File a report about this. 10181 String msg = "System package " + pkg.packageName 10182 + " signature changed; retaining data."; 10183 reportSettingsProblem(Log.WARN, msg); 10184 } 10185 } 10186 10187 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10188 // This package wants to adopt ownership of permissions from 10189 // another package. 10190 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10191 final String origName = pkg.mAdoptPermissions.get(i); 10192 final PackageSetting orig = mSettings.getPackageLPr(origName); 10193 if (orig != null) { 10194 if (verifyPackageUpdateLPr(orig, pkg)) { 10195 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10196 + pkg.packageName); 10197 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10198 } 10199 } 10200 } 10201 } 10202 10203 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10204 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10205 final String codePathString = changedAbiCodePath.get(i); 10206 try { 10207 mInstaller.rmdex(codePathString, 10208 getDexCodeInstructionSet(getPreferredInstructionSet())); 10209 } catch (InstallerException ignored) { 10210 } 10211 } 10212 } 10213 10214 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10215 if (oldPkgSetting != null) { 10216 synchronized (mPackages) { 10217 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10218 } 10219 } 10220 } else { 10221 final int userId = user == null ? 0 : user.getIdentifier(); 10222 // Modify state for the given package setting 10223 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10224 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10225 if (pkgSetting.getInstantApp(userId)) { 10226 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10227 } 10228 } 10229 } 10230 10231 /** 10232 * Returns the "real" name of the package. 10233 * <p>This may differ from the package's actual name if the application has already 10234 * been installed under one of this package's original names. 10235 */ 10236 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10237 @Nullable String renamedPkgName) { 10238 if (isPackageRenamed(pkg, renamedPkgName)) { 10239 return pkg.mRealPackage; 10240 } 10241 return null; 10242 } 10243 10244 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10245 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10246 @Nullable String renamedPkgName) { 10247 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10248 } 10249 10250 /** 10251 * Returns the original package setting. 10252 * <p>A package can migrate its name during an update. In this scenario, a package 10253 * designates a set of names that it considers as one of its original names. 10254 * <p>An original package must be signed identically and it must have the same 10255 * shared user [if any]. 10256 */ 10257 @GuardedBy("mPackages") 10258 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10259 @Nullable String renamedPkgName) { 10260 if (!isPackageRenamed(pkg, renamedPkgName)) { 10261 return null; 10262 } 10263 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10264 final PackageSetting originalPs = 10265 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10266 if (originalPs != null) { 10267 // the package is already installed under its original name... 10268 // but, should we use it? 10269 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10270 // the new package is incompatible with the original 10271 continue; 10272 } else if (originalPs.sharedUser != null) { 10273 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10274 // the shared user id is incompatible with the original 10275 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10276 + " to " + pkg.packageName + ": old uid " 10277 + originalPs.sharedUser.name 10278 + " differs from " + pkg.mSharedUserId); 10279 continue; 10280 } 10281 // TODO: Add case when shared user id is added [b/28144775] 10282 } else { 10283 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10284 + pkg.packageName + " to old name " + originalPs.name); 10285 } 10286 return originalPs; 10287 } 10288 } 10289 return null; 10290 } 10291 10292 /** 10293 * Renames the package if it was installed under a different name. 10294 * <p>When we've already installed the package under an original name, update 10295 * the new package so we can continue to have the old name. 10296 */ 10297 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10298 @NonNull String renamedPackageName) { 10299 if (pkg.mOriginalPackages == null 10300 || !pkg.mOriginalPackages.contains(renamedPackageName) 10301 || pkg.packageName.equals(renamedPackageName)) { 10302 return; 10303 } 10304 pkg.setPackageName(renamedPackageName); 10305 } 10306 10307 /** 10308 * Just scans the package without any side effects. 10309 * <p>Not entirely true at the moment. There is still one side effect -- this 10310 * method potentially modifies a live {@link PackageSetting} object representing 10311 * the package being scanned. This will be resolved in the future. 10312 * 10313 * @param request Information about the package to be scanned 10314 * @param isUnderFactoryTest Whether or not the device is under factory test 10315 * @param currentTime The current time, in millis 10316 * @return The results of the scan 10317 */ 10318 @GuardedBy("mInstallLock") 10319 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10320 boolean isUnderFactoryTest, long currentTime) 10321 throws PackageManagerException { 10322 final PackageParser.Package pkg = request.pkg; 10323 PackageSetting pkgSetting = request.pkgSetting; 10324 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10325 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10326 final @ParseFlags int parseFlags = request.parseFlags; 10327 final @ScanFlags int scanFlags = request.scanFlags; 10328 final String realPkgName = request.realPkgName; 10329 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10330 final UserHandle user = request.user; 10331 final boolean isPlatformPackage = request.isPlatformPackage; 10332 10333 List<String> changedAbiCodePath = null; 10334 10335 if (DEBUG_PACKAGE_SCANNING) { 10336 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10337 Log.d(TAG, "Scanning package " + pkg.packageName); 10338 } 10339 10340 if (Build.IS_DEBUGGABLE && 10341 pkg.isPrivileged() && 10342 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10343 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10344 } 10345 10346 // Initialize package source and resource directories 10347 final File scanFile = new File(pkg.codePath); 10348 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10349 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10350 10351 // We keep references to the derived CPU Abis from settings in oder to reuse 10352 // them in the case where we're not upgrading or booting for the first time. 10353 String primaryCpuAbiFromSettings = null; 10354 String secondaryCpuAbiFromSettings = null; 10355 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10356 10357 if (!needToDeriveAbi) { 10358 if (pkgSetting != null) { 10359 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10360 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10361 } else { 10362 // Re-scanning a system package after uninstalling updates; need to derive ABI 10363 needToDeriveAbi = true; 10364 } 10365 } 10366 10367 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10368 PackageManagerService.reportSettingsProblem(Log.WARN, 10369 "Package " + pkg.packageName + " shared user changed from " 10370 + (pkgSetting.sharedUser != null 10371 ? pkgSetting.sharedUser.name : "<nothing>") 10372 + " to " 10373 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10374 + "; replacing with new"); 10375 pkgSetting = null; 10376 } 10377 10378 String[] usesStaticLibraries = null; 10379 if (pkg.usesStaticLibraries != null) { 10380 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10381 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10382 } 10383 final boolean createNewPackage = (pkgSetting == null); 10384 if (createNewPackage) { 10385 final String parentPackageName = (pkg.parentPackage != null) 10386 ? pkg.parentPackage.packageName : null; 10387 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10388 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10389 // REMOVE SharedUserSetting from method; update in a separate call 10390 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10391 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10392 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10393 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10394 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10395 user, true /*allowInstall*/, instantApp, virtualPreload, 10396 parentPackageName, pkg.getChildPackageNames(), 10397 UserManagerService.getInstance(), usesStaticLibraries, 10398 pkg.usesStaticLibrariesVersions); 10399 } else { 10400 // REMOVE SharedUserSetting from method; update in a separate call. 10401 // 10402 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10403 // secondaryCpuAbi are not known at this point so we always update them 10404 // to null here, only to reset them at a later point. 10405 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10406 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10407 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10408 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10409 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10410 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10411 } 10412 if (createNewPackage && originalPkgSetting != null) { 10413 // This is the initial transition from the original package, so, 10414 // fix up the new package's name now. We must do this after looking 10415 // up the package under its new name, so getPackageLP takes care of 10416 // fiddling things correctly. 10417 pkg.setPackageName(originalPkgSetting.name); 10418 10419 // File a report about this. 10420 String msg = "New package " + pkgSetting.realName 10421 + " renamed to replace old package " + pkgSetting.name; 10422 reportSettingsProblem(Log.WARN, msg); 10423 } 10424 10425 if (disabledPkgSetting != null) { 10426 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10427 } 10428 10429 SELinuxMMAC.assignSeInfoValue(pkg); 10430 10431 pkg.mExtras = pkgSetting; 10432 pkg.applicationInfo.processName = fixProcessName( 10433 pkg.applicationInfo.packageName, 10434 pkg.applicationInfo.processName); 10435 10436 if (!isPlatformPackage) { 10437 // Get all of our default paths setup 10438 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10439 } 10440 10441 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10442 10443 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10444 if (needToDeriveAbi) { 10445 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10446 final boolean extractNativeLibs = !pkg.isLibrary(); 10447 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10448 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10449 10450 // Some system apps still use directory structure for native libraries 10451 // in which case we might end up not detecting abi solely based on apk 10452 // structure. Try to detect abi based on directory structure. 10453 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10454 pkg.applicationInfo.primaryCpuAbi == null) { 10455 setBundledAppAbisAndRoots(pkg, pkgSetting); 10456 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10457 } 10458 } else { 10459 // This is not a first boot or an upgrade, don't bother deriving the 10460 // ABI during the scan. Instead, trust the value that was stored in the 10461 // package setting. 10462 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10463 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10464 10465 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10466 10467 if (DEBUG_ABI_SELECTION) { 10468 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10469 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10470 pkg.applicationInfo.secondaryCpuAbi); 10471 } 10472 } 10473 } else { 10474 if ((scanFlags & SCAN_MOVE) != 0) { 10475 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10476 // but we already have this packages package info in the PackageSetting. We just 10477 // use that and derive the native library path based on the new codepath. 10478 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10479 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10480 } 10481 10482 // Set native library paths again. For moves, the path will be updated based on the 10483 // ABIs we've determined above. For non-moves, the path will be updated based on the 10484 // ABIs we determined during compilation, but the path will depend on the final 10485 // package path (after the rename away from the stage path). 10486 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10487 } 10488 10489 // This is a special case for the "system" package, where the ABI is 10490 // dictated by the zygote configuration (and init.rc). We should keep track 10491 // of this ABI so that we can deal with "normal" applications that run under 10492 // the same UID correctly. 10493 if (isPlatformPackage) { 10494 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10495 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10496 } 10497 10498 // If there's a mismatch between the abi-override in the package setting 10499 // and the abiOverride specified for the install. Warn about this because we 10500 // would've already compiled the app without taking the package setting into 10501 // account. 10502 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10503 if (cpuAbiOverride == null && pkg.packageName != null) { 10504 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10505 " for package " + pkg.packageName); 10506 } 10507 } 10508 10509 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10510 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10511 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10512 10513 // Copy the derived override back to the parsed package, so that we can 10514 // update the package settings accordingly. 10515 pkg.cpuAbiOverride = cpuAbiOverride; 10516 10517 if (DEBUG_ABI_SELECTION) { 10518 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10519 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10520 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10521 } 10522 10523 // Push the derived path down into PackageSettings so we know what to 10524 // clean up at uninstall time. 10525 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10526 10527 if (DEBUG_ABI_SELECTION) { 10528 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10529 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10530 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10531 } 10532 10533 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10534 // We don't do this here during boot because we can do it all 10535 // at once after scanning all existing packages. 10536 // 10537 // We also do this *before* we perform dexopt on this package, so that 10538 // we can avoid redundant dexopts, and also to make sure we've got the 10539 // code and package path correct. 10540 changedAbiCodePath = 10541 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10542 } 10543 10544 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10545 android.Manifest.permission.FACTORY_TEST)) { 10546 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10547 } 10548 10549 if (isSystemApp(pkg)) { 10550 pkgSetting.isOrphaned = true; 10551 } 10552 10553 // Take care of first install / last update times. 10554 final long scanFileTime = getLastModifiedTime(pkg); 10555 if (currentTime != 0) { 10556 if (pkgSetting.firstInstallTime == 0) { 10557 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10558 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10559 pkgSetting.lastUpdateTime = currentTime; 10560 } 10561 } else if (pkgSetting.firstInstallTime == 0) { 10562 // We need *something*. Take time time stamp of the file. 10563 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10564 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10565 if (scanFileTime != pkgSetting.timeStamp) { 10566 // A package on the system image has changed; consider this 10567 // to be an update. 10568 pkgSetting.lastUpdateTime = scanFileTime; 10569 } 10570 } 10571 pkgSetting.setTimeStamp(scanFileTime); 10572 10573 pkgSetting.pkg = pkg; 10574 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10575 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10576 pkgSetting.versionCode = pkg.getLongVersionCode(); 10577 } 10578 // Update volume if needed 10579 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10580 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10581 Slog.i(PackageManagerService.TAG, 10582 "Update" + (pkgSetting.isSystem() ? " system" : "") 10583 + " package " + pkg.packageName 10584 + " volume from " + pkgSetting.volumeUuid 10585 + " to " + volumeUuid); 10586 pkgSetting.volumeUuid = volumeUuid; 10587 } 10588 10589 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10590 } 10591 10592 /** 10593 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10594 */ 10595 private static boolean apkHasCode(String fileName) { 10596 StrictJarFile jarFile = null; 10597 try { 10598 jarFile = new StrictJarFile(fileName, 10599 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10600 return jarFile.findEntry("classes.dex") != null; 10601 } catch (IOException ignore) { 10602 } finally { 10603 try { 10604 if (jarFile != null) { 10605 jarFile.close(); 10606 } 10607 } catch (IOException ignore) {} 10608 } 10609 return false; 10610 } 10611 10612 /** 10613 * Enforces code policy for the package. This ensures that if an APK has 10614 * declared hasCode="true" in its manifest that the APK actually contains 10615 * code. 10616 * 10617 * @throws PackageManagerException If bytecode could not be found when it should exist 10618 */ 10619 private static void assertCodePolicy(PackageParser.Package pkg) 10620 throws PackageManagerException { 10621 final boolean shouldHaveCode = 10622 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10623 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10624 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10625 "Package " + pkg.baseCodePath + " code is missing"); 10626 } 10627 10628 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10629 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10630 final boolean splitShouldHaveCode = 10631 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10632 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10633 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10634 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10635 } 10636 } 10637 } 10638 } 10639 10640 /** 10641 * Applies policy to the parsed package based upon the given policy flags. 10642 * Ensures the package is in a good state. 10643 * <p> 10644 * Implementation detail: This method must NOT have any side effect. It would 10645 * ideally be static, but, it requires locks to read system state. 10646 */ 10647 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10648 final @ScanFlags int scanFlags) { 10649 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10650 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10651 if (pkg.applicationInfo.isDirectBootAware()) { 10652 // we're direct boot aware; set for all components 10653 for (PackageParser.Service s : pkg.services) { 10654 s.info.encryptionAware = s.info.directBootAware = true; 10655 } 10656 for (PackageParser.Provider p : pkg.providers) { 10657 p.info.encryptionAware = p.info.directBootAware = true; 10658 } 10659 for (PackageParser.Activity a : pkg.activities) { 10660 a.info.encryptionAware = a.info.directBootAware = true; 10661 } 10662 for (PackageParser.Activity r : pkg.receivers) { 10663 r.info.encryptionAware = r.info.directBootAware = true; 10664 } 10665 } 10666 if (compressedFileExists(pkg.codePath)) { 10667 pkg.isStub = true; 10668 } 10669 } else { 10670 // non system apps can't be flagged as core 10671 pkg.coreApp = false; 10672 // clear flags not applicable to regular apps 10673 pkg.applicationInfo.flags &= 10674 ~ApplicationInfo.FLAG_PERSISTENT; 10675 pkg.applicationInfo.privateFlags &= 10676 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10677 pkg.applicationInfo.privateFlags &= 10678 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10679 // clear protected broadcasts 10680 pkg.protectedBroadcasts = null; 10681 // cap permission priorities 10682 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10683 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10684 pkg.permissionGroups.get(i).info.priority = 0; 10685 } 10686 } 10687 } 10688 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10689 // ignore export request for single user receivers 10690 if (pkg.receivers != null) { 10691 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10692 final PackageParser.Activity receiver = pkg.receivers.get(i); 10693 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10694 receiver.info.exported = false; 10695 } 10696 } 10697 } 10698 // ignore export request for single user services 10699 if (pkg.services != null) { 10700 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10701 final PackageParser.Service service = pkg.services.get(i); 10702 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10703 service.info.exported = false; 10704 } 10705 } 10706 } 10707 // ignore export request for single user providers 10708 if (pkg.providers != null) { 10709 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10710 final PackageParser.Provider provider = pkg.providers.get(i); 10711 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10712 provider.info.exported = false; 10713 } 10714 } 10715 } 10716 } 10717 10718 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10719 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10720 } 10721 10722 if ((scanFlags & SCAN_AS_OEM) != 0) { 10723 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10724 } 10725 10726 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10727 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10728 } 10729 10730 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10731 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10732 } 10733 10734 if (!isSystemApp(pkg)) { 10735 // Only system apps can use these features. 10736 pkg.mOriginalPackages = null; 10737 pkg.mRealPackage = null; 10738 pkg.mAdoptPermissions = null; 10739 } 10740 } 10741 10742 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10743 throws PackageManagerException { 10744 if (object == null) { 10745 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10746 } 10747 return object; 10748 } 10749 10750 /** 10751 * Asserts the parsed package is valid according to the given policy. If the 10752 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10753 * <p> 10754 * Implementation detail: This method must NOT have any side effects. It would 10755 * ideally be static, but, it requires locks to read system state. 10756 * 10757 * @throws PackageManagerException If the package fails any of the validation checks 10758 */ 10759 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10760 final @ScanFlags int scanFlags) 10761 throws PackageManagerException { 10762 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10763 assertCodePolicy(pkg); 10764 } 10765 10766 if (pkg.applicationInfo.getCodePath() == null || 10767 pkg.applicationInfo.getResourcePath() == null) { 10768 // Bail out. The resource and code paths haven't been set. 10769 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10770 "Code and resource paths haven't been set correctly"); 10771 } 10772 10773 // Make sure we're not adding any bogus keyset info 10774 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10775 ksms.assertScannedPackageValid(pkg); 10776 10777 synchronized (mPackages) { 10778 // The special "android" package can only be defined once 10779 if (pkg.packageName.equals("android")) { 10780 if (mAndroidApplication != null) { 10781 Slog.w(TAG, "*************************************************"); 10782 Slog.w(TAG, "Core android package being redefined. Skipping."); 10783 Slog.w(TAG, " codePath=" + pkg.codePath); 10784 Slog.w(TAG, "*************************************************"); 10785 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10786 "Core android package being redefined. Skipping."); 10787 } 10788 } 10789 10790 // A package name must be unique; don't allow duplicates 10791 if (mPackages.containsKey(pkg.packageName)) { 10792 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10793 "Application package " + pkg.packageName 10794 + " already installed. Skipping duplicate."); 10795 } 10796 10797 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10798 // Static libs have a synthetic package name containing the version 10799 // but we still want the base name to be unique. 10800 if (mPackages.containsKey(pkg.manifestPackageName)) { 10801 throw new PackageManagerException( 10802 "Duplicate static shared lib provider package"); 10803 } 10804 10805 // Static shared libraries should have at least O target SDK 10806 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10807 throw new PackageManagerException( 10808 "Packages declaring static-shared libs must target O SDK or higher"); 10809 } 10810 10811 // Package declaring static a shared lib cannot be instant apps 10812 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10813 throw new PackageManagerException( 10814 "Packages declaring static-shared libs cannot be instant apps"); 10815 } 10816 10817 // Package declaring static a shared lib cannot be renamed since the package 10818 // name is synthetic and apps can't code around package manager internals. 10819 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10820 throw new PackageManagerException( 10821 "Packages declaring static-shared libs cannot be renamed"); 10822 } 10823 10824 // Package declaring static a shared lib cannot declare child packages 10825 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10826 throw new PackageManagerException( 10827 "Packages declaring static-shared libs cannot have child packages"); 10828 } 10829 10830 // Package declaring static a shared lib cannot declare dynamic libs 10831 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10832 throw new PackageManagerException( 10833 "Packages declaring static-shared libs cannot declare dynamic libs"); 10834 } 10835 10836 // Package declaring static a shared lib cannot declare shared users 10837 if (pkg.mSharedUserId != null) { 10838 throw new PackageManagerException( 10839 "Packages declaring static-shared libs cannot declare shared users"); 10840 } 10841 10842 // Static shared libs cannot declare activities 10843 if (!pkg.activities.isEmpty()) { 10844 throw new PackageManagerException( 10845 "Static shared libs cannot declare activities"); 10846 } 10847 10848 // Static shared libs cannot declare services 10849 if (!pkg.services.isEmpty()) { 10850 throw new PackageManagerException( 10851 "Static shared libs cannot declare services"); 10852 } 10853 10854 // Static shared libs cannot declare providers 10855 if (!pkg.providers.isEmpty()) { 10856 throw new PackageManagerException( 10857 "Static shared libs cannot declare content providers"); 10858 } 10859 10860 // Static shared libs cannot declare receivers 10861 if (!pkg.receivers.isEmpty()) { 10862 throw new PackageManagerException( 10863 "Static shared libs cannot declare broadcast receivers"); 10864 } 10865 10866 // Static shared libs cannot declare permission groups 10867 if (!pkg.permissionGroups.isEmpty()) { 10868 throw new PackageManagerException( 10869 "Static shared libs cannot declare permission groups"); 10870 } 10871 10872 // Static shared libs cannot declare permissions 10873 if (!pkg.permissions.isEmpty()) { 10874 throw new PackageManagerException( 10875 "Static shared libs cannot declare permissions"); 10876 } 10877 10878 // Static shared libs cannot declare protected broadcasts 10879 if (pkg.protectedBroadcasts != null) { 10880 throw new PackageManagerException( 10881 "Static shared libs cannot declare protected broadcasts"); 10882 } 10883 10884 // Static shared libs cannot be overlay targets 10885 if (pkg.mOverlayTarget != null) { 10886 throw new PackageManagerException( 10887 "Static shared libs cannot be overlay targets"); 10888 } 10889 10890 // The version codes must be ordered as lib versions 10891 long minVersionCode = Long.MIN_VALUE; 10892 long maxVersionCode = Long.MAX_VALUE; 10893 10894 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10895 pkg.staticSharedLibName); 10896 if (versionedLib != null) { 10897 final int versionCount = versionedLib.size(); 10898 for (int i = 0; i < versionCount; i++) { 10899 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10900 final long libVersionCode = libInfo.getDeclaringPackage() 10901 .getLongVersionCode(); 10902 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10903 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10904 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10905 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10906 } else { 10907 minVersionCode = maxVersionCode = libVersionCode; 10908 break; 10909 } 10910 } 10911 } 10912 if (pkg.getLongVersionCode() < minVersionCode 10913 || pkg.getLongVersionCode() > maxVersionCode) { 10914 throw new PackageManagerException("Static shared" 10915 + " lib version codes must be ordered as lib versions"); 10916 } 10917 } 10918 10919 // Only privileged apps and updated privileged apps can add child packages. 10920 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10921 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10922 throw new PackageManagerException("Only privileged apps can add child " 10923 + "packages. Ignoring package " + pkg.packageName); 10924 } 10925 final int childCount = pkg.childPackages.size(); 10926 for (int i = 0; i < childCount; i++) { 10927 PackageParser.Package childPkg = pkg.childPackages.get(i); 10928 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10929 childPkg.packageName)) { 10930 throw new PackageManagerException("Can't override child of " 10931 + "another disabled app. Ignoring package " + pkg.packageName); 10932 } 10933 } 10934 } 10935 10936 // If we're only installing presumed-existing packages, require that the 10937 // scanned APK is both already known and at the path previously established 10938 // for it. Previously unknown packages we pick up normally, but if we have an 10939 // a priori expectation about this package's install presence, enforce it. 10940 // With a singular exception for new system packages. When an OTA contains 10941 // a new system package, we allow the codepath to change from a system location 10942 // to the user-installed location. If we don't allow this change, any newer, 10943 // user-installed version of the application will be ignored. 10944 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10945 if (mExpectingBetter.containsKey(pkg.packageName)) { 10946 logCriticalInfo(Log.WARN, 10947 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10948 } else { 10949 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10950 if (known != null) { 10951 if (DEBUG_PACKAGE_SCANNING) { 10952 Log.d(TAG, "Examining " + pkg.codePath 10953 + " and requiring known paths " + known.codePathString 10954 + " & " + known.resourcePathString); 10955 } 10956 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10957 || !pkg.applicationInfo.getResourcePath().equals( 10958 known.resourcePathString)) { 10959 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10960 "Application package " + pkg.packageName 10961 + " found at " + pkg.applicationInfo.getCodePath() 10962 + " but expected at " + known.codePathString 10963 + "; ignoring."); 10964 } 10965 } else { 10966 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10967 "Application package " + pkg.packageName 10968 + " not found; ignoring."); 10969 } 10970 } 10971 } 10972 10973 // Verify that this new package doesn't have any content providers 10974 // that conflict with existing packages. Only do this if the 10975 // package isn't already installed, since we don't want to break 10976 // things that are installed. 10977 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10978 final int N = pkg.providers.size(); 10979 int i; 10980 for (i=0; i<N; i++) { 10981 PackageParser.Provider p = pkg.providers.get(i); 10982 if (p.info.authority != null) { 10983 String names[] = p.info.authority.split(";"); 10984 for (int j = 0; j < names.length; j++) { 10985 if (mProvidersByAuthority.containsKey(names[j])) { 10986 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10987 final String otherPackageName = 10988 ((other != null && other.getComponentName() != null) ? 10989 other.getComponentName().getPackageName() : "?"); 10990 throw new PackageManagerException( 10991 INSTALL_FAILED_CONFLICTING_PROVIDER, 10992 "Can't install because provider name " + names[j] 10993 + " (in package " + pkg.applicationInfo.packageName 10994 + ") is already used by " + otherPackageName); 10995 } 10996 } 10997 } 10998 } 10999 } 11000 11001 // Verify that packages sharing a user with a privileged app are marked as privileged. 11002 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11003 SharedUserSetting sharedUserSetting = null; 11004 try { 11005 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11006 } catch (PackageManagerException ignore) {} 11007 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11008 // Exempt SharedUsers signed with the platform key. 11009 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11010 if ((platformPkgSetting.signatures.mSigningDetails 11011 != PackageParser.SigningDetails.UNKNOWN) 11012 && (compareSignatures( 11013 platformPkgSetting.signatures.mSigningDetails.signatures, 11014 pkg.mSigningDetails.signatures) 11015 != PackageManager.SIGNATURE_MATCH)) { 11016 throw new PackageManagerException("Apps that share a user with a " + 11017 "privileged app must themselves be marked as privileged. " + 11018 pkg.packageName + " shares privileged user " + 11019 pkg.mSharedUserId + "."); 11020 } 11021 } 11022 } 11023 11024 // Apply policies specific for runtime resource overlays (RROs). 11025 if (pkg.mOverlayTarget != null) { 11026 // System overlays have some restrictions on their use of the 'static' state. 11027 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11028 // We are scanning a system overlay. This can be the first scan of the 11029 // system/vendor/oem partition, or an update to the system overlay. 11030 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11031 // This must be an update to a system overlay. 11032 final PackageSetting previousPkg = assertNotNull( 11033 mSettings.getPackageLPr(pkg.packageName), 11034 "previous package state not present"); 11035 11036 // Static overlays cannot be updated. 11037 if (previousPkg.pkg.mOverlayIsStatic) { 11038 throw new PackageManagerException("Overlay " + pkg.packageName + 11039 " is static and cannot be upgraded."); 11040 // Non-static overlays cannot be converted to static overlays. 11041 } else if (pkg.mOverlayIsStatic) { 11042 throw new PackageManagerException("Overlay " + pkg.packageName + 11043 " cannot be upgraded into a static overlay."); 11044 } 11045 } 11046 } else { 11047 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11048 if (pkg.mOverlayIsStatic) { 11049 throw new PackageManagerException("Overlay " + pkg.packageName + 11050 " is static but not pre-installed."); 11051 } 11052 11053 // The only case where we allow installation of a non-system overlay is when 11054 // its signature is signed with the platform certificate. 11055 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11056 if ((platformPkgSetting.signatures.mSigningDetails 11057 != PackageParser.SigningDetails.UNKNOWN) 11058 && (compareSignatures( 11059 platformPkgSetting.signatures.mSigningDetails.signatures, 11060 pkg.mSigningDetails.signatures) 11061 != PackageManager.SIGNATURE_MATCH)) { 11062 throw new PackageManagerException("Overlay " + pkg.packageName + 11063 " must be signed with the platform certificate."); 11064 } 11065 } 11066 } 11067 } 11068 } 11069 11070 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11071 int type, String declaringPackageName, long declaringVersionCode) { 11072 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11073 if (versionedLib == null) { 11074 versionedLib = new LongSparseArray<>(); 11075 mSharedLibraries.put(name, versionedLib); 11076 if (type == SharedLibraryInfo.TYPE_STATIC) { 11077 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11078 } 11079 } else if (versionedLib.indexOfKey(version) >= 0) { 11080 return false; 11081 } 11082 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11083 version, type, declaringPackageName, declaringVersionCode); 11084 versionedLib.put(version, libEntry); 11085 return true; 11086 } 11087 11088 private boolean removeSharedLibraryLPw(String name, long version) { 11089 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11090 if (versionedLib == null) { 11091 return false; 11092 } 11093 final int libIdx = versionedLib.indexOfKey(version); 11094 if (libIdx < 0) { 11095 return false; 11096 } 11097 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11098 versionedLib.remove(version); 11099 if (versionedLib.size() <= 0) { 11100 mSharedLibraries.remove(name); 11101 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11102 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11103 .getPackageName()); 11104 } 11105 } 11106 return true; 11107 } 11108 11109 /** 11110 * Adds a scanned package to the system. When this method is finished, the package will 11111 * be available for query, resolution, etc... 11112 */ 11113 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11114 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11115 final String pkgName = pkg.packageName; 11116 if (mCustomResolverComponentName != null && 11117 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11118 setUpCustomResolverActivity(pkg); 11119 } 11120 11121 if (pkg.packageName.equals("android")) { 11122 synchronized (mPackages) { 11123 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11124 // Set up information for our fall-back user intent resolution activity. 11125 mPlatformPackage = pkg; 11126 pkg.mVersionCode = mSdkVersion; 11127 pkg.mVersionCodeMajor = 0; 11128 mAndroidApplication = pkg.applicationInfo; 11129 if (!mResolverReplaced) { 11130 mResolveActivity.applicationInfo = mAndroidApplication; 11131 mResolveActivity.name = ResolverActivity.class.getName(); 11132 mResolveActivity.packageName = mAndroidApplication.packageName; 11133 mResolveActivity.processName = "system:ui"; 11134 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11135 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11136 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11137 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11138 mResolveActivity.exported = true; 11139 mResolveActivity.enabled = true; 11140 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11141 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11142 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11143 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11144 | ActivityInfo.CONFIG_ORIENTATION 11145 | ActivityInfo.CONFIG_KEYBOARD 11146 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11147 mResolveInfo.activityInfo = mResolveActivity; 11148 mResolveInfo.priority = 0; 11149 mResolveInfo.preferredOrder = 0; 11150 mResolveInfo.match = 0; 11151 mResolveComponentName = new ComponentName( 11152 mAndroidApplication.packageName, mResolveActivity.name); 11153 } 11154 } 11155 } 11156 } 11157 11158 ArrayList<PackageParser.Package> clientLibPkgs = null; 11159 // writer 11160 synchronized (mPackages) { 11161 boolean hasStaticSharedLibs = false; 11162 11163 // Any app can add new static shared libraries 11164 if (pkg.staticSharedLibName != null) { 11165 // Static shared libs don't allow renaming as they have synthetic package 11166 // names to allow install of multiple versions, so use name from manifest. 11167 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11168 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11169 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11170 hasStaticSharedLibs = true; 11171 } else { 11172 Slog.w(TAG, "Package " + pkg.packageName + " library " 11173 + pkg.staticSharedLibName + " already exists; skipping"); 11174 } 11175 // Static shared libs cannot be updated once installed since they 11176 // use synthetic package name which includes the version code, so 11177 // not need to update other packages's shared lib dependencies. 11178 } 11179 11180 if (!hasStaticSharedLibs 11181 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11182 // Only system apps can add new dynamic shared libraries. 11183 if (pkg.libraryNames != null) { 11184 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11185 String name = pkg.libraryNames.get(i); 11186 boolean allowed = false; 11187 if (pkg.isUpdatedSystemApp()) { 11188 // New library entries can only be added through the 11189 // system image. This is important to get rid of a lot 11190 // of nasty edge cases: for example if we allowed a non- 11191 // system update of the app to add a library, then uninstalling 11192 // the update would make the library go away, and assumptions 11193 // we made such as through app install filtering would now 11194 // have allowed apps on the device which aren't compatible 11195 // with it. Better to just have the restriction here, be 11196 // conservative, and create many fewer cases that can negatively 11197 // impact the user experience. 11198 final PackageSetting sysPs = mSettings 11199 .getDisabledSystemPkgLPr(pkg.packageName); 11200 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11201 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11202 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11203 allowed = true; 11204 break; 11205 } 11206 } 11207 } 11208 } else { 11209 allowed = true; 11210 } 11211 if (allowed) { 11212 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11213 SharedLibraryInfo.VERSION_UNDEFINED, 11214 SharedLibraryInfo.TYPE_DYNAMIC, 11215 pkg.packageName, pkg.getLongVersionCode())) { 11216 Slog.w(TAG, "Package " + pkg.packageName + " library " 11217 + name + " already exists; skipping"); 11218 } 11219 } else { 11220 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11221 + name + " that is not declared on system image; skipping"); 11222 } 11223 } 11224 11225 if ((scanFlags & SCAN_BOOTING) == 0) { 11226 // If we are not booting, we need to update any applications 11227 // that are clients of our shared library. If we are booting, 11228 // this will all be done once the scan is complete. 11229 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11230 } 11231 } 11232 } 11233 } 11234 11235 if ((scanFlags & SCAN_BOOTING) != 0) { 11236 // No apps can run during boot scan, so they don't need to be frozen 11237 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11238 // Caller asked to not kill app, so it's probably not frozen 11239 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11240 // Caller asked us to ignore frozen check for some reason; they 11241 // probably didn't know the package name 11242 } else { 11243 // We're doing major surgery on this package, so it better be frozen 11244 // right now to keep it from launching 11245 checkPackageFrozen(pkgName); 11246 } 11247 11248 // Also need to kill any apps that are dependent on the library. 11249 if (clientLibPkgs != null) { 11250 for (int i=0; i<clientLibPkgs.size(); i++) { 11251 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11252 killApplication(clientPkg.applicationInfo.packageName, 11253 clientPkg.applicationInfo.uid, "update lib"); 11254 } 11255 } 11256 11257 // writer 11258 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11259 11260 synchronized (mPackages) { 11261 // We don't expect installation to fail beyond this point 11262 11263 // Add the new setting to mSettings 11264 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11265 // Add the new setting to mPackages 11266 mPackages.put(pkg.applicationInfo.packageName, pkg); 11267 // Make sure we don't accidentally delete its data. 11268 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11269 while (iter.hasNext()) { 11270 PackageCleanItem item = iter.next(); 11271 if (pkgName.equals(item.packageName)) { 11272 iter.remove(); 11273 } 11274 } 11275 11276 // Add the package's KeySets to the global KeySetManagerService 11277 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11278 ksms.addScannedPackageLPw(pkg); 11279 11280 int N = pkg.providers.size(); 11281 StringBuilder r = null; 11282 int i; 11283 for (i=0; i<N; i++) { 11284 PackageParser.Provider p = pkg.providers.get(i); 11285 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11286 p.info.processName); 11287 mProviders.addProvider(p); 11288 p.syncable = p.info.isSyncable; 11289 if (p.info.authority != null) { 11290 String names[] = p.info.authority.split(";"); 11291 p.info.authority = null; 11292 for (int j = 0; j < names.length; j++) { 11293 if (j == 1 && p.syncable) { 11294 // We only want the first authority for a provider to possibly be 11295 // syncable, so if we already added this provider using a different 11296 // authority clear the syncable flag. We copy the provider before 11297 // changing it because the mProviders object contains a reference 11298 // to a provider that we don't want to change. 11299 // Only do this for the second authority since the resulting provider 11300 // object can be the same for all future authorities for this provider. 11301 p = new PackageParser.Provider(p); 11302 p.syncable = false; 11303 } 11304 if (!mProvidersByAuthority.containsKey(names[j])) { 11305 mProvidersByAuthority.put(names[j], p); 11306 if (p.info.authority == null) { 11307 p.info.authority = names[j]; 11308 } else { 11309 p.info.authority = p.info.authority + ";" + names[j]; 11310 } 11311 if (DEBUG_PACKAGE_SCANNING) { 11312 if (chatty) 11313 Log.d(TAG, "Registered content provider: " + names[j] 11314 + ", className = " + p.info.name + ", isSyncable = " 11315 + p.info.isSyncable); 11316 } 11317 } else { 11318 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11319 Slog.w(TAG, "Skipping provider name " + names[j] + 11320 " (in package " + pkg.applicationInfo.packageName + 11321 "): name already used by " 11322 + ((other != null && other.getComponentName() != null) 11323 ? other.getComponentName().getPackageName() : "?")); 11324 } 11325 } 11326 } 11327 if (chatty) { 11328 if (r == null) { 11329 r = new StringBuilder(256); 11330 } else { 11331 r.append(' '); 11332 } 11333 r.append(p.info.name); 11334 } 11335 } 11336 if (r != null) { 11337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11338 } 11339 11340 N = pkg.services.size(); 11341 r = null; 11342 for (i=0; i<N; i++) { 11343 PackageParser.Service s = pkg.services.get(i); 11344 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11345 s.info.processName); 11346 mServices.addService(s); 11347 if (chatty) { 11348 if (r == null) { 11349 r = new StringBuilder(256); 11350 } else { 11351 r.append(' '); 11352 } 11353 r.append(s.info.name); 11354 } 11355 } 11356 if (r != null) { 11357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11358 } 11359 11360 N = pkg.receivers.size(); 11361 r = null; 11362 for (i=0; i<N; i++) { 11363 PackageParser.Activity a = pkg.receivers.get(i); 11364 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11365 a.info.processName); 11366 mReceivers.addActivity(a, "receiver"); 11367 if (chatty) { 11368 if (r == null) { 11369 r = new StringBuilder(256); 11370 } else { 11371 r.append(' '); 11372 } 11373 r.append(a.info.name); 11374 } 11375 } 11376 if (r != null) { 11377 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11378 } 11379 11380 N = pkg.activities.size(); 11381 r = null; 11382 for (i=0; i<N; i++) { 11383 PackageParser.Activity a = pkg.activities.get(i); 11384 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11385 a.info.processName); 11386 mActivities.addActivity(a, "activity"); 11387 if (chatty) { 11388 if (r == null) { 11389 r = new StringBuilder(256); 11390 } else { 11391 r.append(' '); 11392 } 11393 r.append(a.info.name); 11394 } 11395 } 11396 if (r != null) { 11397 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11398 } 11399 11400 // Don't allow ephemeral applications to define new permissions groups. 11401 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11402 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11403 + " ignored: instant apps cannot define new permission groups."); 11404 } else { 11405 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11406 } 11407 11408 // Don't allow ephemeral applications to define new permissions. 11409 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11410 Slog.w(TAG, "Permissions from package " + pkg.packageName 11411 + " ignored: instant apps cannot define new permissions."); 11412 } else { 11413 mPermissionManager.addAllPermissions(pkg, chatty); 11414 } 11415 11416 N = pkg.instrumentation.size(); 11417 r = null; 11418 for (i=0; i<N; i++) { 11419 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11420 a.info.packageName = pkg.applicationInfo.packageName; 11421 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11422 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11423 a.info.splitNames = pkg.splitNames; 11424 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11425 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11426 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11427 a.info.dataDir = pkg.applicationInfo.dataDir; 11428 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11429 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11430 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11431 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11432 mInstrumentation.put(a.getComponentName(), a); 11433 if (chatty) { 11434 if (r == null) { 11435 r = new StringBuilder(256); 11436 } else { 11437 r.append(' '); 11438 } 11439 r.append(a.info.name); 11440 } 11441 } 11442 if (r != null) { 11443 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11444 } 11445 11446 if (pkg.protectedBroadcasts != null) { 11447 N = pkg.protectedBroadcasts.size(); 11448 synchronized (mProtectedBroadcasts) { 11449 for (i = 0; i < N; i++) { 11450 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11451 } 11452 } 11453 } 11454 } 11455 11456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11457 } 11458 11459 /** 11460 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11461 * is derived purely on the basis of the contents of {@code scanFile} and 11462 * {@code cpuAbiOverride}. 11463 * 11464 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11465 */ 11466 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11467 boolean extractLibs) 11468 throws PackageManagerException { 11469 // Give ourselves some initial paths; we'll come back for another 11470 // pass once we've determined ABI below. 11471 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11472 11473 // We would never need to extract libs for forward-locked and external packages, 11474 // since the container service will do it for us. We shouldn't attempt to 11475 // extract libs from system app when it was not updated. 11476 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11477 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11478 extractLibs = false; 11479 } 11480 11481 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11482 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11483 11484 NativeLibraryHelper.Handle handle = null; 11485 try { 11486 handle = NativeLibraryHelper.Handle.create(pkg); 11487 // TODO(multiArch): This can be null for apps that didn't go through the 11488 // usual installation process. We can calculate it again, like we 11489 // do during install time. 11490 // 11491 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11492 // unnecessary. 11493 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11494 11495 // Null out the abis so that they can be recalculated. 11496 pkg.applicationInfo.primaryCpuAbi = null; 11497 pkg.applicationInfo.secondaryCpuAbi = null; 11498 if (isMultiArch(pkg.applicationInfo)) { 11499 // Warn if we've set an abiOverride for multi-lib packages.. 11500 // By definition, we need to copy both 32 and 64 bit libraries for 11501 // such packages. 11502 if (pkg.cpuAbiOverride != null 11503 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11504 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11505 } 11506 11507 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11508 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11509 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11510 if (extractLibs) { 11511 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11512 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11513 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11514 useIsaSpecificSubdirs); 11515 } else { 11516 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11517 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11518 } 11519 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11520 } 11521 11522 // Shared library native code should be in the APK zip aligned 11523 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11524 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11525 "Shared library native lib extraction not supported"); 11526 } 11527 11528 maybeThrowExceptionForMultiArchCopy( 11529 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11530 11531 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11532 if (extractLibs) { 11533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11534 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11535 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11536 useIsaSpecificSubdirs); 11537 } else { 11538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11539 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11540 } 11541 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11542 } 11543 11544 maybeThrowExceptionForMultiArchCopy( 11545 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11546 11547 if (abi64 >= 0) { 11548 // Shared library native libs should be in the APK zip aligned 11549 if (extractLibs && pkg.isLibrary()) { 11550 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11551 "Shared library native lib extraction not supported"); 11552 } 11553 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11554 } 11555 11556 if (abi32 >= 0) { 11557 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11558 if (abi64 >= 0) { 11559 if (pkg.use32bitAbi) { 11560 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11561 pkg.applicationInfo.primaryCpuAbi = abi; 11562 } else { 11563 pkg.applicationInfo.secondaryCpuAbi = abi; 11564 } 11565 } else { 11566 pkg.applicationInfo.primaryCpuAbi = abi; 11567 } 11568 } 11569 } else { 11570 String[] abiList = (cpuAbiOverride != null) ? 11571 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11572 11573 // Enable gross and lame hacks for apps that are built with old 11574 // SDK tools. We must scan their APKs for renderscript bitcode and 11575 // not launch them if it's present. Don't bother checking on devices 11576 // that don't have 64 bit support. 11577 boolean needsRenderScriptOverride = false; 11578 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11579 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11580 abiList = Build.SUPPORTED_32_BIT_ABIS; 11581 needsRenderScriptOverride = true; 11582 } 11583 11584 final int copyRet; 11585 if (extractLibs) { 11586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11587 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11588 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11589 } else { 11590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11591 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11592 } 11593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11594 11595 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11596 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11597 "Error unpackaging native libs for app, errorCode=" + copyRet); 11598 } 11599 11600 if (copyRet >= 0) { 11601 // Shared libraries that have native libs must be multi-architecture 11602 if (pkg.isLibrary()) { 11603 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11604 "Shared library with native libs must be multiarch"); 11605 } 11606 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11607 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11608 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11609 } else if (needsRenderScriptOverride) { 11610 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11611 } 11612 } 11613 } catch (IOException ioe) { 11614 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11615 } finally { 11616 IoUtils.closeQuietly(handle); 11617 } 11618 11619 // Now that we've calculated the ABIs and determined if it's an internal app, 11620 // we will go ahead and populate the nativeLibraryPath. 11621 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11622 } 11623 11624 /** 11625 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11626 * i.e, so that all packages can be run inside a single process if required. 11627 * 11628 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11629 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11630 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11631 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11632 * updating a package that belongs to a shared user. 11633 * 11634 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11635 * adds unnecessary complexity. 11636 */ 11637 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11638 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11639 List<String> changedAbiCodePath = null; 11640 String requiredInstructionSet = null; 11641 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11642 requiredInstructionSet = VMRuntime.getInstructionSet( 11643 scannedPackage.applicationInfo.primaryCpuAbi); 11644 } 11645 11646 PackageSetting requirer = null; 11647 for (PackageSetting ps : packagesForUser) { 11648 // If packagesForUser contains scannedPackage, we skip it. This will happen 11649 // when scannedPackage is an update of an existing package. Without this check, 11650 // we will never be able to change the ABI of any package belonging to a shared 11651 // user, even if it's compatible with other packages. 11652 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11653 if (ps.primaryCpuAbiString == null) { 11654 continue; 11655 } 11656 11657 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11658 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11659 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11660 // this but there's not much we can do. 11661 String errorMessage = "Instruction set mismatch, " 11662 + ((requirer == null) ? "[caller]" : requirer) 11663 + " requires " + requiredInstructionSet + " whereas " + ps 11664 + " requires " + instructionSet; 11665 Slog.w(TAG, errorMessage); 11666 } 11667 11668 if (requiredInstructionSet == null) { 11669 requiredInstructionSet = instructionSet; 11670 requirer = ps; 11671 } 11672 } 11673 } 11674 11675 if (requiredInstructionSet != null) { 11676 String adjustedAbi; 11677 if (requirer != null) { 11678 // requirer != null implies that either scannedPackage was null or that scannedPackage 11679 // did not require an ABI, in which case we have to adjust scannedPackage to match 11680 // the ABI of the set (which is the same as requirer's ABI) 11681 adjustedAbi = requirer.primaryCpuAbiString; 11682 if (scannedPackage != null) { 11683 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11684 } 11685 } else { 11686 // requirer == null implies that we're updating all ABIs in the set to 11687 // match scannedPackage. 11688 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11689 } 11690 11691 for (PackageSetting ps : packagesForUser) { 11692 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11693 if (ps.primaryCpuAbiString != null) { 11694 continue; 11695 } 11696 11697 ps.primaryCpuAbiString = adjustedAbi; 11698 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11699 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11700 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11701 if (DEBUG_ABI_SELECTION) { 11702 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11703 + " (requirer=" 11704 + (requirer != null ? requirer.pkg : "null") 11705 + ", scannedPackage=" 11706 + (scannedPackage != null ? scannedPackage : "null") 11707 + ")"); 11708 } 11709 if (changedAbiCodePath == null) { 11710 changedAbiCodePath = new ArrayList<>(); 11711 } 11712 changedAbiCodePath.add(ps.codePathString); 11713 } 11714 } 11715 } 11716 } 11717 return changedAbiCodePath; 11718 } 11719 11720 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11721 synchronized (mPackages) { 11722 mResolverReplaced = true; 11723 // Set up information for custom user intent resolution activity. 11724 mResolveActivity.applicationInfo = pkg.applicationInfo; 11725 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11726 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11727 mResolveActivity.processName = pkg.applicationInfo.packageName; 11728 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11729 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11730 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11731 mResolveActivity.theme = 0; 11732 mResolveActivity.exported = true; 11733 mResolveActivity.enabled = true; 11734 mResolveInfo.activityInfo = mResolveActivity; 11735 mResolveInfo.priority = 0; 11736 mResolveInfo.preferredOrder = 0; 11737 mResolveInfo.match = 0; 11738 mResolveComponentName = mCustomResolverComponentName; 11739 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11740 mResolveComponentName); 11741 } 11742 } 11743 11744 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11745 if (installerActivity == null) { 11746 if (DEBUG_EPHEMERAL) { 11747 Slog.d(TAG, "Clear ephemeral installer activity"); 11748 } 11749 mInstantAppInstallerActivity = null; 11750 return; 11751 } 11752 11753 if (DEBUG_EPHEMERAL) { 11754 Slog.d(TAG, "Set ephemeral installer activity: " 11755 + installerActivity.getComponentName()); 11756 } 11757 // Set up information for ephemeral installer activity 11758 mInstantAppInstallerActivity = installerActivity; 11759 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11760 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11761 mInstantAppInstallerActivity.exported = true; 11762 mInstantAppInstallerActivity.enabled = true; 11763 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11764 mInstantAppInstallerInfo.priority = 0; 11765 mInstantAppInstallerInfo.preferredOrder = 1; 11766 mInstantAppInstallerInfo.isDefault = true; 11767 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11768 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11769 } 11770 11771 private static String calculateBundledApkRoot(final String codePathString) { 11772 final File codePath = new File(codePathString); 11773 final File codeRoot; 11774 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11775 codeRoot = Environment.getRootDirectory(); 11776 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11777 codeRoot = Environment.getOemDirectory(); 11778 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11779 codeRoot = Environment.getVendorDirectory(); 11780 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11781 codeRoot = Environment.getProductDirectory(); 11782 } else { 11783 // Unrecognized code path; take its top real segment as the apk root: 11784 // e.g. /something/app/blah.apk => /something 11785 try { 11786 File f = codePath.getCanonicalFile(); 11787 File parent = f.getParentFile(); // non-null because codePath is a file 11788 File tmp; 11789 while ((tmp = parent.getParentFile()) != null) { 11790 f = parent; 11791 parent = tmp; 11792 } 11793 codeRoot = f; 11794 Slog.w(TAG, "Unrecognized code path " 11795 + codePath + " - using " + codeRoot); 11796 } catch (IOException e) { 11797 // Can't canonicalize the code path -- shenanigans? 11798 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11799 return Environment.getRootDirectory().getPath(); 11800 } 11801 } 11802 return codeRoot.getPath(); 11803 } 11804 11805 /** 11806 * Derive and set the location of native libraries for the given package, 11807 * which varies depending on where and how the package was installed. 11808 */ 11809 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11810 final ApplicationInfo info = pkg.applicationInfo; 11811 final String codePath = pkg.codePath; 11812 final File codeFile = new File(codePath); 11813 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11814 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11815 11816 info.nativeLibraryRootDir = null; 11817 info.nativeLibraryRootRequiresIsa = false; 11818 info.nativeLibraryDir = null; 11819 info.secondaryNativeLibraryDir = null; 11820 11821 if (isApkFile(codeFile)) { 11822 // Monolithic install 11823 if (bundledApp) { 11824 // If "/system/lib64/apkname" exists, assume that is the per-package 11825 // native library directory to use; otherwise use "/system/lib/apkname". 11826 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11827 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11828 getPrimaryInstructionSet(info)); 11829 11830 // This is a bundled system app so choose the path based on the ABI. 11831 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11832 // is just the default path. 11833 final String apkName = deriveCodePathName(codePath); 11834 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11835 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11836 apkName).getAbsolutePath(); 11837 11838 if (info.secondaryCpuAbi != null) { 11839 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11840 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11841 secondaryLibDir, apkName).getAbsolutePath(); 11842 } 11843 } else if (asecApp) { 11844 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11845 .getAbsolutePath(); 11846 } else { 11847 final String apkName = deriveCodePathName(codePath); 11848 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11849 .getAbsolutePath(); 11850 } 11851 11852 info.nativeLibraryRootRequiresIsa = false; 11853 info.nativeLibraryDir = info.nativeLibraryRootDir; 11854 } else { 11855 // Cluster install 11856 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11857 info.nativeLibraryRootRequiresIsa = true; 11858 11859 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11860 getPrimaryInstructionSet(info)).getAbsolutePath(); 11861 11862 if (info.secondaryCpuAbi != null) { 11863 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11864 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11865 } 11866 } 11867 } 11868 11869 /** 11870 * Calculate the abis and roots for a bundled app. These can uniquely 11871 * be determined from the contents of the system partition, i.e whether 11872 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11873 * of this information, and instead assume that the system was built 11874 * sensibly. 11875 */ 11876 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11877 PackageSetting pkgSetting) { 11878 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11879 11880 // If "/system/lib64/apkname" exists, assume that is the per-package 11881 // native library directory to use; otherwise use "/system/lib/apkname". 11882 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11883 setBundledAppAbi(pkg, apkRoot, apkName); 11884 // pkgSetting might be null during rescan following uninstall of updates 11885 // to a bundled app, so accommodate that possibility. The settings in 11886 // that case will be established later from the parsed package. 11887 // 11888 // If the settings aren't null, sync them up with what we've just derived. 11889 // note that apkRoot isn't stored in the package settings. 11890 if (pkgSetting != null) { 11891 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11892 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11893 } 11894 } 11895 11896 /** 11897 * Deduces the ABI of a bundled app and sets the relevant fields on the 11898 * parsed pkg object. 11899 * 11900 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11901 * under which system libraries are installed. 11902 * @param apkName the name of the installed package. 11903 */ 11904 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11905 final File codeFile = new File(pkg.codePath); 11906 11907 final boolean has64BitLibs; 11908 final boolean has32BitLibs; 11909 if (isApkFile(codeFile)) { 11910 // Monolithic install 11911 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11912 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11913 } else { 11914 // Cluster install 11915 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11916 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11917 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11918 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11919 has64BitLibs = (new File(rootDir, isa)).exists(); 11920 } else { 11921 has64BitLibs = false; 11922 } 11923 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11924 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11925 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11926 has32BitLibs = (new File(rootDir, isa)).exists(); 11927 } else { 11928 has32BitLibs = false; 11929 } 11930 } 11931 11932 if (has64BitLibs && !has32BitLibs) { 11933 // The package has 64 bit libs, but not 32 bit libs. Its primary 11934 // ABI should be 64 bit. We can safely assume here that the bundled 11935 // native libraries correspond to the most preferred ABI in the list. 11936 11937 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11938 pkg.applicationInfo.secondaryCpuAbi = null; 11939 } else if (has32BitLibs && !has64BitLibs) { 11940 // The package has 32 bit libs but not 64 bit libs. Its primary 11941 // ABI should be 32 bit. 11942 11943 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11944 pkg.applicationInfo.secondaryCpuAbi = null; 11945 } else if (has32BitLibs && has64BitLibs) { 11946 // The application has both 64 and 32 bit bundled libraries. We check 11947 // here that the app declares multiArch support, and warn if it doesn't. 11948 // 11949 // We will be lenient here and record both ABIs. The primary will be the 11950 // ABI that's higher on the list, i.e, a device that's configured to prefer 11951 // 64 bit apps will see a 64 bit primary ABI, 11952 11953 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11954 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11955 } 11956 11957 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11958 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11959 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11960 } else { 11961 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11962 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11963 } 11964 } else { 11965 pkg.applicationInfo.primaryCpuAbi = null; 11966 pkg.applicationInfo.secondaryCpuAbi = null; 11967 } 11968 } 11969 11970 private void killApplication(String pkgName, int appId, String reason) { 11971 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11972 } 11973 11974 private void killApplication(String pkgName, int appId, int userId, String reason) { 11975 // Request the ActivityManager to kill the process(only for existing packages) 11976 // so that we do not end up in a confused state while the user is still using the older 11977 // version of the application while the new one gets installed. 11978 final long token = Binder.clearCallingIdentity(); 11979 try { 11980 IActivityManager am = ActivityManager.getService(); 11981 if (am != null) { 11982 try { 11983 am.killApplication(pkgName, appId, userId, reason); 11984 } catch (RemoteException e) { 11985 } 11986 } 11987 } finally { 11988 Binder.restoreCallingIdentity(token); 11989 } 11990 } 11991 11992 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11993 // Remove the parent package setting 11994 PackageSetting ps = (PackageSetting) pkg.mExtras; 11995 if (ps != null) { 11996 removePackageLI(ps, chatty); 11997 } 11998 // Remove the child package setting 11999 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12000 for (int i = 0; i < childCount; i++) { 12001 PackageParser.Package childPkg = pkg.childPackages.get(i); 12002 ps = (PackageSetting) childPkg.mExtras; 12003 if (ps != null) { 12004 removePackageLI(ps, chatty); 12005 } 12006 } 12007 } 12008 12009 void removePackageLI(PackageSetting ps, boolean chatty) { 12010 if (DEBUG_INSTALL) { 12011 if (chatty) 12012 Log.d(TAG, "Removing package " + ps.name); 12013 } 12014 12015 // writer 12016 synchronized (mPackages) { 12017 mPackages.remove(ps.name); 12018 final PackageParser.Package pkg = ps.pkg; 12019 if (pkg != null) { 12020 cleanPackageDataStructuresLILPw(pkg, chatty); 12021 } 12022 } 12023 } 12024 12025 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12026 if (DEBUG_INSTALL) { 12027 if (chatty) 12028 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12029 } 12030 12031 // writer 12032 synchronized (mPackages) { 12033 // Remove the parent package 12034 mPackages.remove(pkg.applicationInfo.packageName); 12035 cleanPackageDataStructuresLILPw(pkg, chatty); 12036 12037 // Remove the child packages 12038 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12039 for (int i = 0; i < childCount; i++) { 12040 PackageParser.Package childPkg = pkg.childPackages.get(i); 12041 mPackages.remove(childPkg.applicationInfo.packageName); 12042 cleanPackageDataStructuresLILPw(childPkg, chatty); 12043 } 12044 } 12045 } 12046 12047 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12048 int N = pkg.providers.size(); 12049 StringBuilder r = null; 12050 int i; 12051 for (i=0; i<N; i++) { 12052 PackageParser.Provider p = pkg.providers.get(i); 12053 mProviders.removeProvider(p); 12054 if (p.info.authority == null) { 12055 12056 /* There was another ContentProvider with this authority when 12057 * this app was installed so this authority is null, 12058 * Ignore it as we don't have to unregister the provider. 12059 */ 12060 continue; 12061 } 12062 String names[] = p.info.authority.split(";"); 12063 for (int j = 0; j < names.length; j++) { 12064 if (mProvidersByAuthority.get(names[j]) == p) { 12065 mProvidersByAuthority.remove(names[j]); 12066 if (DEBUG_REMOVE) { 12067 if (chatty) 12068 Log.d(TAG, "Unregistered content provider: " + names[j] 12069 + ", className = " + p.info.name + ", isSyncable = " 12070 + p.info.isSyncable); 12071 } 12072 } 12073 } 12074 if (DEBUG_REMOVE && chatty) { 12075 if (r == null) { 12076 r = new StringBuilder(256); 12077 } else { 12078 r.append(' '); 12079 } 12080 r.append(p.info.name); 12081 } 12082 } 12083 if (r != null) { 12084 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12085 } 12086 12087 N = pkg.services.size(); 12088 r = null; 12089 for (i=0; i<N; i++) { 12090 PackageParser.Service s = pkg.services.get(i); 12091 mServices.removeService(s); 12092 if (chatty) { 12093 if (r == null) { 12094 r = new StringBuilder(256); 12095 } else { 12096 r.append(' '); 12097 } 12098 r.append(s.info.name); 12099 } 12100 } 12101 if (r != null) { 12102 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12103 } 12104 12105 N = pkg.receivers.size(); 12106 r = null; 12107 for (i=0; i<N; i++) { 12108 PackageParser.Activity a = pkg.receivers.get(i); 12109 mReceivers.removeActivity(a, "receiver"); 12110 if (DEBUG_REMOVE && chatty) { 12111 if (r == null) { 12112 r = new StringBuilder(256); 12113 } else { 12114 r.append(' '); 12115 } 12116 r.append(a.info.name); 12117 } 12118 } 12119 if (r != null) { 12120 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12121 } 12122 12123 N = pkg.activities.size(); 12124 r = null; 12125 for (i=0; i<N; i++) { 12126 PackageParser.Activity a = pkg.activities.get(i); 12127 mActivities.removeActivity(a, "activity"); 12128 if (DEBUG_REMOVE && chatty) { 12129 if (r == null) { 12130 r = new StringBuilder(256); 12131 } else { 12132 r.append(' '); 12133 } 12134 r.append(a.info.name); 12135 } 12136 } 12137 if (r != null) { 12138 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12139 } 12140 12141 mPermissionManager.removeAllPermissions(pkg, chatty); 12142 12143 N = pkg.instrumentation.size(); 12144 r = null; 12145 for (i=0; i<N; i++) { 12146 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12147 mInstrumentation.remove(a.getComponentName()); 12148 if (DEBUG_REMOVE && chatty) { 12149 if (r == null) { 12150 r = new StringBuilder(256); 12151 } else { 12152 r.append(' '); 12153 } 12154 r.append(a.info.name); 12155 } 12156 } 12157 if (r != null) { 12158 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12159 } 12160 12161 r = null; 12162 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12163 // Only system apps can hold shared libraries. 12164 if (pkg.libraryNames != null) { 12165 for (i = 0; i < pkg.libraryNames.size(); i++) { 12166 String name = pkg.libraryNames.get(i); 12167 if (removeSharedLibraryLPw(name, 0)) { 12168 if (DEBUG_REMOVE && chatty) { 12169 if (r == null) { 12170 r = new StringBuilder(256); 12171 } else { 12172 r.append(' '); 12173 } 12174 r.append(name); 12175 } 12176 } 12177 } 12178 } 12179 } 12180 12181 r = null; 12182 12183 // Any package can hold static shared libraries. 12184 if (pkg.staticSharedLibName != null) { 12185 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12186 if (DEBUG_REMOVE && chatty) { 12187 if (r == null) { 12188 r = new StringBuilder(256); 12189 } else { 12190 r.append(' '); 12191 } 12192 r.append(pkg.staticSharedLibName); 12193 } 12194 } 12195 } 12196 12197 if (r != null) { 12198 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12199 } 12200 } 12201 12202 12203 final class ActivityIntentResolver 12204 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12205 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12206 boolean defaultOnly, int userId) { 12207 if (!sUserManager.exists(userId)) return null; 12208 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12209 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12210 } 12211 12212 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12213 int userId) { 12214 if (!sUserManager.exists(userId)) return null; 12215 mFlags = flags; 12216 return super.queryIntent(intent, resolvedType, 12217 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12218 userId); 12219 } 12220 12221 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12222 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12223 if (!sUserManager.exists(userId)) return null; 12224 if (packageActivities == null) { 12225 return null; 12226 } 12227 mFlags = flags; 12228 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12229 final int N = packageActivities.size(); 12230 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12231 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12232 12233 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12234 for (int i = 0; i < N; ++i) { 12235 intentFilters = packageActivities.get(i).intents; 12236 if (intentFilters != null && intentFilters.size() > 0) { 12237 PackageParser.ActivityIntentInfo[] array = 12238 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12239 intentFilters.toArray(array); 12240 listCut.add(array); 12241 } 12242 } 12243 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12244 } 12245 12246 /** 12247 * Finds a privileged activity that matches the specified activity names. 12248 */ 12249 private PackageParser.Activity findMatchingActivity( 12250 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12251 for (PackageParser.Activity sysActivity : activityList) { 12252 if (sysActivity.info.name.equals(activityInfo.name)) { 12253 return sysActivity; 12254 } 12255 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12256 return sysActivity; 12257 } 12258 if (sysActivity.info.targetActivity != null) { 12259 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12260 return sysActivity; 12261 } 12262 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12263 return sysActivity; 12264 } 12265 } 12266 } 12267 return null; 12268 } 12269 12270 public class IterGenerator<E> { 12271 public Iterator<E> generate(ActivityIntentInfo info) { 12272 return null; 12273 } 12274 } 12275 12276 public class ActionIterGenerator extends IterGenerator<String> { 12277 @Override 12278 public Iterator<String> generate(ActivityIntentInfo info) { 12279 return info.actionsIterator(); 12280 } 12281 } 12282 12283 public class CategoriesIterGenerator extends IterGenerator<String> { 12284 @Override 12285 public Iterator<String> generate(ActivityIntentInfo info) { 12286 return info.categoriesIterator(); 12287 } 12288 } 12289 12290 public class SchemesIterGenerator extends IterGenerator<String> { 12291 @Override 12292 public Iterator<String> generate(ActivityIntentInfo info) { 12293 return info.schemesIterator(); 12294 } 12295 } 12296 12297 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12298 @Override 12299 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12300 return info.authoritiesIterator(); 12301 } 12302 } 12303 12304 /** 12305 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12306 * MODIFIED. Do not pass in a list that should not be changed. 12307 */ 12308 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12309 IterGenerator<T> generator, Iterator<T> searchIterator) { 12310 // loop through the set of actions; every one must be found in the intent filter 12311 while (searchIterator.hasNext()) { 12312 // we must have at least one filter in the list to consider a match 12313 if (intentList.size() == 0) { 12314 break; 12315 } 12316 12317 final T searchAction = searchIterator.next(); 12318 12319 // loop through the set of intent filters 12320 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12321 while (intentIter.hasNext()) { 12322 final ActivityIntentInfo intentInfo = intentIter.next(); 12323 boolean selectionFound = false; 12324 12325 // loop through the intent filter's selection criteria; at least one 12326 // of them must match the searched criteria 12327 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12328 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12329 final T intentSelection = intentSelectionIter.next(); 12330 if (intentSelection != null && intentSelection.equals(searchAction)) { 12331 selectionFound = true; 12332 break; 12333 } 12334 } 12335 12336 // the selection criteria wasn't found in this filter's set; this filter 12337 // is not a potential match 12338 if (!selectionFound) { 12339 intentIter.remove(); 12340 } 12341 } 12342 } 12343 } 12344 12345 private boolean isProtectedAction(ActivityIntentInfo filter) { 12346 final Iterator<String> actionsIter = filter.actionsIterator(); 12347 while (actionsIter != null && actionsIter.hasNext()) { 12348 final String filterAction = actionsIter.next(); 12349 if (PROTECTED_ACTIONS.contains(filterAction)) { 12350 return true; 12351 } 12352 } 12353 return false; 12354 } 12355 12356 /** 12357 * Adjusts the priority of the given intent filter according to policy. 12358 * <p> 12359 * <ul> 12360 * <li>The priority for non privileged applications is capped to '0'</li> 12361 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12362 * <li>The priority for unbundled updates to privileged applications is capped to the 12363 * priority defined on the system partition</li> 12364 * </ul> 12365 * <p> 12366 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12367 * allowed to obtain any priority on any action. 12368 */ 12369 private void adjustPriority( 12370 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12371 // nothing to do; priority is fine as-is 12372 if (intent.getPriority() <= 0) { 12373 return; 12374 } 12375 12376 final ActivityInfo activityInfo = intent.activity.info; 12377 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12378 12379 final boolean privilegedApp = 12380 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12381 if (!privilegedApp) { 12382 // non-privileged applications can never define a priority >0 12383 if (DEBUG_FILTERS) { 12384 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12385 + " package: " + applicationInfo.packageName 12386 + " activity: " + intent.activity.className 12387 + " origPrio: " + intent.getPriority()); 12388 } 12389 intent.setPriority(0); 12390 return; 12391 } 12392 12393 if (systemActivities == null) { 12394 // the system package is not disabled; we're parsing the system partition 12395 if (isProtectedAction(intent)) { 12396 if (mDeferProtectedFilters) { 12397 // We can't deal with these just yet. No component should ever obtain a 12398 // >0 priority for a protected actions, with ONE exception -- the setup 12399 // wizard. The setup wizard, however, cannot be known until we're able to 12400 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12401 // until all intent filters have been processed. Chicken, meet egg. 12402 // Let the filter temporarily have a high priority and rectify the 12403 // priorities after all system packages have been scanned. 12404 mProtectedFilters.add(intent); 12405 if (DEBUG_FILTERS) { 12406 Slog.i(TAG, "Protected action; save for later;" 12407 + " package: " + applicationInfo.packageName 12408 + " activity: " + intent.activity.className 12409 + " origPrio: " + intent.getPriority()); 12410 } 12411 return; 12412 } else { 12413 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12414 Slog.i(TAG, "No setup wizard;" 12415 + " All protected intents capped to priority 0"); 12416 } 12417 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12418 if (DEBUG_FILTERS) { 12419 Slog.i(TAG, "Found setup wizard;" 12420 + " allow priority " + intent.getPriority() + ";" 12421 + " package: " + intent.activity.info.packageName 12422 + " activity: " + intent.activity.className 12423 + " priority: " + intent.getPriority()); 12424 } 12425 // setup wizard gets whatever it wants 12426 return; 12427 } 12428 if (DEBUG_FILTERS) { 12429 Slog.i(TAG, "Protected action; cap priority to 0;" 12430 + " package: " + intent.activity.info.packageName 12431 + " activity: " + intent.activity.className 12432 + " origPrio: " + intent.getPriority()); 12433 } 12434 intent.setPriority(0); 12435 return; 12436 } 12437 } 12438 // privileged apps on the system image get whatever priority they request 12439 return; 12440 } 12441 12442 // privileged app unbundled update ... try to find the same activity 12443 final PackageParser.Activity foundActivity = 12444 findMatchingActivity(systemActivities, activityInfo); 12445 if (foundActivity == null) { 12446 // this is a new activity; it cannot obtain >0 priority 12447 if (DEBUG_FILTERS) { 12448 Slog.i(TAG, "New activity; cap priority to 0;" 12449 + " package: " + applicationInfo.packageName 12450 + " activity: " + intent.activity.className 12451 + " origPrio: " + intent.getPriority()); 12452 } 12453 intent.setPriority(0); 12454 return; 12455 } 12456 12457 // found activity, now check for filter equivalence 12458 12459 // a shallow copy is enough; we modify the list, not its contents 12460 final List<ActivityIntentInfo> intentListCopy = 12461 new ArrayList<>(foundActivity.intents); 12462 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12463 12464 // find matching action subsets 12465 final Iterator<String> actionsIterator = intent.actionsIterator(); 12466 if (actionsIterator != null) { 12467 getIntentListSubset( 12468 intentListCopy, new ActionIterGenerator(), actionsIterator); 12469 if (intentListCopy.size() == 0) { 12470 // no more intents to match; we're not equivalent 12471 if (DEBUG_FILTERS) { 12472 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12473 + " package: " + applicationInfo.packageName 12474 + " activity: " + intent.activity.className 12475 + " origPrio: " + intent.getPriority()); 12476 } 12477 intent.setPriority(0); 12478 return; 12479 } 12480 } 12481 12482 // find matching category subsets 12483 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12484 if (categoriesIterator != null) { 12485 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12486 categoriesIterator); 12487 if (intentListCopy.size() == 0) { 12488 // no more intents to match; we're not equivalent 12489 if (DEBUG_FILTERS) { 12490 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12491 + " package: " + applicationInfo.packageName 12492 + " activity: " + intent.activity.className 12493 + " origPrio: " + intent.getPriority()); 12494 } 12495 intent.setPriority(0); 12496 return; 12497 } 12498 } 12499 12500 // find matching schemes subsets 12501 final Iterator<String> schemesIterator = intent.schemesIterator(); 12502 if (schemesIterator != null) { 12503 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12504 schemesIterator); 12505 if (intentListCopy.size() == 0) { 12506 // no more intents to match; we're not equivalent 12507 if (DEBUG_FILTERS) { 12508 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12509 + " package: " + applicationInfo.packageName 12510 + " activity: " + intent.activity.className 12511 + " origPrio: " + intent.getPriority()); 12512 } 12513 intent.setPriority(0); 12514 return; 12515 } 12516 } 12517 12518 // find matching authorities subsets 12519 final Iterator<IntentFilter.AuthorityEntry> 12520 authoritiesIterator = intent.authoritiesIterator(); 12521 if (authoritiesIterator != null) { 12522 getIntentListSubset(intentListCopy, 12523 new AuthoritiesIterGenerator(), 12524 authoritiesIterator); 12525 if (intentListCopy.size() == 0) { 12526 // no more intents to match; we're not equivalent 12527 if (DEBUG_FILTERS) { 12528 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12529 + " package: " + applicationInfo.packageName 12530 + " activity: " + intent.activity.className 12531 + " origPrio: " + intent.getPriority()); 12532 } 12533 intent.setPriority(0); 12534 return; 12535 } 12536 } 12537 12538 // we found matching filter(s); app gets the max priority of all intents 12539 int cappedPriority = 0; 12540 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12541 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12542 } 12543 if (intent.getPriority() > cappedPriority) { 12544 if (DEBUG_FILTERS) { 12545 Slog.i(TAG, "Found matching filter(s);" 12546 + " cap priority to " + cappedPriority + ";" 12547 + " package: " + applicationInfo.packageName 12548 + " activity: " + intent.activity.className 12549 + " origPrio: " + intent.getPriority()); 12550 } 12551 intent.setPriority(cappedPriority); 12552 return; 12553 } 12554 // all this for nothing; the requested priority was <= what was on the system 12555 } 12556 12557 public final void addActivity(PackageParser.Activity a, String type) { 12558 mActivities.put(a.getComponentName(), a); 12559 if (DEBUG_SHOW_INFO) 12560 Log.v( 12561 TAG, " " + type + " " + 12562 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12563 if (DEBUG_SHOW_INFO) 12564 Log.v(TAG, " Class=" + a.info.name); 12565 final int NI = a.intents.size(); 12566 for (int j=0; j<NI; j++) { 12567 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12568 if ("activity".equals(type)) { 12569 final PackageSetting ps = 12570 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12571 final List<PackageParser.Activity> systemActivities = 12572 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12573 adjustPriority(systemActivities, intent); 12574 } 12575 if (DEBUG_SHOW_INFO) { 12576 Log.v(TAG, " IntentFilter:"); 12577 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12578 } 12579 if (!intent.debugCheck()) { 12580 Log.w(TAG, "==> For Activity " + a.info.name); 12581 } 12582 addFilter(intent); 12583 } 12584 } 12585 12586 public final void removeActivity(PackageParser.Activity a, String type) { 12587 mActivities.remove(a.getComponentName()); 12588 if (DEBUG_SHOW_INFO) { 12589 Log.v(TAG, " " + type + " " 12590 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12591 : a.info.name) + ":"); 12592 Log.v(TAG, " Class=" + a.info.name); 12593 } 12594 final int NI = a.intents.size(); 12595 for (int j=0; j<NI; j++) { 12596 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12597 if (DEBUG_SHOW_INFO) { 12598 Log.v(TAG, " IntentFilter:"); 12599 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12600 } 12601 removeFilter(intent); 12602 } 12603 } 12604 12605 @Override 12606 protected boolean allowFilterResult( 12607 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12608 ActivityInfo filterAi = filter.activity.info; 12609 for (int i=dest.size()-1; i>=0; i--) { 12610 ActivityInfo destAi = dest.get(i).activityInfo; 12611 if (destAi.name == filterAi.name 12612 && destAi.packageName == filterAi.packageName) { 12613 return false; 12614 } 12615 } 12616 return true; 12617 } 12618 12619 @Override 12620 protected ActivityIntentInfo[] newArray(int size) { 12621 return new ActivityIntentInfo[size]; 12622 } 12623 12624 @Override 12625 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12626 if (!sUserManager.exists(userId)) return true; 12627 PackageParser.Package p = filter.activity.owner; 12628 if (p != null) { 12629 PackageSetting ps = (PackageSetting)p.mExtras; 12630 if (ps != null) { 12631 // System apps are never considered stopped for purposes of 12632 // filtering, because there may be no way for the user to 12633 // actually re-launch them. 12634 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12635 && ps.getStopped(userId); 12636 } 12637 } 12638 return false; 12639 } 12640 12641 @Override 12642 protected boolean isPackageForFilter(String packageName, 12643 PackageParser.ActivityIntentInfo info) { 12644 return packageName.equals(info.activity.owner.packageName); 12645 } 12646 12647 @Override 12648 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12649 int match, int userId) { 12650 if (!sUserManager.exists(userId)) return null; 12651 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12652 return null; 12653 } 12654 final PackageParser.Activity activity = info.activity; 12655 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12656 if (ps == null) { 12657 return null; 12658 } 12659 final PackageUserState userState = ps.readUserState(userId); 12660 ActivityInfo ai = 12661 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12662 if (ai == null) { 12663 return null; 12664 } 12665 final boolean matchExplicitlyVisibleOnly = 12666 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12667 final boolean matchVisibleToInstantApp = 12668 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12669 final boolean componentVisible = 12670 matchVisibleToInstantApp 12671 && info.isVisibleToInstantApp() 12672 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12673 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12674 // throw out filters that aren't visible to ephemeral apps 12675 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12676 return null; 12677 } 12678 // throw out instant app filters if we're not explicitly requesting them 12679 if (!matchInstantApp && userState.instantApp) { 12680 return null; 12681 } 12682 // throw out instant app filters if updates are available; will trigger 12683 // instant app resolution 12684 if (userState.instantApp && ps.isUpdateAvailable()) { 12685 return null; 12686 } 12687 final ResolveInfo res = new ResolveInfo(); 12688 res.activityInfo = ai; 12689 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12690 res.filter = info; 12691 } 12692 if (info != null) { 12693 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12694 } 12695 res.priority = info.getPriority(); 12696 res.preferredOrder = activity.owner.mPreferredOrder; 12697 //System.out.println("Result: " + res.activityInfo.className + 12698 // " = " + res.priority); 12699 res.match = match; 12700 res.isDefault = info.hasDefault; 12701 res.labelRes = info.labelRes; 12702 res.nonLocalizedLabel = info.nonLocalizedLabel; 12703 if (userNeedsBadging(userId)) { 12704 res.noResourceId = true; 12705 } else { 12706 res.icon = info.icon; 12707 } 12708 res.iconResourceId = info.icon; 12709 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12710 res.isInstantAppAvailable = userState.instantApp; 12711 return res; 12712 } 12713 12714 @Override 12715 protected void sortResults(List<ResolveInfo> results) { 12716 Collections.sort(results, mResolvePrioritySorter); 12717 } 12718 12719 @Override 12720 protected void dumpFilter(PrintWriter out, String prefix, 12721 PackageParser.ActivityIntentInfo filter) { 12722 out.print(prefix); out.print( 12723 Integer.toHexString(System.identityHashCode(filter.activity))); 12724 out.print(' '); 12725 filter.activity.printComponentShortName(out); 12726 out.print(" filter "); 12727 out.println(Integer.toHexString(System.identityHashCode(filter))); 12728 } 12729 12730 @Override 12731 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12732 return filter.activity; 12733 } 12734 12735 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12736 PackageParser.Activity activity = (PackageParser.Activity)label; 12737 out.print(prefix); out.print( 12738 Integer.toHexString(System.identityHashCode(activity))); 12739 out.print(' '); 12740 activity.printComponentShortName(out); 12741 if (count > 1) { 12742 out.print(" ("); out.print(count); out.print(" filters)"); 12743 } 12744 out.println(); 12745 } 12746 12747 // Keys are String (activity class name), values are Activity. 12748 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12749 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12750 private int mFlags; 12751 } 12752 12753 private final class ServiceIntentResolver 12754 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12755 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12756 boolean defaultOnly, int userId) { 12757 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12758 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12759 } 12760 12761 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12762 int userId) { 12763 if (!sUserManager.exists(userId)) return null; 12764 mFlags = flags; 12765 return super.queryIntent(intent, resolvedType, 12766 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12767 userId); 12768 } 12769 12770 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12771 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12772 if (!sUserManager.exists(userId)) return null; 12773 if (packageServices == null) { 12774 return null; 12775 } 12776 mFlags = flags; 12777 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12778 final int N = packageServices.size(); 12779 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12780 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12781 12782 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12783 for (int i = 0; i < N; ++i) { 12784 intentFilters = packageServices.get(i).intents; 12785 if (intentFilters != null && intentFilters.size() > 0) { 12786 PackageParser.ServiceIntentInfo[] array = 12787 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12788 intentFilters.toArray(array); 12789 listCut.add(array); 12790 } 12791 } 12792 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12793 } 12794 12795 public final void addService(PackageParser.Service s) { 12796 mServices.put(s.getComponentName(), s); 12797 if (DEBUG_SHOW_INFO) { 12798 Log.v(TAG, " " 12799 + (s.info.nonLocalizedLabel != null 12800 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12801 Log.v(TAG, " Class=" + s.info.name); 12802 } 12803 final int NI = s.intents.size(); 12804 int j; 12805 for (j=0; j<NI; j++) { 12806 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12807 if (DEBUG_SHOW_INFO) { 12808 Log.v(TAG, " IntentFilter:"); 12809 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12810 } 12811 if (!intent.debugCheck()) { 12812 Log.w(TAG, "==> For Service " + s.info.name); 12813 } 12814 addFilter(intent); 12815 } 12816 } 12817 12818 public final void removeService(PackageParser.Service s) { 12819 mServices.remove(s.getComponentName()); 12820 if (DEBUG_SHOW_INFO) { 12821 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12822 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12823 Log.v(TAG, " Class=" + s.info.name); 12824 } 12825 final int NI = s.intents.size(); 12826 int j; 12827 for (j=0; j<NI; j++) { 12828 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12829 if (DEBUG_SHOW_INFO) { 12830 Log.v(TAG, " IntentFilter:"); 12831 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12832 } 12833 removeFilter(intent); 12834 } 12835 } 12836 12837 @Override 12838 protected boolean allowFilterResult( 12839 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12840 ServiceInfo filterSi = filter.service.info; 12841 for (int i=dest.size()-1; i>=0; i--) { 12842 ServiceInfo destAi = dest.get(i).serviceInfo; 12843 if (destAi.name == filterSi.name 12844 && destAi.packageName == filterSi.packageName) { 12845 return false; 12846 } 12847 } 12848 return true; 12849 } 12850 12851 @Override 12852 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12853 return new PackageParser.ServiceIntentInfo[size]; 12854 } 12855 12856 @Override 12857 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12858 if (!sUserManager.exists(userId)) return true; 12859 PackageParser.Package p = filter.service.owner; 12860 if (p != null) { 12861 PackageSetting ps = (PackageSetting)p.mExtras; 12862 if (ps != null) { 12863 // System apps are never considered stopped for purposes of 12864 // filtering, because there may be no way for the user to 12865 // actually re-launch them. 12866 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12867 && ps.getStopped(userId); 12868 } 12869 } 12870 return false; 12871 } 12872 12873 @Override 12874 protected boolean isPackageForFilter(String packageName, 12875 PackageParser.ServiceIntentInfo info) { 12876 return packageName.equals(info.service.owner.packageName); 12877 } 12878 12879 @Override 12880 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12881 int match, int userId) { 12882 if (!sUserManager.exists(userId)) return null; 12883 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12884 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12885 return null; 12886 } 12887 final PackageParser.Service service = info.service; 12888 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12889 if (ps == null) { 12890 return null; 12891 } 12892 final PackageUserState userState = ps.readUserState(userId); 12893 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12894 userState, userId); 12895 if (si == null) { 12896 return null; 12897 } 12898 final boolean matchVisibleToInstantApp = 12899 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12900 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12901 // throw out filters that aren't visible to ephemeral apps 12902 if (matchVisibleToInstantApp 12903 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12904 return null; 12905 } 12906 // throw out ephemeral filters if we're not explicitly requesting them 12907 if (!isInstantApp && userState.instantApp) { 12908 return null; 12909 } 12910 // throw out instant app filters if updates are available; will trigger 12911 // instant app resolution 12912 if (userState.instantApp && ps.isUpdateAvailable()) { 12913 return null; 12914 } 12915 final ResolveInfo res = new ResolveInfo(); 12916 res.serviceInfo = si; 12917 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12918 res.filter = filter; 12919 } 12920 res.priority = info.getPriority(); 12921 res.preferredOrder = service.owner.mPreferredOrder; 12922 res.match = match; 12923 res.isDefault = info.hasDefault; 12924 res.labelRes = info.labelRes; 12925 res.nonLocalizedLabel = info.nonLocalizedLabel; 12926 res.icon = info.icon; 12927 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12928 return res; 12929 } 12930 12931 @Override 12932 protected void sortResults(List<ResolveInfo> results) { 12933 Collections.sort(results, mResolvePrioritySorter); 12934 } 12935 12936 @Override 12937 protected void dumpFilter(PrintWriter out, String prefix, 12938 PackageParser.ServiceIntentInfo filter) { 12939 out.print(prefix); out.print( 12940 Integer.toHexString(System.identityHashCode(filter.service))); 12941 out.print(' '); 12942 filter.service.printComponentShortName(out); 12943 out.print(" filter "); 12944 out.print(Integer.toHexString(System.identityHashCode(filter))); 12945 if (filter.service.info.permission != null) { 12946 out.print(" permission "); out.println(filter.service.info.permission); 12947 } else { 12948 out.println(); 12949 } 12950 } 12951 12952 @Override 12953 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12954 return filter.service; 12955 } 12956 12957 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12958 PackageParser.Service service = (PackageParser.Service)label; 12959 out.print(prefix); out.print( 12960 Integer.toHexString(System.identityHashCode(service))); 12961 out.print(' '); 12962 service.printComponentShortName(out); 12963 if (count > 1) { 12964 out.print(" ("); out.print(count); out.print(" filters)"); 12965 } 12966 out.println(); 12967 } 12968 12969// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12970// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12971// final List<ResolveInfo> retList = Lists.newArrayList(); 12972// while (i.hasNext()) { 12973// final ResolveInfo resolveInfo = (ResolveInfo) i; 12974// if (isEnabledLP(resolveInfo.serviceInfo)) { 12975// retList.add(resolveInfo); 12976// } 12977// } 12978// return retList; 12979// } 12980 12981 // Keys are String (activity class name), values are Activity. 12982 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12983 = new ArrayMap<ComponentName, PackageParser.Service>(); 12984 private int mFlags; 12985 } 12986 12987 private final class ProviderIntentResolver 12988 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12989 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12990 boolean defaultOnly, int userId) { 12991 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12992 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12993 } 12994 12995 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12996 int userId) { 12997 if (!sUserManager.exists(userId)) 12998 return null; 12999 mFlags = flags; 13000 return super.queryIntent(intent, resolvedType, 13001 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13002 userId); 13003 } 13004 13005 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13006 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13007 if (!sUserManager.exists(userId)) 13008 return null; 13009 if (packageProviders == null) { 13010 return null; 13011 } 13012 mFlags = flags; 13013 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13014 final int N = packageProviders.size(); 13015 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13016 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13017 13018 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13019 for (int i = 0; i < N; ++i) { 13020 intentFilters = packageProviders.get(i).intents; 13021 if (intentFilters != null && intentFilters.size() > 0) { 13022 PackageParser.ProviderIntentInfo[] array = 13023 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13024 intentFilters.toArray(array); 13025 listCut.add(array); 13026 } 13027 } 13028 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13029 } 13030 13031 public final void addProvider(PackageParser.Provider p) { 13032 if (mProviders.containsKey(p.getComponentName())) { 13033 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13034 return; 13035 } 13036 13037 mProviders.put(p.getComponentName(), p); 13038 if (DEBUG_SHOW_INFO) { 13039 Log.v(TAG, " " 13040 + (p.info.nonLocalizedLabel != null 13041 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13042 Log.v(TAG, " Class=" + p.info.name); 13043 } 13044 final int NI = p.intents.size(); 13045 int j; 13046 for (j = 0; j < NI; j++) { 13047 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13048 if (DEBUG_SHOW_INFO) { 13049 Log.v(TAG, " IntentFilter:"); 13050 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13051 } 13052 if (!intent.debugCheck()) { 13053 Log.w(TAG, "==> For Provider " + p.info.name); 13054 } 13055 addFilter(intent); 13056 } 13057 } 13058 13059 public final void removeProvider(PackageParser.Provider p) { 13060 mProviders.remove(p.getComponentName()); 13061 if (DEBUG_SHOW_INFO) { 13062 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13063 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13064 Log.v(TAG, " Class=" + p.info.name); 13065 } 13066 final int NI = p.intents.size(); 13067 int j; 13068 for (j = 0; j < NI; j++) { 13069 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13070 if (DEBUG_SHOW_INFO) { 13071 Log.v(TAG, " IntentFilter:"); 13072 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13073 } 13074 removeFilter(intent); 13075 } 13076 } 13077 13078 @Override 13079 protected boolean allowFilterResult( 13080 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13081 ProviderInfo filterPi = filter.provider.info; 13082 for (int i = dest.size() - 1; i >= 0; i--) { 13083 ProviderInfo destPi = dest.get(i).providerInfo; 13084 if (destPi.name == filterPi.name 13085 && destPi.packageName == filterPi.packageName) { 13086 return false; 13087 } 13088 } 13089 return true; 13090 } 13091 13092 @Override 13093 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13094 return new PackageParser.ProviderIntentInfo[size]; 13095 } 13096 13097 @Override 13098 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13099 if (!sUserManager.exists(userId)) 13100 return true; 13101 PackageParser.Package p = filter.provider.owner; 13102 if (p != null) { 13103 PackageSetting ps = (PackageSetting) p.mExtras; 13104 if (ps != null) { 13105 // System apps are never considered stopped for purposes of 13106 // filtering, because there may be no way for the user to 13107 // actually re-launch them. 13108 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13109 && ps.getStopped(userId); 13110 } 13111 } 13112 return false; 13113 } 13114 13115 @Override 13116 protected boolean isPackageForFilter(String packageName, 13117 PackageParser.ProviderIntentInfo info) { 13118 return packageName.equals(info.provider.owner.packageName); 13119 } 13120 13121 @Override 13122 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13123 int match, int userId) { 13124 if (!sUserManager.exists(userId)) 13125 return null; 13126 final PackageParser.ProviderIntentInfo info = filter; 13127 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13128 return null; 13129 } 13130 final PackageParser.Provider provider = info.provider; 13131 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13132 if (ps == null) { 13133 return null; 13134 } 13135 final PackageUserState userState = ps.readUserState(userId); 13136 final boolean matchVisibleToInstantApp = 13137 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13138 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13139 // throw out filters that aren't visible to instant applications 13140 if (matchVisibleToInstantApp 13141 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13142 return null; 13143 } 13144 // throw out instant application filters if we're not explicitly requesting them 13145 if (!isInstantApp && userState.instantApp) { 13146 return null; 13147 } 13148 // throw out instant application filters if updates are available; will trigger 13149 // instant application resolution 13150 if (userState.instantApp && ps.isUpdateAvailable()) { 13151 return null; 13152 } 13153 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13154 userState, userId); 13155 if (pi == null) { 13156 return null; 13157 } 13158 final ResolveInfo res = new ResolveInfo(); 13159 res.providerInfo = pi; 13160 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13161 res.filter = filter; 13162 } 13163 res.priority = info.getPriority(); 13164 res.preferredOrder = provider.owner.mPreferredOrder; 13165 res.match = match; 13166 res.isDefault = info.hasDefault; 13167 res.labelRes = info.labelRes; 13168 res.nonLocalizedLabel = info.nonLocalizedLabel; 13169 res.icon = info.icon; 13170 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13171 return res; 13172 } 13173 13174 @Override 13175 protected void sortResults(List<ResolveInfo> results) { 13176 Collections.sort(results, mResolvePrioritySorter); 13177 } 13178 13179 @Override 13180 protected void dumpFilter(PrintWriter out, String prefix, 13181 PackageParser.ProviderIntentInfo filter) { 13182 out.print(prefix); 13183 out.print( 13184 Integer.toHexString(System.identityHashCode(filter.provider))); 13185 out.print(' '); 13186 filter.provider.printComponentShortName(out); 13187 out.print(" filter "); 13188 out.println(Integer.toHexString(System.identityHashCode(filter))); 13189 } 13190 13191 @Override 13192 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13193 return filter.provider; 13194 } 13195 13196 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13197 PackageParser.Provider provider = (PackageParser.Provider)label; 13198 out.print(prefix); out.print( 13199 Integer.toHexString(System.identityHashCode(provider))); 13200 out.print(' '); 13201 provider.printComponentShortName(out); 13202 if (count > 1) { 13203 out.print(" ("); out.print(count); out.print(" filters)"); 13204 } 13205 out.println(); 13206 } 13207 13208 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13209 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13210 private int mFlags; 13211 } 13212 13213 static final class EphemeralIntentResolver 13214 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13215 /** 13216 * The result that has the highest defined order. Ordering applies on a 13217 * per-package basis. Mapping is from package name to Pair of order and 13218 * EphemeralResolveInfo. 13219 * <p> 13220 * NOTE: This is implemented as a field variable for convenience and efficiency. 13221 * By having a field variable, we're able to track filter ordering as soon as 13222 * a non-zero order is defined. Otherwise, multiple loops across the result set 13223 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13224 * this needs to be contained entirely within {@link #filterResults}. 13225 */ 13226 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13227 13228 @Override 13229 protected AuxiliaryResolveInfo[] newArray(int size) { 13230 return new AuxiliaryResolveInfo[size]; 13231 } 13232 13233 @Override 13234 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13235 return true; 13236 } 13237 13238 @Override 13239 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13240 int userId) { 13241 if (!sUserManager.exists(userId)) { 13242 return null; 13243 } 13244 final String packageName = responseObj.resolveInfo.getPackageName(); 13245 final Integer order = responseObj.getOrder(); 13246 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13247 mOrderResult.get(packageName); 13248 // ordering is enabled and this item's order isn't high enough 13249 if (lastOrderResult != null && lastOrderResult.first >= order) { 13250 return null; 13251 } 13252 final InstantAppResolveInfo res = responseObj.resolveInfo; 13253 if (order > 0) { 13254 // non-zero order, enable ordering 13255 mOrderResult.put(packageName, new Pair<>(order, res)); 13256 } 13257 return responseObj; 13258 } 13259 13260 @Override 13261 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13262 // only do work if ordering is enabled [most of the time it won't be] 13263 if (mOrderResult.size() == 0) { 13264 return; 13265 } 13266 int resultSize = results.size(); 13267 for (int i = 0; i < resultSize; i++) { 13268 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13269 final String packageName = info.getPackageName(); 13270 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13271 if (savedInfo == null) { 13272 // package doesn't having ordering 13273 continue; 13274 } 13275 if (savedInfo.second == info) { 13276 // circled back to the highest ordered item; remove from order list 13277 mOrderResult.remove(packageName); 13278 if (mOrderResult.size() == 0) { 13279 // no more ordered items 13280 break; 13281 } 13282 continue; 13283 } 13284 // item has a worse order, remove it from the result list 13285 results.remove(i); 13286 resultSize--; 13287 i--; 13288 } 13289 } 13290 } 13291 13292 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13293 new Comparator<ResolveInfo>() { 13294 public int compare(ResolveInfo r1, ResolveInfo r2) { 13295 int v1 = r1.priority; 13296 int v2 = r2.priority; 13297 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13298 if (v1 != v2) { 13299 return (v1 > v2) ? -1 : 1; 13300 } 13301 v1 = r1.preferredOrder; 13302 v2 = r2.preferredOrder; 13303 if (v1 != v2) { 13304 return (v1 > v2) ? -1 : 1; 13305 } 13306 if (r1.isDefault != r2.isDefault) { 13307 return r1.isDefault ? -1 : 1; 13308 } 13309 v1 = r1.match; 13310 v2 = r2.match; 13311 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13312 if (v1 != v2) { 13313 return (v1 > v2) ? -1 : 1; 13314 } 13315 if (r1.system != r2.system) { 13316 return r1.system ? -1 : 1; 13317 } 13318 if (r1.activityInfo != null) { 13319 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13320 } 13321 if (r1.serviceInfo != null) { 13322 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13323 } 13324 if (r1.providerInfo != null) { 13325 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13326 } 13327 return 0; 13328 } 13329 }; 13330 13331 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13332 new Comparator<ProviderInfo>() { 13333 public int compare(ProviderInfo p1, ProviderInfo p2) { 13334 final int v1 = p1.initOrder; 13335 final int v2 = p2.initOrder; 13336 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13337 } 13338 }; 13339 13340 @Override 13341 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13342 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13343 final int[] userIds, int[] instantUserIds) { 13344 mHandler.post(new Runnable() { 13345 @Override 13346 public void run() { 13347 try { 13348 final IActivityManager am = ActivityManager.getService(); 13349 if (am == null) return; 13350 final int[] resolvedUserIds; 13351 if (userIds == null) { 13352 resolvedUserIds = am.getRunningUserIds(); 13353 } else { 13354 resolvedUserIds = userIds; 13355 } 13356 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13357 resolvedUserIds, false); 13358 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13359 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13360 instantUserIds, true); 13361 } 13362 } catch (RemoteException ex) { 13363 } 13364 } 13365 }); 13366 } 13367 13368 @Override 13369 public void notifyPackageAdded(String packageName) { 13370 final PackageListObserver[] observers; 13371 synchronized (mPackages) { 13372 if (mPackageListObservers.size() == 0) { 13373 return; 13374 } 13375 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13376 } 13377 for (int i = observers.length - 1; i >= 0; --i) { 13378 observers[i].onPackageAdded(packageName); 13379 } 13380 } 13381 13382 @Override 13383 public void notifyPackageRemoved(String packageName) { 13384 final PackageListObserver[] observers; 13385 synchronized (mPackages) { 13386 if (mPackageListObservers.size() == 0) { 13387 return; 13388 } 13389 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13390 } 13391 for (int i = observers.length - 1; i >= 0; --i) { 13392 observers[i].onPackageRemoved(packageName); 13393 } 13394 } 13395 13396 /** 13397 * Sends a broadcast for the given action. 13398 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13399 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13400 * the system and applications allowed to see instant applications to receive package 13401 * lifecycle events for instant applications. 13402 */ 13403 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13404 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13405 int[] userIds, boolean isInstantApp) 13406 throws RemoteException { 13407 for (int id : userIds) { 13408 final Intent intent = new Intent(action, 13409 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13410 final String[] requiredPermissions = 13411 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13412 if (extras != null) { 13413 intent.putExtras(extras); 13414 } 13415 if (targetPkg != null) { 13416 intent.setPackage(targetPkg); 13417 } 13418 // Modify the UID when posting to other users 13419 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13420 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13421 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13422 intent.putExtra(Intent.EXTRA_UID, uid); 13423 } 13424 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13425 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13426 if (DEBUG_BROADCASTS) { 13427 RuntimeException here = new RuntimeException("here"); 13428 here.fillInStackTrace(); 13429 Slog.d(TAG, "Sending to user " + id + ": " 13430 + intent.toShortString(false, true, false, false) 13431 + " " + intent.getExtras(), here); 13432 } 13433 am.broadcastIntent(null, intent, null, finishedReceiver, 13434 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13435 null, finishedReceiver != null, false, id); 13436 } 13437 } 13438 13439 /** 13440 * Check if the external storage media is available. This is true if there 13441 * is a mounted external storage medium or if the external storage is 13442 * emulated. 13443 */ 13444 private boolean isExternalMediaAvailable() { 13445 return mMediaMounted || Environment.isExternalStorageEmulated(); 13446 } 13447 13448 @Override 13449 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13450 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13451 return null; 13452 } 13453 if (!isExternalMediaAvailable()) { 13454 // If the external storage is no longer mounted at this point, 13455 // the caller may not have been able to delete all of this 13456 // packages files and can not delete any more. Bail. 13457 return null; 13458 } 13459 synchronized (mPackages) { 13460 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13461 if (lastPackage != null) { 13462 pkgs.remove(lastPackage); 13463 } 13464 if (pkgs.size() > 0) { 13465 return pkgs.get(0); 13466 } 13467 } 13468 return null; 13469 } 13470 13471 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13472 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13473 userId, andCode ? 1 : 0, packageName); 13474 if (mSystemReady) { 13475 msg.sendToTarget(); 13476 } else { 13477 if (mPostSystemReadyMessages == null) { 13478 mPostSystemReadyMessages = new ArrayList<>(); 13479 } 13480 mPostSystemReadyMessages.add(msg); 13481 } 13482 } 13483 13484 void startCleaningPackages() { 13485 // reader 13486 if (!isExternalMediaAvailable()) { 13487 return; 13488 } 13489 synchronized (mPackages) { 13490 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13491 return; 13492 } 13493 } 13494 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13495 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13496 IActivityManager am = ActivityManager.getService(); 13497 if (am != null) { 13498 int dcsUid = -1; 13499 synchronized (mPackages) { 13500 if (!mDefaultContainerWhitelisted) { 13501 mDefaultContainerWhitelisted = true; 13502 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13503 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13504 } 13505 } 13506 try { 13507 if (dcsUid > 0) { 13508 am.backgroundWhitelistUid(dcsUid); 13509 } 13510 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13511 UserHandle.USER_SYSTEM); 13512 } catch (RemoteException e) { 13513 } 13514 } 13515 } 13516 13517 /** 13518 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13519 * it is acting on behalf on an enterprise or the user). 13520 * 13521 * Note that the ordering of the conditionals in this method is important. The checks we perform 13522 * are as follows, in this order: 13523 * 13524 * 1) If the install is being performed by a system app, we can trust the app to have set the 13525 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13526 * what it is. 13527 * 2) If the install is being performed by a device or profile owner app, the install reason 13528 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13529 * set the install reason correctly. If the app targets an older SDK version where install 13530 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13531 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13532 * 3) In all other cases, the install is being performed by a regular app that is neither part 13533 * of the system nor a device or profile owner. We have no reason to believe that this app is 13534 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13535 * set to enterprise policy and if so, change it to unknown instead. 13536 */ 13537 private int fixUpInstallReason(String installerPackageName, int installerUid, 13538 int installReason) { 13539 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13540 == PERMISSION_GRANTED) { 13541 // If the install is being performed by a system app, we trust that app to have set the 13542 // install reason correctly. 13543 return installReason; 13544 } 13545 13546 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13547 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13548 if (dpm != null) { 13549 ComponentName owner = null; 13550 try { 13551 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13552 if (owner == null) { 13553 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13554 } 13555 } catch (RemoteException e) { 13556 } 13557 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13558 // If the install is being performed by a device or profile owner, the install 13559 // reason should be enterprise policy. 13560 return PackageManager.INSTALL_REASON_POLICY; 13561 } 13562 } 13563 13564 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13565 // If the install is being performed by a regular app (i.e. neither system app nor 13566 // device or profile owner), we have no reason to believe that the app is acting on 13567 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13568 // change it to unknown instead. 13569 return PackageManager.INSTALL_REASON_UNKNOWN; 13570 } 13571 13572 // If the install is being performed by a regular app and the install reason was set to any 13573 // value but enterprise policy, leave the install reason unchanged. 13574 return installReason; 13575 } 13576 13577 void installStage(String packageName, File stagedDir, 13578 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13579 String installerPackageName, int installerUid, UserHandle user, 13580 PackageParser.SigningDetails signingDetails) { 13581 if (DEBUG_EPHEMERAL) { 13582 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13583 Slog.d(TAG, "Ephemeral install of " + packageName); 13584 } 13585 } 13586 final VerificationInfo verificationInfo = new VerificationInfo( 13587 sessionParams.originatingUri, sessionParams.referrerUri, 13588 sessionParams.originatingUid, installerUid); 13589 13590 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13591 13592 final Message msg = mHandler.obtainMessage(INIT_COPY); 13593 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13594 sessionParams.installReason); 13595 final InstallParams params = new InstallParams(origin, null, observer, 13596 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13597 verificationInfo, user, sessionParams.abiOverride, 13598 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13599 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13600 msg.obj = params; 13601 13602 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13603 System.identityHashCode(msg.obj)); 13604 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13605 System.identityHashCode(msg.obj)); 13606 13607 mHandler.sendMessage(msg); 13608 } 13609 13610 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13611 int userId) { 13612 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13613 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13614 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13615 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13616 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13617 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13618 13619 // Send a session commit broadcast 13620 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13621 info.installReason = pkgSetting.getInstallReason(userId); 13622 info.appPackageName = packageName; 13623 sendSessionCommitBroadcast(info, userId); 13624 } 13625 13626 @Override 13627 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13628 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13629 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13630 return; 13631 } 13632 Bundle extras = new Bundle(1); 13633 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13634 final int uid = UserHandle.getUid( 13635 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13636 extras.putInt(Intent.EXTRA_UID, uid); 13637 13638 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13639 packageName, extras, 0, null, null, userIds, instantUserIds); 13640 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13641 mHandler.post(() -> { 13642 for (int userId : userIds) { 13643 sendBootCompletedBroadcastToSystemApp( 13644 packageName, includeStopped, userId); 13645 } 13646 } 13647 ); 13648 } 13649 } 13650 13651 /** 13652 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13653 * automatically without needing an explicit launch. 13654 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13655 */ 13656 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13657 int userId) { 13658 // If user is not running, the app didn't miss any broadcast 13659 if (!mUserManagerInternal.isUserRunning(userId)) { 13660 return; 13661 } 13662 final IActivityManager am = ActivityManager.getService(); 13663 try { 13664 // Deliver LOCKED_BOOT_COMPLETED first 13665 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13666 .setPackage(packageName); 13667 if (includeStopped) { 13668 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13669 } 13670 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13671 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13672 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13673 13674 // Deliver BOOT_COMPLETED only if user is unlocked 13675 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13676 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13677 if (includeStopped) { 13678 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13679 } 13680 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13681 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13682 } 13683 } catch (RemoteException e) { 13684 throw e.rethrowFromSystemServer(); 13685 } 13686 } 13687 13688 @Override 13689 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13690 int userId) { 13691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13692 PackageSetting pkgSetting; 13693 final int callingUid = Binder.getCallingUid(); 13694 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13695 true /* requireFullPermission */, true /* checkShell */, 13696 "setApplicationHiddenSetting for user " + userId); 13697 13698 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13699 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13700 return false; 13701 } 13702 13703 long callingId = Binder.clearCallingIdentity(); 13704 try { 13705 boolean sendAdded = false; 13706 boolean sendRemoved = false; 13707 // writer 13708 synchronized (mPackages) { 13709 pkgSetting = mSettings.mPackages.get(packageName); 13710 if (pkgSetting == null) { 13711 return false; 13712 } 13713 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13714 return false; 13715 } 13716 // Do not allow "android" is being disabled 13717 if ("android".equals(packageName)) { 13718 Slog.w(TAG, "Cannot hide package: android"); 13719 return false; 13720 } 13721 // Cannot hide static shared libs as they are considered 13722 // a part of the using app (emulating static linking). Also 13723 // static libs are installed always on internal storage. 13724 PackageParser.Package pkg = mPackages.get(packageName); 13725 if (pkg != null && pkg.staticSharedLibName != null) { 13726 Slog.w(TAG, "Cannot hide package: " + packageName 13727 + " providing static shared library: " 13728 + pkg.staticSharedLibName); 13729 return false; 13730 } 13731 // Only allow protected packages to hide themselves. 13732 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13733 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13734 Slog.w(TAG, "Not hiding protected package: " + packageName); 13735 return false; 13736 } 13737 13738 if (pkgSetting.getHidden(userId) != hidden) { 13739 pkgSetting.setHidden(hidden, userId); 13740 mSettings.writePackageRestrictionsLPr(userId); 13741 if (hidden) { 13742 sendRemoved = true; 13743 } else { 13744 sendAdded = true; 13745 } 13746 } 13747 } 13748 if (sendAdded) { 13749 sendPackageAddedForUser(packageName, pkgSetting, userId); 13750 return true; 13751 } 13752 if (sendRemoved) { 13753 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13754 "hiding pkg"); 13755 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13756 return true; 13757 } 13758 } finally { 13759 Binder.restoreCallingIdentity(callingId); 13760 } 13761 return false; 13762 } 13763 13764 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13765 int userId) { 13766 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13767 info.removedPackage = packageName; 13768 info.installerPackageName = pkgSetting.installerPackageName; 13769 info.removedUsers = new int[] {userId}; 13770 info.broadcastUsers = new int[] {userId}; 13771 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13772 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13773 } 13774 13775 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13776 if (pkgList.length > 0) { 13777 Bundle extras = new Bundle(1); 13778 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13779 13780 sendPackageBroadcast( 13781 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13782 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13783 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13784 new int[] {userId}, null); 13785 } 13786 } 13787 13788 /** 13789 * Returns true if application is not found or there was an error. Otherwise it returns 13790 * the hidden state of the package for the given user. 13791 */ 13792 @Override 13793 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13795 final int callingUid = Binder.getCallingUid(); 13796 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13797 true /* requireFullPermission */, false /* checkShell */, 13798 "getApplicationHidden for user " + userId); 13799 PackageSetting ps; 13800 long callingId = Binder.clearCallingIdentity(); 13801 try { 13802 // writer 13803 synchronized (mPackages) { 13804 ps = mSettings.mPackages.get(packageName); 13805 if (ps == null) { 13806 return true; 13807 } 13808 if (filterAppAccessLPr(ps, callingUid, userId)) { 13809 return true; 13810 } 13811 return ps.getHidden(userId); 13812 } 13813 } finally { 13814 Binder.restoreCallingIdentity(callingId); 13815 } 13816 } 13817 13818 /** 13819 * @hide 13820 */ 13821 @Override 13822 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13823 int installReason) { 13824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13825 null); 13826 PackageSetting pkgSetting; 13827 final int callingUid = Binder.getCallingUid(); 13828 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13829 true /* requireFullPermission */, true /* checkShell */, 13830 "installExistingPackage for user " + userId); 13831 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13832 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13833 } 13834 13835 long callingId = Binder.clearCallingIdentity(); 13836 try { 13837 boolean installed = false; 13838 final boolean instantApp = 13839 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13840 final boolean fullApp = 13841 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13842 13843 // writer 13844 synchronized (mPackages) { 13845 pkgSetting = mSettings.mPackages.get(packageName); 13846 if (pkgSetting == null) { 13847 return PackageManager.INSTALL_FAILED_INVALID_URI; 13848 } 13849 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13850 // only allow the existing package to be used if it's installed as a full 13851 // application for at least one user 13852 boolean installAllowed = false; 13853 for (int checkUserId : sUserManager.getUserIds()) { 13854 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13855 if (installAllowed) { 13856 break; 13857 } 13858 } 13859 if (!installAllowed) { 13860 return PackageManager.INSTALL_FAILED_INVALID_URI; 13861 } 13862 } 13863 if (!pkgSetting.getInstalled(userId)) { 13864 pkgSetting.setInstalled(true, userId); 13865 pkgSetting.setHidden(false, userId); 13866 pkgSetting.setInstallReason(installReason, userId); 13867 mSettings.writePackageRestrictionsLPr(userId); 13868 mSettings.writeKernelMappingLPr(pkgSetting); 13869 installed = true; 13870 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13871 // upgrade app from instant to full; we don't allow app downgrade 13872 installed = true; 13873 } 13874 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13875 } 13876 13877 if (installed) { 13878 if (pkgSetting.pkg != null) { 13879 synchronized (mInstallLock) { 13880 // We don't need to freeze for a brand new install 13881 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13882 } 13883 } 13884 sendPackageAddedForUser(packageName, pkgSetting, userId); 13885 synchronized (mPackages) { 13886 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13887 } 13888 } 13889 } finally { 13890 Binder.restoreCallingIdentity(callingId); 13891 } 13892 13893 return PackageManager.INSTALL_SUCCEEDED; 13894 } 13895 13896 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13897 boolean instantApp, boolean fullApp) { 13898 // no state specified; do nothing 13899 if (!instantApp && !fullApp) { 13900 return; 13901 } 13902 if (userId != UserHandle.USER_ALL) { 13903 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13904 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13905 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13906 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13907 } 13908 } else { 13909 for (int currentUserId : sUserManager.getUserIds()) { 13910 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13911 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13912 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13913 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13914 } 13915 } 13916 } 13917 } 13918 13919 boolean isUserRestricted(int userId, String restrictionKey) { 13920 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13921 if (restrictions.getBoolean(restrictionKey, false)) { 13922 Log.w(TAG, "User is restricted: " + restrictionKey); 13923 return true; 13924 } 13925 return false; 13926 } 13927 13928 @Override 13929 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13930 int userId) { 13931 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13932 final int callingUid = Binder.getCallingUid(); 13933 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13934 true /* requireFullPermission */, true /* checkShell */, 13935 "setPackagesSuspended for user " + userId); 13936 13937 if (ArrayUtils.isEmpty(packageNames)) { 13938 return packageNames; 13939 } 13940 13941 // List of package names for whom the suspended state has changed. 13942 List<String> changedPackages = new ArrayList<>(packageNames.length); 13943 // List of package names for whom the suspended state is not set as requested in this 13944 // method. 13945 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13946 long callingId = Binder.clearCallingIdentity(); 13947 try { 13948 for (int i = 0; i < packageNames.length; i++) { 13949 String packageName = packageNames[i]; 13950 boolean changed = false; 13951 final int appId; 13952 synchronized (mPackages) { 13953 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13954 if (pkgSetting == null 13955 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13956 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13957 + "\". Skipping suspending/un-suspending."); 13958 unactionedPackages.add(packageName); 13959 continue; 13960 } 13961 appId = pkgSetting.appId; 13962 if (pkgSetting.getSuspended(userId) != suspended) { 13963 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13964 unactionedPackages.add(packageName); 13965 continue; 13966 } 13967 pkgSetting.setSuspended(suspended, userId); 13968 mSettings.writePackageRestrictionsLPr(userId); 13969 changed = true; 13970 changedPackages.add(packageName); 13971 } 13972 } 13973 13974 if (changed && suspended) { 13975 killApplication(packageName, UserHandle.getUid(userId, appId), 13976 "suspending package"); 13977 } 13978 } 13979 } finally { 13980 Binder.restoreCallingIdentity(callingId); 13981 } 13982 13983 if (!changedPackages.isEmpty()) { 13984 sendPackagesSuspendedForUser(changedPackages.toArray( 13985 new String[changedPackages.size()]), userId, suspended); 13986 } 13987 13988 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13989 } 13990 13991 @Override 13992 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13993 final int callingUid = Binder.getCallingUid(); 13994 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13995 true /* requireFullPermission */, false /* checkShell */, 13996 "isPackageSuspendedForUser for user " + userId); 13997 synchronized (mPackages) { 13998 final PackageSetting ps = mSettings.mPackages.get(packageName); 13999 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14000 throw new IllegalArgumentException("Unknown target package: " + packageName); 14001 } 14002 return ps.getSuspended(userId); 14003 } 14004 } 14005 14006 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14007 if (isPackageDeviceAdmin(packageName, userId)) { 14008 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14009 + "\": has an active device admin"); 14010 return false; 14011 } 14012 14013 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14014 if (packageName.equals(activeLauncherPackageName)) { 14015 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14016 + "\": contains the active launcher"); 14017 return false; 14018 } 14019 14020 if (packageName.equals(mRequiredInstallerPackage)) { 14021 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14022 + "\": required for package installation"); 14023 return false; 14024 } 14025 14026 if (packageName.equals(mRequiredUninstallerPackage)) { 14027 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14028 + "\": required for package uninstallation"); 14029 return false; 14030 } 14031 14032 if (packageName.equals(mRequiredVerifierPackage)) { 14033 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14034 + "\": required for package verification"); 14035 return false; 14036 } 14037 14038 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14039 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14040 + "\": is the default dialer"); 14041 return false; 14042 } 14043 14044 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14045 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14046 + "\": protected package"); 14047 return false; 14048 } 14049 14050 // Cannot suspend static shared libs as they are considered 14051 // a part of the using app (emulating static linking). Also 14052 // static libs are installed always on internal storage. 14053 PackageParser.Package pkg = mPackages.get(packageName); 14054 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14055 Slog.w(TAG, "Cannot suspend package: " + packageName 14056 + " providing static shared library: " 14057 + pkg.staticSharedLibName); 14058 return false; 14059 } 14060 14061 return true; 14062 } 14063 14064 private String getActiveLauncherPackageName(int userId) { 14065 Intent intent = new Intent(Intent.ACTION_MAIN); 14066 intent.addCategory(Intent.CATEGORY_HOME); 14067 ResolveInfo resolveInfo = resolveIntent( 14068 intent, 14069 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14070 PackageManager.MATCH_DEFAULT_ONLY, 14071 userId); 14072 14073 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14074 } 14075 14076 private String getDefaultDialerPackageName(int userId) { 14077 synchronized (mPackages) { 14078 return mSettings.getDefaultDialerPackageNameLPw(userId); 14079 } 14080 } 14081 14082 @Override 14083 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14084 mContext.enforceCallingOrSelfPermission( 14085 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14086 "Only package verification agents can verify applications"); 14087 14088 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14089 final PackageVerificationResponse response = new PackageVerificationResponse( 14090 verificationCode, Binder.getCallingUid()); 14091 msg.arg1 = id; 14092 msg.obj = response; 14093 mHandler.sendMessage(msg); 14094 } 14095 14096 @Override 14097 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14098 long millisecondsToDelay) { 14099 mContext.enforceCallingOrSelfPermission( 14100 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14101 "Only package verification agents can extend verification timeouts"); 14102 14103 final PackageVerificationState state = mPendingVerification.get(id); 14104 final PackageVerificationResponse response = new PackageVerificationResponse( 14105 verificationCodeAtTimeout, Binder.getCallingUid()); 14106 14107 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14108 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14109 } 14110 if (millisecondsToDelay < 0) { 14111 millisecondsToDelay = 0; 14112 } 14113 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14114 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14115 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14116 } 14117 14118 if ((state != null) && !state.timeoutExtended()) { 14119 state.extendTimeout(); 14120 14121 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14122 msg.arg1 = id; 14123 msg.obj = response; 14124 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14125 } 14126 } 14127 14128 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14129 int verificationCode, UserHandle user) { 14130 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14131 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14132 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14133 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14134 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14135 14136 mContext.sendBroadcastAsUser(intent, user, 14137 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14138 } 14139 14140 private ComponentName matchComponentForVerifier(String packageName, 14141 List<ResolveInfo> receivers) { 14142 ActivityInfo targetReceiver = null; 14143 14144 final int NR = receivers.size(); 14145 for (int i = 0; i < NR; i++) { 14146 final ResolveInfo info = receivers.get(i); 14147 if (info.activityInfo == null) { 14148 continue; 14149 } 14150 14151 if (packageName.equals(info.activityInfo.packageName)) { 14152 targetReceiver = info.activityInfo; 14153 break; 14154 } 14155 } 14156 14157 if (targetReceiver == null) { 14158 return null; 14159 } 14160 14161 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14162 } 14163 14164 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14165 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14166 if (pkgInfo.verifiers.length == 0) { 14167 return null; 14168 } 14169 14170 final int N = pkgInfo.verifiers.length; 14171 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14172 for (int i = 0; i < N; i++) { 14173 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14174 14175 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14176 receivers); 14177 if (comp == null) { 14178 continue; 14179 } 14180 14181 final int verifierUid = getUidForVerifier(verifierInfo); 14182 if (verifierUid == -1) { 14183 continue; 14184 } 14185 14186 if (DEBUG_VERIFY) { 14187 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14188 + " with the correct signature"); 14189 } 14190 sufficientVerifiers.add(comp); 14191 verificationState.addSufficientVerifier(verifierUid); 14192 } 14193 14194 return sufficientVerifiers; 14195 } 14196 14197 private int getUidForVerifier(VerifierInfo verifierInfo) { 14198 synchronized (mPackages) { 14199 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14200 if (pkg == null) { 14201 return -1; 14202 } else if (pkg.mSigningDetails.signatures.length != 1) { 14203 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14204 + " has more than one signature; ignoring"); 14205 return -1; 14206 } 14207 14208 /* 14209 * If the public key of the package's signature does not match 14210 * our expected public key, then this is a different package and 14211 * we should skip. 14212 */ 14213 14214 final byte[] expectedPublicKey; 14215 try { 14216 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14217 final PublicKey publicKey = verifierSig.getPublicKey(); 14218 expectedPublicKey = publicKey.getEncoded(); 14219 } catch (CertificateException e) { 14220 return -1; 14221 } 14222 14223 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14224 14225 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14226 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14227 + " does not have the expected public key; ignoring"); 14228 return -1; 14229 } 14230 14231 return pkg.applicationInfo.uid; 14232 } 14233 } 14234 14235 @Override 14236 public void finishPackageInstall(int token, boolean didLaunch) { 14237 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14238 14239 if (DEBUG_INSTALL) { 14240 Slog.v(TAG, "BM finishing package install for " + token); 14241 } 14242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14243 14244 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14245 mHandler.sendMessage(msg); 14246 } 14247 14248 /** 14249 * Get the verification agent timeout. Used for both the APK verifier and the 14250 * intent filter verifier. 14251 * 14252 * @return verification timeout in milliseconds 14253 */ 14254 private long getVerificationTimeout() { 14255 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14256 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14257 DEFAULT_VERIFICATION_TIMEOUT); 14258 } 14259 14260 /** 14261 * Get the default verification agent response code. 14262 * 14263 * @return default verification response code 14264 */ 14265 private int getDefaultVerificationResponse(UserHandle user) { 14266 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14267 return PackageManager.VERIFICATION_REJECT; 14268 } 14269 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14270 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14271 DEFAULT_VERIFICATION_RESPONSE); 14272 } 14273 14274 /** 14275 * Check whether or not package verification has been enabled. 14276 * 14277 * @return true if verification should be performed 14278 */ 14279 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14280 if (!DEFAULT_VERIFY_ENABLE) { 14281 return false; 14282 } 14283 14284 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14285 14286 // Check if installing from ADB 14287 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14288 // Do not run verification in a test harness environment 14289 if (ActivityManager.isRunningInTestHarness()) { 14290 return false; 14291 } 14292 if (ensureVerifyAppsEnabled) { 14293 return true; 14294 } 14295 // Check if the developer does not want package verification for ADB installs 14296 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14297 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14298 return false; 14299 } 14300 } else { 14301 // only when not installed from ADB, skip verification for instant apps when 14302 // the installer and verifier are the same. 14303 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14304 if (mInstantAppInstallerActivity != null 14305 && mInstantAppInstallerActivity.packageName.equals( 14306 mRequiredVerifierPackage)) { 14307 try { 14308 mContext.getSystemService(AppOpsManager.class) 14309 .checkPackage(installerUid, mRequiredVerifierPackage); 14310 if (DEBUG_VERIFY) { 14311 Slog.i(TAG, "disable verification for instant app"); 14312 } 14313 return false; 14314 } catch (SecurityException ignore) { } 14315 } 14316 } 14317 } 14318 14319 if (ensureVerifyAppsEnabled) { 14320 return true; 14321 } 14322 14323 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14324 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14325 } 14326 14327 @Override 14328 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14329 throws RemoteException { 14330 mContext.enforceCallingOrSelfPermission( 14331 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14332 "Only intentfilter verification agents can verify applications"); 14333 14334 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14335 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14336 Binder.getCallingUid(), verificationCode, failedDomains); 14337 msg.arg1 = id; 14338 msg.obj = response; 14339 mHandler.sendMessage(msg); 14340 } 14341 14342 @Override 14343 public int getIntentVerificationStatus(String packageName, int userId) { 14344 final int callingUid = Binder.getCallingUid(); 14345 if (UserHandle.getUserId(callingUid) != userId) { 14346 mContext.enforceCallingOrSelfPermission( 14347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14348 "getIntentVerificationStatus" + userId); 14349 } 14350 if (getInstantAppPackageName(callingUid) != null) { 14351 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14352 } 14353 synchronized (mPackages) { 14354 final PackageSetting ps = mSettings.mPackages.get(packageName); 14355 if (ps == null 14356 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14357 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14358 } 14359 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14360 } 14361 } 14362 14363 @Override 14364 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14365 mContext.enforceCallingOrSelfPermission( 14366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14367 14368 boolean result = false; 14369 synchronized (mPackages) { 14370 final PackageSetting ps = mSettings.mPackages.get(packageName); 14371 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14372 return false; 14373 } 14374 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14375 } 14376 if (result) { 14377 scheduleWritePackageRestrictionsLocked(userId); 14378 } 14379 return result; 14380 } 14381 14382 @Override 14383 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14384 String packageName) { 14385 final int callingUid = Binder.getCallingUid(); 14386 if (getInstantAppPackageName(callingUid) != null) { 14387 return ParceledListSlice.emptyList(); 14388 } 14389 synchronized (mPackages) { 14390 final PackageSetting ps = mSettings.mPackages.get(packageName); 14391 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14392 return ParceledListSlice.emptyList(); 14393 } 14394 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14395 } 14396 } 14397 14398 @Override 14399 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14400 if (TextUtils.isEmpty(packageName)) { 14401 return ParceledListSlice.emptyList(); 14402 } 14403 final int callingUid = Binder.getCallingUid(); 14404 final int callingUserId = UserHandle.getUserId(callingUid); 14405 synchronized (mPackages) { 14406 PackageParser.Package pkg = mPackages.get(packageName); 14407 if (pkg == null || pkg.activities == null) { 14408 return ParceledListSlice.emptyList(); 14409 } 14410 if (pkg.mExtras == null) { 14411 return ParceledListSlice.emptyList(); 14412 } 14413 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14414 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14415 return ParceledListSlice.emptyList(); 14416 } 14417 final int count = pkg.activities.size(); 14418 ArrayList<IntentFilter> result = new ArrayList<>(); 14419 for (int n=0; n<count; n++) { 14420 PackageParser.Activity activity = pkg.activities.get(n); 14421 if (activity.intents != null && activity.intents.size() > 0) { 14422 result.addAll(activity.intents); 14423 } 14424 } 14425 return new ParceledListSlice<>(result); 14426 } 14427 } 14428 14429 @Override 14430 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14431 mContext.enforceCallingOrSelfPermission( 14432 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14433 if (UserHandle.getCallingUserId() != userId) { 14434 mContext.enforceCallingOrSelfPermission( 14435 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14436 } 14437 14438 synchronized (mPackages) { 14439 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14440 if (packageName != null) { 14441 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14442 packageName, userId); 14443 } 14444 return result; 14445 } 14446 } 14447 14448 @Override 14449 public String getDefaultBrowserPackageName(int userId) { 14450 if (UserHandle.getCallingUserId() != userId) { 14451 mContext.enforceCallingOrSelfPermission( 14452 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14453 } 14454 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14455 return null; 14456 } 14457 synchronized (mPackages) { 14458 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14459 } 14460 } 14461 14462 /** 14463 * Get the "allow unknown sources" setting. 14464 * 14465 * @return the current "allow unknown sources" setting 14466 */ 14467 private int getUnknownSourcesSettings() { 14468 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14469 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14470 -1); 14471 } 14472 14473 @Override 14474 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14475 final int callingUid = Binder.getCallingUid(); 14476 if (getInstantAppPackageName(callingUid) != null) { 14477 return; 14478 } 14479 // writer 14480 synchronized (mPackages) { 14481 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14482 if (targetPackageSetting == null 14483 || filterAppAccessLPr( 14484 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14485 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14486 } 14487 14488 PackageSetting installerPackageSetting; 14489 if (installerPackageName != null) { 14490 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14491 if (installerPackageSetting == null) { 14492 throw new IllegalArgumentException("Unknown installer package: " 14493 + installerPackageName); 14494 } 14495 } else { 14496 installerPackageSetting = null; 14497 } 14498 14499 Signature[] callerSignature; 14500 Object obj = mSettings.getUserIdLPr(callingUid); 14501 if (obj != null) { 14502 if (obj instanceof SharedUserSetting) { 14503 callerSignature = 14504 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14505 } else if (obj instanceof PackageSetting) { 14506 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14507 } else { 14508 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14509 } 14510 } else { 14511 throw new SecurityException("Unknown calling UID: " + callingUid); 14512 } 14513 14514 // Verify: can't set installerPackageName to a package that is 14515 // not signed with the same cert as the caller. 14516 if (installerPackageSetting != null) { 14517 if (compareSignatures(callerSignature, 14518 installerPackageSetting.signatures.mSigningDetails.signatures) 14519 != PackageManager.SIGNATURE_MATCH) { 14520 throw new SecurityException( 14521 "Caller does not have same cert as new installer package " 14522 + installerPackageName); 14523 } 14524 } 14525 14526 // Verify: if target already has an installer package, it must 14527 // be signed with the same cert as the caller. 14528 if (targetPackageSetting.installerPackageName != null) { 14529 PackageSetting setting = mSettings.mPackages.get( 14530 targetPackageSetting.installerPackageName); 14531 // If the currently set package isn't valid, then it's always 14532 // okay to change it. 14533 if (setting != null) { 14534 if (compareSignatures(callerSignature, 14535 setting.signatures.mSigningDetails.signatures) 14536 != PackageManager.SIGNATURE_MATCH) { 14537 throw new SecurityException( 14538 "Caller does not have same cert as old installer package " 14539 + targetPackageSetting.installerPackageName); 14540 } 14541 } 14542 } 14543 14544 // Okay! 14545 targetPackageSetting.installerPackageName = installerPackageName; 14546 if (installerPackageName != null) { 14547 mSettings.mInstallerPackages.add(installerPackageName); 14548 } 14549 scheduleWriteSettingsLocked(); 14550 } 14551 } 14552 14553 @Override 14554 public void setApplicationCategoryHint(String packageName, int categoryHint, 14555 String callerPackageName) { 14556 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14557 throw new SecurityException("Instant applications don't have access to this method"); 14558 } 14559 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14560 callerPackageName); 14561 synchronized (mPackages) { 14562 PackageSetting ps = mSettings.mPackages.get(packageName); 14563 if (ps == null) { 14564 throw new IllegalArgumentException("Unknown target package " + packageName); 14565 } 14566 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14567 throw new IllegalArgumentException("Unknown target package " + packageName); 14568 } 14569 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14570 throw new IllegalArgumentException("Calling package " + callerPackageName 14571 + " is not installer for " + packageName); 14572 } 14573 14574 if (ps.categoryHint != categoryHint) { 14575 ps.categoryHint = categoryHint; 14576 scheduleWriteSettingsLocked(); 14577 } 14578 } 14579 } 14580 14581 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14582 // Queue up an async operation since the package installation may take a little while. 14583 mHandler.post(new Runnable() { 14584 public void run() { 14585 mHandler.removeCallbacks(this); 14586 // Result object to be returned 14587 PackageInstalledInfo res = new PackageInstalledInfo(); 14588 res.setReturnCode(currentStatus); 14589 res.uid = -1; 14590 res.pkg = null; 14591 res.removedInfo = null; 14592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14593 args.doPreInstall(res.returnCode); 14594 synchronized (mInstallLock) { 14595 installPackageTracedLI(args, res); 14596 } 14597 args.doPostInstall(res.returnCode, res.uid); 14598 } 14599 14600 // A restore should be performed at this point if (a) the install 14601 // succeeded, (b) the operation is not an update, and (c) the new 14602 // package has not opted out of backup participation. 14603 final boolean update = res.removedInfo != null 14604 && res.removedInfo.removedPackage != null; 14605 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14606 boolean doRestore = !update 14607 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14608 14609 // Set up the post-install work request bookkeeping. This will be used 14610 // and cleaned up by the post-install event handling regardless of whether 14611 // there's a restore pass performed. Token values are >= 1. 14612 int token; 14613 if (mNextInstallToken < 0) mNextInstallToken = 1; 14614 token = mNextInstallToken++; 14615 14616 PostInstallData data = new PostInstallData(args, res); 14617 mRunningInstalls.put(token, data); 14618 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14619 14620 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14621 // Pass responsibility to the Backup Manager. It will perform a 14622 // restore if appropriate, then pass responsibility back to the 14623 // Package Manager to run the post-install observer callbacks 14624 // and broadcasts. 14625 IBackupManager bm = IBackupManager.Stub.asInterface( 14626 ServiceManager.getService(Context.BACKUP_SERVICE)); 14627 if (bm != null) { 14628 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14629 + " to BM for possible restore"); 14630 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14631 try { 14632 // TODO: http://b/22388012 14633 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14634 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14635 } else { 14636 doRestore = false; 14637 } 14638 } catch (RemoteException e) { 14639 // can't happen; the backup manager is local 14640 } catch (Exception e) { 14641 Slog.e(TAG, "Exception trying to enqueue restore", e); 14642 doRestore = false; 14643 } 14644 } else { 14645 Slog.e(TAG, "Backup Manager not found!"); 14646 doRestore = false; 14647 } 14648 } 14649 14650 if (!doRestore) { 14651 // No restore possible, or the Backup Manager was mysteriously not 14652 // available -- just fire the post-install work request directly. 14653 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14654 14655 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14656 14657 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14658 mHandler.sendMessage(msg); 14659 } 14660 } 14661 }); 14662 } 14663 14664 /** 14665 * Callback from PackageSettings whenever an app is first transitioned out of the 14666 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14667 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14668 * here whether the app is the target of an ongoing install, and only send the 14669 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14670 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14671 * handling. 14672 */ 14673 void notifyFirstLaunch(final String packageName, final String installerPackage, 14674 final int userId) { 14675 // Serialize this with the rest of the install-process message chain. In the 14676 // restore-at-install case, this Runnable will necessarily run before the 14677 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14678 // are coherent. In the non-restore case, the app has already completed install 14679 // and been launched through some other means, so it is not in a problematic 14680 // state for observers to see the FIRST_LAUNCH signal. 14681 mHandler.post(new Runnable() { 14682 @Override 14683 public void run() { 14684 for (int i = 0; i < mRunningInstalls.size(); i++) { 14685 final PostInstallData data = mRunningInstalls.valueAt(i); 14686 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14687 continue; 14688 } 14689 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14690 // right package; but is it for the right user? 14691 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14692 if (userId == data.res.newUsers[uIndex]) { 14693 if (DEBUG_BACKUP) { 14694 Slog.i(TAG, "Package " + packageName 14695 + " being restored so deferring FIRST_LAUNCH"); 14696 } 14697 return; 14698 } 14699 } 14700 } 14701 } 14702 // didn't find it, so not being restored 14703 if (DEBUG_BACKUP) { 14704 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14705 } 14706 final boolean isInstantApp = isInstantApp(packageName, userId); 14707 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14708 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14709 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14710 } 14711 }); 14712 } 14713 14714 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14715 int[] userIds, int[] instantUserIds) { 14716 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14717 installerPkg, null, userIds, instantUserIds); 14718 } 14719 14720 private abstract class HandlerParams { 14721 private static final int MAX_RETRIES = 4; 14722 14723 /** 14724 * Number of times startCopy() has been attempted and had a non-fatal 14725 * error. 14726 */ 14727 private int mRetries = 0; 14728 14729 /** User handle for the user requesting the information or installation. */ 14730 private final UserHandle mUser; 14731 String traceMethod; 14732 int traceCookie; 14733 14734 HandlerParams(UserHandle user) { 14735 mUser = user; 14736 } 14737 14738 UserHandle getUser() { 14739 return mUser; 14740 } 14741 14742 HandlerParams setTraceMethod(String traceMethod) { 14743 this.traceMethod = traceMethod; 14744 return this; 14745 } 14746 14747 HandlerParams setTraceCookie(int traceCookie) { 14748 this.traceCookie = traceCookie; 14749 return this; 14750 } 14751 14752 final boolean startCopy() { 14753 boolean res; 14754 try { 14755 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14756 14757 if (++mRetries > MAX_RETRIES) { 14758 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14759 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14760 handleServiceError(); 14761 return false; 14762 } else { 14763 handleStartCopy(); 14764 res = true; 14765 } 14766 } catch (RemoteException e) { 14767 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14768 mHandler.sendEmptyMessage(MCS_RECONNECT); 14769 res = false; 14770 } 14771 handleReturnCode(); 14772 return res; 14773 } 14774 14775 final void serviceError() { 14776 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14777 handleServiceError(); 14778 handleReturnCode(); 14779 } 14780 14781 abstract void handleStartCopy() throws RemoteException; 14782 abstract void handleServiceError(); 14783 abstract void handleReturnCode(); 14784 } 14785 14786 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14787 for (File path : paths) { 14788 try { 14789 mcs.clearDirectory(path.getAbsolutePath()); 14790 } catch (RemoteException e) { 14791 } 14792 } 14793 } 14794 14795 static class OriginInfo { 14796 /** 14797 * Location where install is coming from, before it has been 14798 * copied/renamed into place. This could be a single monolithic APK 14799 * file, or a cluster directory. This location may be untrusted. 14800 */ 14801 final File file; 14802 14803 /** 14804 * Flag indicating that {@link #file} or {@link #cid} has already been 14805 * staged, meaning downstream users don't need to defensively copy the 14806 * contents. 14807 */ 14808 final boolean staged; 14809 14810 /** 14811 * Flag indicating that {@link #file} or {@link #cid} is an already 14812 * installed app that is being moved. 14813 */ 14814 final boolean existing; 14815 14816 final String resolvedPath; 14817 final File resolvedFile; 14818 14819 static OriginInfo fromNothing() { 14820 return new OriginInfo(null, false, false); 14821 } 14822 14823 static OriginInfo fromUntrustedFile(File file) { 14824 return new OriginInfo(file, false, false); 14825 } 14826 14827 static OriginInfo fromExistingFile(File file) { 14828 return new OriginInfo(file, false, true); 14829 } 14830 14831 static OriginInfo fromStagedFile(File file) { 14832 return new OriginInfo(file, true, false); 14833 } 14834 14835 private OriginInfo(File file, boolean staged, boolean existing) { 14836 this.file = file; 14837 this.staged = staged; 14838 this.existing = existing; 14839 14840 if (file != null) { 14841 resolvedPath = file.getAbsolutePath(); 14842 resolvedFile = file; 14843 } else { 14844 resolvedPath = null; 14845 resolvedFile = null; 14846 } 14847 } 14848 } 14849 14850 static class MoveInfo { 14851 final int moveId; 14852 final String fromUuid; 14853 final String toUuid; 14854 final String packageName; 14855 final String dataAppName; 14856 final int appId; 14857 final String seinfo; 14858 final int targetSdkVersion; 14859 14860 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14861 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14862 this.moveId = moveId; 14863 this.fromUuid = fromUuid; 14864 this.toUuid = toUuid; 14865 this.packageName = packageName; 14866 this.dataAppName = dataAppName; 14867 this.appId = appId; 14868 this.seinfo = seinfo; 14869 this.targetSdkVersion = targetSdkVersion; 14870 } 14871 } 14872 14873 static class VerificationInfo { 14874 /** A constant used to indicate that a uid value is not present. */ 14875 public static final int NO_UID = -1; 14876 14877 /** URI referencing where the package was downloaded from. */ 14878 final Uri originatingUri; 14879 14880 /** HTTP referrer URI associated with the originatingURI. */ 14881 final Uri referrer; 14882 14883 /** UID of the application that the install request originated from. */ 14884 final int originatingUid; 14885 14886 /** UID of application requesting the install */ 14887 final int installerUid; 14888 14889 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14890 this.originatingUri = originatingUri; 14891 this.referrer = referrer; 14892 this.originatingUid = originatingUid; 14893 this.installerUid = installerUid; 14894 } 14895 } 14896 14897 class InstallParams extends HandlerParams { 14898 final OriginInfo origin; 14899 final MoveInfo move; 14900 final IPackageInstallObserver2 observer; 14901 int installFlags; 14902 final String installerPackageName; 14903 final String volumeUuid; 14904 private InstallArgs mArgs; 14905 private int mRet; 14906 final String packageAbiOverride; 14907 final String[] grantedRuntimePermissions; 14908 final VerificationInfo verificationInfo; 14909 final PackageParser.SigningDetails signingDetails; 14910 final int installReason; 14911 14912 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14913 int installFlags, String installerPackageName, String volumeUuid, 14914 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14915 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14916 super(user); 14917 this.origin = origin; 14918 this.move = move; 14919 this.observer = observer; 14920 this.installFlags = installFlags; 14921 this.installerPackageName = installerPackageName; 14922 this.volumeUuid = volumeUuid; 14923 this.verificationInfo = verificationInfo; 14924 this.packageAbiOverride = packageAbiOverride; 14925 this.grantedRuntimePermissions = grantedPermissions; 14926 this.signingDetails = signingDetails; 14927 this.installReason = installReason; 14928 } 14929 14930 @Override 14931 public String toString() { 14932 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14933 + " file=" + origin.file + "}"; 14934 } 14935 14936 private int installLocationPolicy(PackageInfoLite pkgLite) { 14937 String packageName = pkgLite.packageName; 14938 int installLocation = pkgLite.installLocation; 14939 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14940 // reader 14941 synchronized (mPackages) { 14942 // Currently installed package which the new package is attempting to replace or 14943 // null if no such package is installed. 14944 PackageParser.Package installedPkg = mPackages.get(packageName); 14945 // Package which currently owns the data which the new package will own if installed. 14946 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14947 // will be null whereas dataOwnerPkg will contain information about the package 14948 // which was uninstalled while keeping its data. 14949 PackageParser.Package dataOwnerPkg = installedPkg; 14950 if (dataOwnerPkg == null) { 14951 PackageSetting ps = mSettings.mPackages.get(packageName); 14952 if (ps != null) { 14953 dataOwnerPkg = ps.pkg; 14954 } 14955 } 14956 14957 if (dataOwnerPkg != null) { 14958 // If installed, the package will get access to data left on the device by its 14959 // predecessor. As a security measure, this is permited only if this is not a 14960 // version downgrade or if the predecessor package is marked as debuggable and 14961 // a downgrade is explicitly requested. 14962 // 14963 // On debuggable platform builds, downgrades are permitted even for 14964 // non-debuggable packages to make testing easier. Debuggable platform builds do 14965 // not offer security guarantees and thus it's OK to disable some security 14966 // mechanisms to make debugging/testing easier on those builds. However, even on 14967 // debuggable builds downgrades of packages are permitted only if requested via 14968 // installFlags. This is because we aim to keep the behavior of debuggable 14969 // platform builds as close as possible to the behavior of non-debuggable 14970 // platform builds. 14971 final boolean downgradeRequested = 14972 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14973 final boolean packageDebuggable = 14974 (dataOwnerPkg.applicationInfo.flags 14975 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14976 final boolean downgradePermitted = 14977 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14978 if (!downgradePermitted) { 14979 try { 14980 checkDowngrade(dataOwnerPkg, pkgLite); 14981 } catch (PackageManagerException e) { 14982 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14983 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14984 } 14985 } 14986 } 14987 14988 if (installedPkg != null) { 14989 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14990 // Check for updated system application. 14991 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14992 if (onSd) { 14993 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14994 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14995 } 14996 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14997 } else { 14998 if (onSd) { 14999 // Install flag overrides everything. 15000 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15001 } 15002 // If current upgrade specifies particular preference 15003 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15004 // Application explicitly specified internal. 15005 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15006 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15007 // App explictly prefers external. Let policy decide 15008 } else { 15009 // Prefer previous location 15010 if (isExternal(installedPkg)) { 15011 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15012 } 15013 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15014 } 15015 } 15016 } else { 15017 // Invalid install. Return error code 15018 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15019 } 15020 } 15021 } 15022 // All the special cases have been taken care of. 15023 // Return result based on recommended install location. 15024 if (onSd) { 15025 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15026 } 15027 return pkgLite.recommendedInstallLocation; 15028 } 15029 15030 /* 15031 * Invoke remote method to get package information and install 15032 * location values. Override install location based on default 15033 * policy if needed and then create install arguments based 15034 * on the install location. 15035 */ 15036 public void handleStartCopy() throws RemoteException { 15037 int ret = PackageManager.INSTALL_SUCCEEDED; 15038 15039 // If we're already staged, we've firmly committed to an install location 15040 if (origin.staged) { 15041 if (origin.file != null) { 15042 installFlags |= PackageManager.INSTALL_INTERNAL; 15043 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15044 } else { 15045 throw new IllegalStateException("Invalid stage location"); 15046 } 15047 } 15048 15049 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15050 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15051 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15052 PackageInfoLite pkgLite = null; 15053 15054 if (onInt && onSd) { 15055 // Check if both bits are set. 15056 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15057 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15058 } else if (onSd && ephemeral) { 15059 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15060 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15061 } else { 15062 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15063 packageAbiOverride); 15064 15065 if (DEBUG_EPHEMERAL && ephemeral) { 15066 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15067 } 15068 15069 /* 15070 * If we have too little free space, try to free cache 15071 * before giving up. 15072 */ 15073 if (!origin.staged && pkgLite.recommendedInstallLocation 15074 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15075 // TODO: focus freeing disk space on the target device 15076 final StorageManager storage = StorageManager.from(mContext); 15077 final long lowThreshold = storage.getStorageLowBytes( 15078 Environment.getDataDirectory()); 15079 15080 final long sizeBytes = mContainerService.calculateInstalledSize( 15081 origin.resolvedPath, packageAbiOverride); 15082 15083 try { 15084 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15085 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15086 installFlags, packageAbiOverride); 15087 } catch (InstallerException e) { 15088 Slog.w(TAG, "Failed to free cache", e); 15089 } 15090 15091 /* 15092 * The cache free must have deleted the file we 15093 * downloaded to install. 15094 * 15095 * TODO: fix the "freeCache" call to not delete 15096 * the file we care about. 15097 */ 15098 if (pkgLite.recommendedInstallLocation 15099 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15100 pkgLite.recommendedInstallLocation 15101 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15102 } 15103 } 15104 } 15105 15106 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15107 int loc = pkgLite.recommendedInstallLocation; 15108 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15109 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15110 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15111 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15112 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15113 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15114 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15115 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15116 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15117 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15118 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15119 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15120 } else { 15121 // Override with defaults if needed. 15122 loc = installLocationPolicy(pkgLite); 15123 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15124 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15125 } else if (!onSd && !onInt) { 15126 // Override install location with flags 15127 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15128 // Set the flag to install on external media. 15129 installFlags |= PackageManager.INSTALL_EXTERNAL; 15130 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15131 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15132 if (DEBUG_EPHEMERAL) { 15133 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15134 } 15135 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15136 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15137 |PackageManager.INSTALL_INTERNAL); 15138 } else { 15139 // Make sure the flag for installing on external 15140 // media is unset 15141 installFlags |= PackageManager.INSTALL_INTERNAL; 15142 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15143 } 15144 } 15145 } 15146 } 15147 15148 final InstallArgs args = createInstallArgs(this); 15149 mArgs = args; 15150 15151 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15152 // TODO: http://b/22976637 15153 // Apps installed for "all" users use the device owner to verify the app 15154 UserHandle verifierUser = getUser(); 15155 if (verifierUser == UserHandle.ALL) { 15156 verifierUser = UserHandle.SYSTEM; 15157 } 15158 15159 /* 15160 * Determine if we have any installed package verifiers. If we 15161 * do, then we'll defer to them to verify the packages. 15162 */ 15163 final int requiredUid = mRequiredVerifierPackage == null ? -1 15164 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15165 verifierUser.getIdentifier()); 15166 final int installerUid = 15167 verificationInfo == null ? -1 : verificationInfo.installerUid; 15168 if (!origin.existing && requiredUid != -1 15169 && isVerificationEnabled( 15170 verifierUser.getIdentifier(), installFlags, installerUid)) { 15171 final Intent verification = new Intent( 15172 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15173 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15174 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15175 PACKAGE_MIME_TYPE); 15176 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15177 15178 // Query all live verifiers based on current user state 15179 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15180 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15181 false /*allowDynamicSplits*/); 15182 15183 if (DEBUG_VERIFY) { 15184 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15185 + verification.toString() + " with " + pkgLite.verifiers.length 15186 + " optional verifiers"); 15187 } 15188 15189 final int verificationId = mPendingVerificationToken++; 15190 15191 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15192 15193 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15194 installerPackageName); 15195 15196 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15197 installFlags); 15198 15199 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15200 pkgLite.packageName); 15201 15202 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15203 pkgLite.versionCode); 15204 15205 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15206 pkgLite.getLongVersionCode()); 15207 15208 if (verificationInfo != null) { 15209 if (verificationInfo.originatingUri != null) { 15210 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15211 verificationInfo.originatingUri); 15212 } 15213 if (verificationInfo.referrer != null) { 15214 verification.putExtra(Intent.EXTRA_REFERRER, 15215 verificationInfo.referrer); 15216 } 15217 if (verificationInfo.originatingUid >= 0) { 15218 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15219 verificationInfo.originatingUid); 15220 } 15221 if (verificationInfo.installerUid >= 0) { 15222 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15223 verificationInfo.installerUid); 15224 } 15225 } 15226 15227 final PackageVerificationState verificationState = new PackageVerificationState( 15228 requiredUid, args); 15229 15230 mPendingVerification.append(verificationId, verificationState); 15231 15232 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15233 receivers, verificationState); 15234 15235 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15236 final long idleDuration = getVerificationTimeout(); 15237 15238 /* 15239 * If any sufficient verifiers were listed in the package 15240 * manifest, attempt to ask them. 15241 */ 15242 if (sufficientVerifiers != null) { 15243 final int N = sufficientVerifiers.size(); 15244 if (N == 0) { 15245 Slog.i(TAG, "Additional verifiers required, but none installed."); 15246 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15247 } else { 15248 for (int i = 0; i < N; i++) { 15249 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15250 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15251 verifierComponent.getPackageName(), idleDuration, 15252 verifierUser.getIdentifier(), false, "package verifier"); 15253 15254 final Intent sufficientIntent = new Intent(verification); 15255 sufficientIntent.setComponent(verifierComponent); 15256 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15257 } 15258 } 15259 } 15260 15261 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15262 mRequiredVerifierPackage, receivers); 15263 if (ret == PackageManager.INSTALL_SUCCEEDED 15264 && mRequiredVerifierPackage != null) { 15265 Trace.asyncTraceBegin( 15266 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15267 /* 15268 * Send the intent to the required verification agent, 15269 * but only start the verification timeout after the 15270 * target BroadcastReceivers have run. 15271 */ 15272 verification.setComponent(requiredVerifierComponent); 15273 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15274 mRequiredVerifierPackage, idleDuration, 15275 verifierUser.getIdentifier(), false, "package verifier"); 15276 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15277 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15278 new BroadcastReceiver() { 15279 @Override 15280 public void onReceive(Context context, Intent intent) { 15281 final Message msg = mHandler 15282 .obtainMessage(CHECK_PENDING_VERIFICATION); 15283 msg.arg1 = verificationId; 15284 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15285 } 15286 }, null, 0, null, null); 15287 15288 /* 15289 * We don't want the copy to proceed until verification 15290 * succeeds, so null out this field. 15291 */ 15292 mArgs = null; 15293 } 15294 } else { 15295 /* 15296 * No package verification is enabled, so immediately start 15297 * the remote call to initiate copy using temporary file. 15298 */ 15299 ret = args.copyApk(mContainerService, true); 15300 } 15301 } 15302 15303 mRet = ret; 15304 } 15305 15306 @Override 15307 void handleReturnCode() { 15308 // If mArgs is null, then MCS couldn't be reached. When it 15309 // reconnects, it will try again to install. At that point, this 15310 // will succeed. 15311 if (mArgs != null) { 15312 processPendingInstall(mArgs, mRet); 15313 } 15314 } 15315 15316 @Override 15317 void handleServiceError() { 15318 mArgs = createInstallArgs(this); 15319 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15320 } 15321 } 15322 15323 private InstallArgs createInstallArgs(InstallParams params) { 15324 if (params.move != null) { 15325 return new MoveInstallArgs(params); 15326 } else { 15327 return new FileInstallArgs(params); 15328 } 15329 } 15330 15331 /** 15332 * Create args that describe an existing installed package. Typically used 15333 * when cleaning up old installs, or used as a move source. 15334 */ 15335 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15336 String resourcePath, String[] instructionSets) { 15337 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15338 } 15339 15340 static abstract class InstallArgs { 15341 /** @see InstallParams#origin */ 15342 final OriginInfo origin; 15343 /** @see InstallParams#move */ 15344 final MoveInfo move; 15345 15346 final IPackageInstallObserver2 observer; 15347 // Always refers to PackageManager flags only 15348 final int installFlags; 15349 final String installerPackageName; 15350 final String volumeUuid; 15351 final UserHandle user; 15352 final String abiOverride; 15353 final String[] installGrantPermissions; 15354 /** If non-null, drop an async trace when the install completes */ 15355 final String traceMethod; 15356 final int traceCookie; 15357 final PackageParser.SigningDetails signingDetails; 15358 final int installReason; 15359 15360 // The list of instruction sets supported by this app. This is currently 15361 // only used during the rmdex() phase to clean up resources. We can get rid of this 15362 // if we move dex files under the common app path. 15363 /* nullable */ String[] instructionSets; 15364 15365 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15366 int installFlags, String installerPackageName, String volumeUuid, 15367 UserHandle user, String[] instructionSets, 15368 String abiOverride, String[] installGrantPermissions, 15369 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15370 int installReason) { 15371 this.origin = origin; 15372 this.move = move; 15373 this.installFlags = installFlags; 15374 this.observer = observer; 15375 this.installerPackageName = installerPackageName; 15376 this.volumeUuid = volumeUuid; 15377 this.user = user; 15378 this.instructionSets = instructionSets; 15379 this.abiOverride = abiOverride; 15380 this.installGrantPermissions = installGrantPermissions; 15381 this.traceMethod = traceMethod; 15382 this.traceCookie = traceCookie; 15383 this.signingDetails = signingDetails; 15384 this.installReason = installReason; 15385 } 15386 15387 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15388 abstract int doPreInstall(int status); 15389 15390 /** 15391 * Rename package into final resting place. All paths on the given 15392 * scanned package should be updated to reflect the rename. 15393 */ 15394 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15395 abstract int doPostInstall(int status, int uid); 15396 15397 /** @see PackageSettingBase#codePathString */ 15398 abstract String getCodePath(); 15399 /** @see PackageSettingBase#resourcePathString */ 15400 abstract String getResourcePath(); 15401 15402 // Need installer lock especially for dex file removal. 15403 abstract void cleanUpResourcesLI(); 15404 abstract boolean doPostDeleteLI(boolean delete); 15405 15406 /** 15407 * Called before the source arguments are copied. This is used mostly 15408 * for MoveParams when it needs to read the source file to put it in the 15409 * destination. 15410 */ 15411 int doPreCopy() { 15412 return PackageManager.INSTALL_SUCCEEDED; 15413 } 15414 15415 /** 15416 * Called after the source arguments are copied. This is used mostly for 15417 * MoveParams when it needs to read the source file to put it in the 15418 * destination. 15419 */ 15420 int doPostCopy(int uid) { 15421 return PackageManager.INSTALL_SUCCEEDED; 15422 } 15423 15424 protected boolean isFwdLocked() { 15425 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15426 } 15427 15428 protected boolean isExternalAsec() { 15429 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15430 } 15431 15432 protected boolean isEphemeral() { 15433 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15434 } 15435 15436 UserHandle getUser() { 15437 return user; 15438 } 15439 } 15440 15441 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15442 if (!allCodePaths.isEmpty()) { 15443 if (instructionSets == null) { 15444 throw new IllegalStateException("instructionSet == null"); 15445 } 15446 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15447 for (String codePath : allCodePaths) { 15448 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15449 try { 15450 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15451 } catch (InstallerException ignored) { 15452 } 15453 } 15454 } 15455 } 15456 } 15457 15458 /** 15459 * Logic to handle installation of non-ASEC applications, including copying 15460 * and renaming logic. 15461 */ 15462 class FileInstallArgs extends InstallArgs { 15463 private File codeFile; 15464 private File resourceFile; 15465 15466 // Example topology: 15467 // /data/app/com.example/base.apk 15468 // /data/app/com.example/split_foo.apk 15469 // /data/app/com.example/lib/arm/libfoo.so 15470 // /data/app/com.example/lib/arm64/libfoo.so 15471 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15472 15473 /** New install */ 15474 FileInstallArgs(InstallParams params) { 15475 super(params.origin, params.move, params.observer, params.installFlags, 15476 params.installerPackageName, params.volumeUuid, 15477 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15478 params.grantedRuntimePermissions, 15479 params.traceMethod, params.traceCookie, params.signingDetails, 15480 params.installReason); 15481 if (isFwdLocked()) { 15482 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15483 } 15484 } 15485 15486 /** Existing install */ 15487 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15488 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15489 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15490 PackageManager.INSTALL_REASON_UNKNOWN); 15491 this.codeFile = (codePath != null) ? new File(codePath) : null; 15492 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15493 } 15494 15495 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15497 try { 15498 return doCopyApk(imcs, temp); 15499 } finally { 15500 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15501 } 15502 } 15503 15504 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15505 if (origin.staged) { 15506 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15507 codeFile = origin.file; 15508 resourceFile = origin.file; 15509 return PackageManager.INSTALL_SUCCEEDED; 15510 } 15511 15512 try { 15513 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15514 final File tempDir = 15515 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15516 codeFile = tempDir; 15517 resourceFile = tempDir; 15518 } catch (IOException e) { 15519 Slog.w(TAG, "Failed to create copy file: " + e); 15520 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15521 } 15522 15523 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15524 @Override 15525 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15526 if (!FileUtils.isValidExtFilename(name)) { 15527 throw new IllegalArgumentException("Invalid filename: " + name); 15528 } 15529 try { 15530 final File file = new File(codeFile, name); 15531 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15532 O_RDWR | O_CREAT, 0644); 15533 Os.chmod(file.getAbsolutePath(), 0644); 15534 return new ParcelFileDescriptor(fd); 15535 } catch (ErrnoException e) { 15536 throw new RemoteException("Failed to open: " + e.getMessage()); 15537 } 15538 } 15539 }; 15540 15541 int ret = PackageManager.INSTALL_SUCCEEDED; 15542 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15543 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15544 Slog.e(TAG, "Failed to copy package"); 15545 return ret; 15546 } 15547 15548 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15549 NativeLibraryHelper.Handle handle = null; 15550 try { 15551 handle = NativeLibraryHelper.Handle.create(codeFile); 15552 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15553 abiOverride); 15554 } catch (IOException e) { 15555 Slog.e(TAG, "Copying native libraries failed", e); 15556 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15557 } finally { 15558 IoUtils.closeQuietly(handle); 15559 } 15560 15561 return ret; 15562 } 15563 15564 int doPreInstall(int status) { 15565 if (status != PackageManager.INSTALL_SUCCEEDED) { 15566 cleanUp(); 15567 } 15568 return status; 15569 } 15570 15571 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15572 if (status != PackageManager.INSTALL_SUCCEEDED) { 15573 cleanUp(); 15574 return false; 15575 } 15576 15577 final File targetDir = codeFile.getParentFile(); 15578 final File beforeCodeFile = codeFile; 15579 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15580 15581 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15582 try { 15583 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15584 } catch (ErrnoException e) { 15585 Slog.w(TAG, "Failed to rename", e); 15586 return false; 15587 } 15588 15589 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15590 Slog.w(TAG, "Failed to restorecon"); 15591 return false; 15592 } 15593 15594 // Reflect the rename internally 15595 codeFile = afterCodeFile; 15596 resourceFile = afterCodeFile; 15597 15598 // Reflect the rename in scanned details 15599 try { 15600 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15601 } catch (IOException e) { 15602 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15603 return false; 15604 } 15605 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15606 afterCodeFile, pkg.baseCodePath)); 15607 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15608 afterCodeFile, pkg.splitCodePaths)); 15609 15610 // Reflect the rename in app info 15611 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15612 pkg.setApplicationInfoCodePath(pkg.codePath); 15613 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15614 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15615 pkg.setApplicationInfoResourcePath(pkg.codePath); 15616 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15617 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15618 15619 return true; 15620 } 15621 15622 int doPostInstall(int status, int uid) { 15623 if (status != PackageManager.INSTALL_SUCCEEDED) { 15624 cleanUp(); 15625 } 15626 return status; 15627 } 15628 15629 @Override 15630 String getCodePath() { 15631 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15632 } 15633 15634 @Override 15635 String getResourcePath() { 15636 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15637 } 15638 15639 private boolean cleanUp() { 15640 if (codeFile == null || !codeFile.exists()) { 15641 return false; 15642 } 15643 15644 removeCodePathLI(codeFile); 15645 15646 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15647 resourceFile.delete(); 15648 } 15649 15650 return true; 15651 } 15652 15653 void cleanUpResourcesLI() { 15654 // Try enumerating all code paths before deleting 15655 List<String> allCodePaths = Collections.EMPTY_LIST; 15656 if (codeFile != null && codeFile.exists()) { 15657 try { 15658 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15659 allCodePaths = pkg.getAllCodePaths(); 15660 } catch (PackageParserException e) { 15661 // Ignored; we tried our best 15662 } 15663 } 15664 15665 cleanUp(); 15666 removeDexFiles(allCodePaths, instructionSets); 15667 } 15668 15669 boolean doPostDeleteLI(boolean delete) { 15670 // XXX err, shouldn't we respect the delete flag? 15671 cleanUpResourcesLI(); 15672 return true; 15673 } 15674 } 15675 15676 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15677 PackageManagerException { 15678 if (copyRet < 0) { 15679 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15680 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15681 throw new PackageManagerException(copyRet, message); 15682 } 15683 } 15684 } 15685 15686 /** 15687 * Extract the StorageManagerService "container ID" from the full code path of an 15688 * .apk. 15689 */ 15690 static String cidFromCodePath(String fullCodePath) { 15691 int eidx = fullCodePath.lastIndexOf("/"); 15692 String subStr1 = fullCodePath.substring(0, eidx); 15693 int sidx = subStr1.lastIndexOf("/"); 15694 return subStr1.substring(sidx+1, eidx); 15695 } 15696 15697 /** 15698 * Logic to handle movement of existing installed applications. 15699 */ 15700 class MoveInstallArgs extends InstallArgs { 15701 private File codeFile; 15702 private File resourceFile; 15703 15704 /** New install */ 15705 MoveInstallArgs(InstallParams params) { 15706 super(params.origin, params.move, params.observer, params.installFlags, 15707 params.installerPackageName, params.volumeUuid, 15708 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15709 params.grantedRuntimePermissions, 15710 params.traceMethod, params.traceCookie, params.signingDetails, 15711 params.installReason); 15712 } 15713 15714 int copyApk(IMediaContainerService imcs, boolean temp) { 15715 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15716 + move.fromUuid + " to " + move.toUuid); 15717 synchronized (mInstaller) { 15718 try { 15719 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15720 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15721 } catch (InstallerException e) { 15722 Slog.w(TAG, "Failed to move app", e); 15723 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15724 } 15725 } 15726 15727 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15728 resourceFile = codeFile; 15729 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15730 15731 return PackageManager.INSTALL_SUCCEEDED; 15732 } 15733 15734 int doPreInstall(int status) { 15735 if (status != PackageManager.INSTALL_SUCCEEDED) { 15736 cleanUp(move.toUuid); 15737 } 15738 return status; 15739 } 15740 15741 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15742 if (status != PackageManager.INSTALL_SUCCEEDED) { 15743 cleanUp(move.toUuid); 15744 return false; 15745 } 15746 15747 // Reflect the move in app info 15748 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15749 pkg.setApplicationInfoCodePath(pkg.codePath); 15750 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15751 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15752 pkg.setApplicationInfoResourcePath(pkg.codePath); 15753 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15754 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15755 15756 return true; 15757 } 15758 15759 int doPostInstall(int status, int uid) { 15760 if (status == PackageManager.INSTALL_SUCCEEDED) { 15761 cleanUp(move.fromUuid); 15762 } else { 15763 cleanUp(move.toUuid); 15764 } 15765 return status; 15766 } 15767 15768 @Override 15769 String getCodePath() { 15770 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15771 } 15772 15773 @Override 15774 String getResourcePath() { 15775 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15776 } 15777 15778 private boolean cleanUp(String volumeUuid) { 15779 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15780 move.dataAppName); 15781 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15782 final int[] userIds = sUserManager.getUserIds(); 15783 synchronized (mInstallLock) { 15784 // Clean up both app data and code 15785 // All package moves are frozen until finished 15786 for (int userId : userIds) { 15787 try { 15788 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15789 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15790 } catch (InstallerException e) { 15791 Slog.w(TAG, String.valueOf(e)); 15792 } 15793 } 15794 removeCodePathLI(codeFile); 15795 } 15796 return true; 15797 } 15798 15799 void cleanUpResourcesLI() { 15800 throw new UnsupportedOperationException(); 15801 } 15802 15803 boolean doPostDeleteLI(boolean delete) { 15804 throw new UnsupportedOperationException(); 15805 } 15806 } 15807 15808 static String getAsecPackageName(String packageCid) { 15809 int idx = packageCid.lastIndexOf("-"); 15810 if (idx == -1) { 15811 return packageCid; 15812 } 15813 return packageCid.substring(0, idx); 15814 } 15815 15816 // Utility method used to create code paths based on package name and available index. 15817 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15818 String idxStr = ""; 15819 int idx = 1; 15820 // Fall back to default value of idx=1 if prefix is not 15821 // part of oldCodePath 15822 if (oldCodePath != null) { 15823 String subStr = oldCodePath; 15824 // Drop the suffix right away 15825 if (suffix != null && subStr.endsWith(suffix)) { 15826 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15827 } 15828 // If oldCodePath already contains prefix find out the 15829 // ending index to either increment or decrement. 15830 int sidx = subStr.lastIndexOf(prefix); 15831 if (sidx != -1) { 15832 subStr = subStr.substring(sidx + prefix.length()); 15833 if (subStr != null) { 15834 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15835 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15836 } 15837 try { 15838 idx = Integer.parseInt(subStr); 15839 if (idx <= 1) { 15840 idx++; 15841 } else { 15842 idx--; 15843 } 15844 } catch(NumberFormatException e) { 15845 } 15846 } 15847 } 15848 } 15849 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15850 return prefix + idxStr; 15851 } 15852 15853 private File getNextCodePath(File targetDir, String packageName) { 15854 File result; 15855 SecureRandom random = new SecureRandom(); 15856 byte[] bytes = new byte[16]; 15857 do { 15858 random.nextBytes(bytes); 15859 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15860 result = new File(targetDir, packageName + "-" + suffix); 15861 } while (result.exists()); 15862 return result; 15863 } 15864 15865 // Utility method that returns the relative package path with respect 15866 // to the installation directory. Like say for /data/data/com.test-1.apk 15867 // string com.test-1 is returned. 15868 static String deriveCodePathName(String codePath) { 15869 if (codePath == null) { 15870 return null; 15871 } 15872 final File codeFile = new File(codePath); 15873 final String name = codeFile.getName(); 15874 if (codeFile.isDirectory()) { 15875 return name; 15876 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15877 final int lastDot = name.lastIndexOf('.'); 15878 return name.substring(0, lastDot); 15879 } else { 15880 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15881 return null; 15882 } 15883 } 15884 15885 static class PackageInstalledInfo { 15886 String name; 15887 int uid; 15888 // The set of users that originally had this package installed. 15889 int[] origUsers; 15890 // The set of users that now have this package installed. 15891 int[] newUsers; 15892 PackageParser.Package pkg; 15893 int returnCode; 15894 String returnMsg; 15895 String installerPackageName; 15896 PackageRemovedInfo removedInfo; 15897 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15898 15899 public void setError(int code, String msg) { 15900 setReturnCode(code); 15901 setReturnMessage(msg); 15902 Slog.w(TAG, msg); 15903 } 15904 15905 public void setError(String msg, PackageParserException e) { 15906 setReturnCode(e.error); 15907 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15908 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15909 for (int i = 0; i < childCount; i++) { 15910 addedChildPackages.valueAt(i).setError(msg, e); 15911 } 15912 Slog.w(TAG, msg, e); 15913 } 15914 15915 public void setError(String msg, PackageManagerException e) { 15916 returnCode = e.error; 15917 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15918 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15919 for (int i = 0; i < childCount; i++) { 15920 addedChildPackages.valueAt(i).setError(msg, e); 15921 } 15922 Slog.w(TAG, msg, e); 15923 } 15924 15925 public void setReturnCode(int returnCode) { 15926 this.returnCode = returnCode; 15927 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15928 for (int i = 0; i < childCount; i++) { 15929 addedChildPackages.valueAt(i).returnCode = returnCode; 15930 } 15931 } 15932 15933 private void setReturnMessage(String returnMsg) { 15934 this.returnMsg = returnMsg; 15935 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15936 for (int i = 0; i < childCount; i++) { 15937 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15938 } 15939 } 15940 15941 // In some error cases we want to convey more info back to the observer 15942 String origPackage; 15943 String origPermission; 15944 } 15945 15946 /* 15947 * Install a non-existing package. 15948 */ 15949 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15950 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15951 String volumeUuid, PackageInstalledInfo res, int installReason) { 15952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15953 15954 // Remember this for later, in case we need to rollback this install 15955 String pkgName = pkg.packageName; 15956 15957 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15958 15959 synchronized(mPackages) { 15960 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15961 if (renamedPackage != null) { 15962 // A package with the same name is already installed, though 15963 // it has been renamed to an older name. The package we 15964 // are trying to install should be installed as an update to 15965 // the existing one, but that has not been requested, so bail. 15966 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15967 + " without first uninstalling package running as " 15968 + renamedPackage); 15969 return; 15970 } 15971 if (mPackages.containsKey(pkgName)) { 15972 // Don't allow installation over an existing package with the same name. 15973 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15974 + " without first uninstalling."); 15975 return; 15976 } 15977 } 15978 15979 try { 15980 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15981 System.currentTimeMillis(), user); 15982 15983 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15984 15985 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15986 prepareAppDataAfterInstallLIF(newPackage); 15987 15988 } else { 15989 // Remove package from internal structures, but keep around any 15990 // data that might have already existed 15991 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15992 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15993 } 15994 } catch (PackageManagerException e) { 15995 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15996 } 15997 15998 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15999 } 16000 16001 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16002 try (DigestInputStream digestStream = 16003 new DigestInputStream(new FileInputStream(file), digest)) { 16004 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16005 } 16006 } 16007 16008 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16009 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16010 PackageInstalledInfo res, int installReason) { 16011 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16012 16013 final PackageParser.Package oldPackage; 16014 final PackageSetting ps; 16015 final String pkgName = pkg.packageName; 16016 final int[] allUsers; 16017 final int[] installedUsers; 16018 16019 synchronized(mPackages) { 16020 oldPackage = mPackages.get(pkgName); 16021 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16022 16023 // don't allow upgrade to target a release SDK from a pre-release SDK 16024 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16025 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16026 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16027 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16028 if (oldTargetsPreRelease 16029 && !newTargetsPreRelease 16030 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16031 Slog.w(TAG, "Can't install package targeting released sdk"); 16032 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16033 return; 16034 } 16035 16036 ps = mSettings.mPackages.get(pkgName); 16037 16038 // verify signatures are valid 16039 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16040 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16041 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16042 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16043 "New package not signed by keys specified by upgrade-keysets: " 16044 + pkgName); 16045 return; 16046 } 16047 } else { 16048 // default to original signature matching 16049 if (compareSignatures(oldPackage.mSigningDetails.signatures, 16050 pkg.mSigningDetails.signatures) 16051 != PackageManager.SIGNATURE_MATCH) { 16052 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16053 "New package has a different signature: " + pkgName); 16054 return; 16055 } 16056 } 16057 16058 // don't allow a system upgrade unless the upgrade hash matches 16059 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16060 byte[] digestBytes = null; 16061 try { 16062 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16063 updateDigest(digest, new File(pkg.baseCodePath)); 16064 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16065 for (String path : pkg.splitCodePaths) { 16066 updateDigest(digest, new File(path)); 16067 } 16068 } 16069 digestBytes = digest.digest(); 16070 } catch (NoSuchAlgorithmException | IOException e) { 16071 res.setError(INSTALL_FAILED_INVALID_APK, 16072 "Could not compute hash: " + pkgName); 16073 return; 16074 } 16075 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16076 res.setError(INSTALL_FAILED_INVALID_APK, 16077 "New package fails restrict-update check: " + pkgName); 16078 return; 16079 } 16080 // retain upgrade restriction 16081 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16082 } 16083 16084 // Check for shared user id changes 16085 String invalidPackageName = 16086 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16087 if (invalidPackageName != null) { 16088 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16089 "Package " + invalidPackageName + " tried to change user " 16090 + oldPackage.mSharedUserId); 16091 return; 16092 } 16093 16094 // check if the new package supports all of the abis which the old package supports 16095 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16096 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16097 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16098 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16099 "Update to package " + pkgName + " doesn't support multi arch"); 16100 return; 16101 } 16102 16103 // In case of rollback, remember per-user/profile install state 16104 allUsers = sUserManager.getUserIds(); 16105 installedUsers = ps.queryInstalledUsers(allUsers, true); 16106 16107 // don't allow an upgrade from full to ephemeral 16108 if (isInstantApp) { 16109 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16110 for (int currentUser : allUsers) { 16111 if (!ps.getInstantApp(currentUser)) { 16112 // can't downgrade from full to instant 16113 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16114 + " for user: " + currentUser); 16115 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16116 return; 16117 } 16118 } 16119 } else if (!ps.getInstantApp(user.getIdentifier())) { 16120 // can't downgrade from full to instant 16121 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16122 + " for user: " + user.getIdentifier()); 16123 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16124 return; 16125 } 16126 } 16127 } 16128 16129 // Update what is removed 16130 res.removedInfo = new PackageRemovedInfo(this); 16131 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16132 res.removedInfo.removedPackage = oldPackage.packageName; 16133 res.removedInfo.installerPackageName = ps.installerPackageName; 16134 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16135 res.removedInfo.isUpdate = true; 16136 res.removedInfo.origUsers = installedUsers; 16137 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16138 for (int i = 0; i < installedUsers.length; i++) { 16139 final int userId = installedUsers[i]; 16140 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16141 } 16142 16143 final int childCount = (oldPackage.childPackages != null) 16144 ? oldPackage.childPackages.size() : 0; 16145 for (int i = 0; i < childCount; i++) { 16146 boolean childPackageUpdated = false; 16147 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16148 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16149 if (res.addedChildPackages != null) { 16150 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16151 if (childRes != null) { 16152 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16153 childRes.removedInfo.removedPackage = childPkg.packageName; 16154 if (childPs != null) { 16155 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16156 } 16157 childRes.removedInfo.isUpdate = true; 16158 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16159 childPackageUpdated = true; 16160 } 16161 } 16162 if (!childPackageUpdated) { 16163 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16164 childRemovedRes.removedPackage = childPkg.packageName; 16165 if (childPs != null) { 16166 childRemovedRes.installerPackageName = childPs.installerPackageName; 16167 } 16168 childRemovedRes.isUpdate = false; 16169 childRemovedRes.dataRemoved = true; 16170 synchronized (mPackages) { 16171 if (childPs != null) { 16172 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16173 } 16174 } 16175 if (res.removedInfo.removedChildPackages == null) { 16176 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16177 } 16178 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16179 } 16180 } 16181 16182 boolean sysPkg = (isSystemApp(oldPackage)); 16183 if (sysPkg) { 16184 // Set the system/privileged/oem/vendor/product flags as needed 16185 final boolean privileged = 16186 (oldPackage.applicationInfo.privateFlags 16187 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16188 final boolean oem = 16189 (oldPackage.applicationInfo.privateFlags 16190 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16191 final boolean vendor = 16192 (oldPackage.applicationInfo.privateFlags 16193 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16194 final boolean product = 16195 (oldPackage.applicationInfo.privateFlags 16196 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16197 final @ParseFlags int systemParseFlags = parseFlags; 16198 final @ScanFlags int systemScanFlags = scanFlags 16199 | SCAN_AS_SYSTEM 16200 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16201 | (oem ? SCAN_AS_OEM : 0) 16202 | (vendor ? SCAN_AS_VENDOR : 0) 16203 | (product ? SCAN_AS_PRODUCT : 0); 16204 16205 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16206 user, allUsers, installerPackageName, res, installReason); 16207 } else { 16208 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16209 user, allUsers, installerPackageName, res, installReason); 16210 } 16211 } 16212 16213 @Override 16214 public List<String> getPreviousCodePaths(String packageName) { 16215 final int callingUid = Binder.getCallingUid(); 16216 final List<String> result = new ArrayList<>(); 16217 if (getInstantAppPackageName(callingUid) != null) { 16218 return result; 16219 } 16220 final PackageSetting ps = mSettings.mPackages.get(packageName); 16221 if (ps != null 16222 && ps.oldCodePaths != null 16223 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16224 result.addAll(ps.oldCodePaths); 16225 } 16226 return result; 16227 } 16228 16229 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16230 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16231 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16232 String installerPackageName, PackageInstalledInfo res, int installReason) { 16233 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16234 + deletedPackage); 16235 16236 String pkgName = deletedPackage.packageName; 16237 boolean deletedPkg = true; 16238 boolean addedPkg = false; 16239 boolean updatedSettings = false; 16240 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16241 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16242 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16243 16244 final long origUpdateTime = (pkg.mExtras != null) 16245 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16246 16247 // First delete the existing package while retaining the data directory 16248 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16249 res.removedInfo, true, pkg)) { 16250 // If the existing package wasn't successfully deleted 16251 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16252 deletedPkg = false; 16253 } else { 16254 // Successfully deleted the old package; proceed with replace. 16255 16256 // If deleted package lived in a container, give users a chance to 16257 // relinquish resources before killing. 16258 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16259 if (DEBUG_INSTALL) { 16260 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16261 } 16262 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16263 final ArrayList<String> pkgList = new ArrayList<String>(1); 16264 pkgList.add(deletedPackage.applicationInfo.packageName); 16265 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16266 } 16267 16268 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16269 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16270 16271 try { 16272 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16273 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16274 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16275 installReason); 16276 16277 // Update the in-memory copy of the previous code paths. 16278 PackageSetting ps = mSettings.mPackages.get(pkgName); 16279 if (!killApp) { 16280 if (ps.oldCodePaths == null) { 16281 ps.oldCodePaths = new ArraySet<>(); 16282 } 16283 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16284 if (deletedPackage.splitCodePaths != null) { 16285 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16286 } 16287 } else { 16288 ps.oldCodePaths = null; 16289 } 16290 if (ps.childPackageNames != null) { 16291 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16292 final String childPkgName = ps.childPackageNames.get(i); 16293 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16294 childPs.oldCodePaths = ps.oldCodePaths; 16295 } 16296 } 16297 // set instant app status, but, only if it's explicitly specified 16298 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16299 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16300 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16301 prepareAppDataAfterInstallLIF(newPackage); 16302 addedPkg = true; 16303 mDexManager.notifyPackageUpdated(newPackage.packageName, 16304 newPackage.baseCodePath, newPackage.splitCodePaths); 16305 } catch (PackageManagerException e) { 16306 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16307 } 16308 } 16309 16310 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16311 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16312 16313 // Revert all internal state mutations and added folders for the failed install 16314 if (addedPkg) { 16315 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16316 res.removedInfo, true, null); 16317 } 16318 16319 // Restore the old package 16320 if (deletedPkg) { 16321 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16322 File restoreFile = new File(deletedPackage.codePath); 16323 // Parse old package 16324 boolean oldExternal = isExternal(deletedPackage); 16325 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16326 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16327 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16328 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16329 try { 16330 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16331 null); 16332 } catch (PackageManagerException e) { 16333 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16334 + e.getMessage()); 16335 return; 16336 } 16337 16338 synchronized (mPackages) { 16339 // Ensure the installer package name up to date 16340 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16341 16342 // Update permissions for restored package 16343 mPermissionManager.updatePermissions( 16344 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16345 mPermissionCallback); 16346 16347 mSettings.writeLPr(); 16348 } 16349 16350 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16351 } 16352 } else { 16353 synchronized (mPackages) { 16354 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16355 if (ps != null) { 16356 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16357 if (res.removedInfo.removedChildPackages != null) { 16358 final int childCount = res.removedInfo.removedChildPackages.size(); 16359 // Iterate in reverse as we may modify the collection 16360 for (int i = childCount - 1; i >= 0; i--) { 16361 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16362 if (res.addedChildPackages.containsKey(childPackageName)) { 16363 res.removedInfo.removedChildPackages.removeAt(i); 16364 } else { 16365 PackageRemovedInfo childInfo = res.removedInfo 16366 .removedChildPackages.valueAt(i); 16367 childInfo.removedForAllUsers = mPackages.get( 16368 childInfo.removedPackage) == null; 16369 } 16370 } 16371 } 16372 } 16373 } 16374 } 16375 } 16376 16377 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16378 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16379 final @ScanFlags int scanFlags, UserHandle user, 16380 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16381 int installReason) { 16382 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16383 + ", old=" + deletedPackage); 16384 16385 final boolean disabledSystem; 16386 16387 // Remove existing system package 16388 removePackageLI(deletedPackage, true); 16389 16390 synchronized (mPackages) { 16391 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16392 } 16393 if (!disabledSystem) { 16394 // We didn't need to disable the .apk as a current system package, 16395 // which means we are replacing another update that is already 16396 // installed. We need to make sure to delete the older one's .apk. 16397 res.removedInfo.args = createInstallArgsForExisting(0, 16398 deletedPackage.applicationInfo.getCodePath(), 16399 deletedPackage.applicationInfo.getResourcePath(), 16400 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16401 } else { 16402 res.removedInfo.args = null; 16403 } 16404 16405 // Successfully disabled the old package. Now proceed with re-installation 16406 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16407 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16408 16409 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16410 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16411 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16412 16413 PackageParser.Package newPackage = null; 16414 try { 16415 // Add the package to the internal data structures 16416 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16417 16418 // Set the update and install times 16419 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16420 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16421 System.currentTimeMillis()); 16422 16423 // Update the package dynamic state if succeeded 16424 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16425 // Now that the install succeeded make sure we remove data 16426 // directories for any child package the update removed. 16427 final int deletedChildCount = (deletedPackage.childPackages != null) 16428 ? deletedPackage.childPackages.size() : 0; 16429 final int newChildCount = (newPackage.childPackages != null) 16430 ? newPackage.childPackages.size() : 0; 16431 for (int i = 0; i < deletedChildCount; i++) { 16432 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16433 boolean childPackageDeleted = true; 16434 for (int j = 0; j < newChildCount; j++) { 16435 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16436 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16437 childPackageDeleted = false; 16438 break; 16439 } 16440 } 16441 if (childPackageDeleted) { 16442 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16443 deletedChildPkg.packageName); 16444 if (ps != null && res.removedInfo.removedChildPackages != null) { 16445 PackageRemovedInfo removedChildRes = res.removedInfo 16446 .removedChildPackages.get(deletedChildPkg.packageName); 16447 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16448 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16449 } 16450 } 16451 } 16452 16453 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16454 installReason); 16455 prepareAppDataAfterInstallLIF(newPackage); 16456 16457 mDexManager.notifyPackageUpdated(newPackage.packageName, 16458 newPackage.baseCodePath, newPackage.splitCodePaths); 16459 } 16460 } catch (PackageManagerException e) { 16461 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16462 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16463 } 16464 16465 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16466 // Re installation failed. Restore old information 16467 // Remove new pkg information 16468 if (newPackage != null) { 16469 removeInstalledPackageLI(newPackage, true); 16470 } 16471 // Add back the old system package 16472 try { 16473 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16474 } catch (PackageManagerException e) { 16475 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16476 } 16477 16478 synchronized (mPackages) { 16479 if (disabledSystem) { 16480 enableSystemPackageLPw(deletedPackage); 16481 } 16482 16483 // Ensure the installer package name up to date 16484 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16485 16486 // Update permissions for restored package 16487 mPermissionManager.updatePermissions( 16488 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16489 mPermissionCallback); 16490 16491 mSettings.writeLPr(); 16492 } 16493 16494 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16495 + " after failed upgrade"); 16496 } 16497 } 16498 16499 /** 16500 * Checks whether the parent or any of the child packages have a change shared 16501 * user. For a package to be a valid update the shred users of the parent and 16502 * the children should match. We may later support changing child shared users. 16503 * @param oldPkg The updated package. 16504 * @param newPkg The update package. 16505 * @return The shared user that change between the versions. 16506 */ 16507 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16508 PackageParser.Package newPkg) { 16509 // Check parent shared user 16510 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16511 return newPkg.packageName; 16512 } 16513 // Check child shared users 16514 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16515 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16516 for (int i = 0; i < newChildCount; i++) { 16517 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16518 // If this child was present, did it have the same shared user? 16519 for (int j = 0; j < oldChildCount; j++) { 16520 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16521 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16522 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16523 return newChildPkg.packageName; 16524 } 16525 } 16526 } 16527 return null; 16528 } 16529 16530 private void removeNativeBinariesLI(PackageSetting ps) { 16531 // Remove the lib path for the parent package 16532 if (ps != null) { 16533 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16534 // Remove the lib path for the child packages 16535 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16536 for (int i = 0; i < childCount; i++) { 16537 PackageSetting childPs = null; 16538 synchronized (mPackages) { 16539 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16540 } 16541 if (childPs != null) { 16542 NativeLibraryHelper.removeNativeBinariesLI(childPs 16543 .legacyNativeLibraryPathString); 16544 } 16545 } 16546 } 16547 } 16548 16549 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16550 // Enable the parent package 16551 mSettings.enableSystemPackageLPw(pkg.packageName); 16552 // Enable the child packages 16553 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16554 for (int i = 0; i < childCount; i++) { 16555 PackageParser.Package childPkg = pkg.childPackages.get(i); 16556 mSettings.enableSystemPackageLPw(childPkg.packageName); 16557 } 16558 } 16559 16560 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16561 PackageParser.Package newPkg) { 16562 // Disable the parent package (parent always replaced) 16563 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16564 // Disable the child packages 16565 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16566 for (int i = 0; i < childCount; i++) { 16567 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16568 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16569 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16570 } 16571 return disabled; 16572 } 16573 16574 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16575 String installerPackageName) { 16576 // Enable the parent package 16577 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16578 // Enable the child packages 16579 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16580 for (int i = 0; i < childCount; i++) { 16581 PackageParser.Package childPkg = pkg.childPackages.get(i); 16582 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16583 } 16584 } 16585 16586 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16587 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16588 // Update the parent package setting 16589 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16590 res, user, installReason); 16591 // Update the child packages setting 16592 final int childCount = (newPackage.childPackages != null) 16593 ? newPackage.childPackages.size() : 0; 16594 for (int i = 0; i < childCount; i++) { 16595 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16596 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16597 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16598 childRes.origUsers, childRes, user, installReason); 16599 } 16600 } 16601 16602 private void updateSettingsInternalLI(PackageParser.Package pkg, 16603 String installerPackageName, int[] allUsers, int[] installedForUsers, 16604 PackageInstalledInfo res, UserHandle user, int installReason) { 16605 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16606 16607 String pkgName = pkg.packageName; 16608 synchronized (mPackages) { 16609 //write settings. the installStatus will be incomplete at this stage. 16610 //note that the new package setting would have already been 16611 //added to mPackages. It hasn't been persisted yet. 16612 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16613 // TODO: Remove this write? It's also written at the end of this method 16614 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16615 mSettings.writeLPr(); 16616 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16617 } 16618 16619 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16620 synchronized (mPackages) { 16621// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16622 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16623 mPermissionCallback); 16624 // For system-bundled packages, we assume that installing an upgraded version 16625 // of the package implies that the user actually wants to run that new code, 16626 // so we enable the package. 16627 PackageSetting ps = mSettings.mPackages.get(pkgName); 16628 final int userId = user.getIdentifier(); 16629 if (ps != null) { 16630 if (isSystemApp(pkg)) { 16631 if (DEBUG_INSTALL) { 16632 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16633 } 16634 // Enable system package for requested users 16635 if (res.origUsers != null) { 16636 for (int origUserId : res.origUsers) { 16637 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16638 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16639 origUserId, installerPackageName); 16640 } 16641 } 16642 } 16643 // Also convey the prior install/uninstall state 16644 if (allUsers != null && installedForUsers != null) { 16645 for (int currentUserId : allUsers) { 16646 final boolean installed = ArrayUtils.contains( 16647 installedForUsers, currentUserId); 16648 if (DEBUG_INSTALL) { 16649 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16650 } 16651 ps.setInstalled(installed, currentUserId); 16652 } 16653 // these install state changes will be persisted in the 16654 // upcoming call to mSettings.writeLPr(). 16655 } 16656 } 16657 // It's implied that when a user requests installation, they want the app to be 16658 // installed and enabled. 16659 if (userId != UserHandle.USER_ALL) { 16660 ps.setInstalled(true, userId); 16661 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16662 } 16663 16664 // When replacing an existing package, preserve the original install reason for all 16665 // users that had the package installed before. 16666 final Set<Integer> previousUserIds = new ArraySet<>(); 16667 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16668 final int installReasonCount = res.removedInfo.installReasons.size(); 16669 for (int i = 0; i < installReasonCount; i++) { 16670 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16671 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16672 ps.setInstallReason(previousInstallReason, previousUserId); 16673 previousUserIds.add(previousUserId); 16674 } 16675 } 16676 16677 // Set install reason for users that are having the package newly installed. 16678 if (userId == UserHandle.USER_ALL) { 16679 for (int currentUserId : sUserManager.getUserIds()) { 16680 if (!previousUserIds.contains(currentUserId)) { 16681 ps.setInstallReason(installReason, currentUserId); 16682 } 16683 } 16684 } else if (!previousUserIds.contains(userId)) { 16685 ps.setInstallReason(installReason, userId); 16686 } 16687 mSettings.writeKernelMappingLPr(ps); 16688 } 16689 res.name = pkgName; 16690 res.uid = pkg.applicationInfo.uid; 16691 res.pkg = pkg; 16692 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16693 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16694 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16695 //to update install status 16696 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16697 mSettings.writeLPr(); 16698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16699 } 16700 16701 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16702 } 16703 16704 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16705 try { 16706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16707 installPackageLI(args, res); 16708 } finally { 16709 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16710 } 16711 } 16712 16713 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16714 final int installFlags = args.installFlags; 16715 final String installerPackageName = args.installerPackageName; 16716 final String volumeUuid = args.volumeUuid; 16717 final File tmpPackageFile = new File(args.getCodePath()); 16718 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16719 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16720 || (args.volumeUuid != null)); 16721 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16722 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16723 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16724 final boolean virtualPreload = 16725 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16726 boolean replace = false; 16727 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16728 if (args.move != null) { 16729 // moving a complete application; perform an initial scan on the new install location 16730 scanFlags |= SCAN_INITIAL; 16731 } 16732 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16733 scanFlags |= SCAN_DONT_KILL_APP; 16734 } 16735 if (instantApp) { 16736 scanFlags |= SCAN_AS_INSTANT_APP; 16737 } 16738 if (fullApp) { 16739 scanFlags |= SCAN_AS_FULL_APP; 16740 } 16741 if (virtualPreload) { 16742 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16743 } 16744 16745 // Result object to be returned 16746 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16747 res.installerPackageName = installerPackageName; 16748 16749 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16750 16751 // Sanity check 16752 if (instantApp && (forwardLocked || onExternal)) { 16753 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16754 + " external=" + onExternal); 16755 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16756 return; 16757 } 16758 16759 // Retrieve PackageSettings and parse package 16760 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16761 | PackageParser.PARSE_ENFORCE_CODE 16762 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16763 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16764 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16765 PackageParser pp = new PackageParser(); 16766 pp.setSeparateProcesses(mSeparateProcesses); 16767 pp.setDisplayMetrics(mMetrics); 16768 pp.setCallback(mPackageParserCallback); 16769 16770 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16771 final PackageParser.Package pkg; 16772 try { 16773 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16774 DexMetadataHelper.validatePackageDexMetadata(pkg); 16775 } catch (PackageParserException e) { 16776 res.setError("Failed parse during installPackageLI", e); 16777 return; 16778 } finally { 16779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16780 } 16781 16782 // Instant apps have several additional install-time checks. 16783 if (instantApp) { 16784 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16785 Slog.w(TAG, 16786 "Instant app package " + pkg.packageName + " does not target at least O"); 16787 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16788 "Instant app package must target at least O"); 16789 return; 16790 } 16791 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16792 Slog.w(TAG, "Instant app package " + pkg.packageName 16793 + " does not target targetSandboxVersion 2"); 16794 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16795 "Instant app package must use targetSandboxVersion 2"); 16796 return; 16797 } 16798 if (pkg.mSharedUserId != null) { 16799 Slog.w(TAG, "Instant app package " + pkg.packageName 16800 + " may not declare sharedUserId."); 16801 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16802 "Instant app package may not declare a sharedUserId"); 16803 return; 16804 } 16805 } 16806 16807 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16808 // Static shared libraries have synthetic package names 16809 renameStaticSharedLibraryPackage(pkg); 16810 16811 // No static shared libs on external storage 16812 if (onExternal) { 16813 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16814 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16815 "Packages declaring static-shared libs cannot be updated"); 16816 return; 16817 } 16818 } 16819 16820 // If we are installing a clustered package add results for the children 16821 if (pkg.childPackages != null) { 16822 synchronized (mPackages) { 16823 final int childCount = pkg.childPackages.size(); 16824 for (int i = 0; i < childCount; i++) { 16825 PackageParser.Package childPkg = pkg.childPackages.get(i); 16826 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16827 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16828 childRes.pkg = childPkg; 16829 childRes.name = childPkg.packageName; 16830 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16831 if (childPs != null) { 16832 childRes.origUsers = childPs.queryInstalledUsers( 16833 sUserManager.getUserIds(), true); 16834 } 16835 if ((mPackages.containsKey(childPkg.packageName))) { 16836 childRes.removedInfo = new PackageRemovedInfo(this); 16837 childRes.removedInfo.removedPackage = childPkg.packageName; 16838 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16839 } 16840 if (res.addedChildPackages == null) { 16841 res.addedChildPackages = new ArrayMap<>(); 16842 } 16843 res.addedChildPackages.put(childPkg.packageName, childRes); 16844 } 16845 } 16846 } 16847 16848 // If package doesn't declare API override, mark that we have an install 16849 // time CPU ABI override. 16850 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16851 pkg.cpuAbiOverride = args.abiOverride; 16852 } 16853 16854 String pkgName = res.name = pkg.packageName; 16855 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16856 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16857 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16858 return; 16859 } 16860 } 16861 16862 try { 16863 // either use what we've been given or parse directly from the APK 16864 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16865 pkg.setSigningDetails(args.signingDetails); 16866 } else { 16867 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16868 } 16869 } catch (PackageParserException e) { 16870 res.setError("Failed collect during installPackageLI", e); 16871 return; 16872 } 16873 16874 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16875 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16876 Slog.w(TAG, "Instant app package " + pkg.packageName 16877 + " is not signed with at least APK Signature Scheme v2"); 16878 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16879 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16880 return; 16881 } 16882 16883 // Get rid of all references to package scan path via parser. 16884 pp = null; 16885 String oldCodePath = null; 16886 boolean systemApp = false; 16887 synchronized (mPackages) { 16888 // Check if installing already existing package 16889 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16890 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16891 if (pkg.mOriginalPackages != null 16892 && pkg.mOriginalPackages.contains(oldName) 16893 && mPackages.containsKey(oldName)) { 16894 // This package is derived from an original package, 16895 // and this device has been updating from that original 16896 // name. We must continue using the original name, so 16897 // rename the new package here. 16898 pkg.setPackageName(oldName); 16899 pkgName = pkg.packageName; 16900 replace = true; 16901 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16902 + oldName + " pkgName=" + pkgName); 16903 } else if (mPackages.containsKey(pkgName)) { 16904 // This package, under its official name, already exists 16905 // on the device; we should replace it. 16906 replace = true; 16907 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16908 } 16909 16910 // Child packages are installed through the parent package 16911 if (pkg.parentPackage != null) { 16912 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16913 "Package " + pkg.packageName + " is child of package " 16914 + pkg.parentPackage.parentPackage + ". Child packages " 16915 + "can be updated only through the parent package."); 16916 return; 16917 } 16918 16919 if (replace) { 16920 // Prevent apps opting out from runtime permissions 16921 PackageParser.Package oldPackage = mPackages.get(pkgName); 16922 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16923 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16924 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16925 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16926 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16927 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16928 + " doesn't support runtime permissions but the old" 16929 + " target SDK " + oldTargetSdk + " does."); 16930 return; 16931 } 16932 // Prevent persistent apps from being updated 16933 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16934 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16935 "Package " + oldPackage.packageName + " is a persistent app. " 16936 + "Persistent apps are not updateable."); 16937 return; 16938 } 16939 // Prevent apps from downgrading their targetSandbox. 16940 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16941 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16942 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16943 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16944 "Package " + pkg.packageName + " new target sandbox " 16945 + newTargetSandbox + " is incompatible with the previous value of" 16946 + oldTargetSandbox + "."); 16947 return; 16948 } 16949 16950 // Prevent installing of child packages 16951 if (oldPackage.parentPackage != null) { 16952 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16953 "Package " + pkg.packageName + " is child of package " 16954 + oldPackage.parentPackage + ". Child packages " 16955 + "can be updated only through the parent package."); 16956 return; 16957 } 16958 } 16959 } 16960 16961 PackageSetting ps = mSettings.mPackages.get(pkgName); 16962 if (ps != null) { 16963 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16964 16965 // Static shared libs have same package with different versions where 16966 // we internally use a synthetic package name to allow multiple versions 16967 // of the same package, therefore we need to compare signatures against 16968 // the package setting for the latest library version. 16969 PackageSetting signatureCheckPs = ps; 16970 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16971 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16972 if (libraryEntry != null) { 16973 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16974 } 16975 } 16976 16977 // Quick sanity check that we're signed correctly if updating; 16978 // we'll check this again later when scanning, but we want to 16979 // bail early here before tripping over redefined permissions. 16980 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16981 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16982 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16983 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16984 + pkg.packageName + " upgrade keys do not match the " 16985 + "previously installed version"); 16986 return; 16987 } 16988 } else { 16989 try { 16990 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16991 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16992 // We don't care about disabledPkgSetting on install for now. 16993 final boolean compatMatch = verifySignatures( 16994 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16995 compareRecover); 16996 // The new KeySets will be re-added later in the scanning process. 16997 if (compatMatch) { 16998 synchronized (mPackages) { 16999 ksms.removeAppKeySetDataLPw(pkg.packageName); 17000 } 17001 } 17002 } catch (PackageManagerException e) { 17003 res.setError(e.error, e.getMessage()); 17004 return; 17005 } 17006 } 17007 17008 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17009 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17010 systemApp = (ps.pkg.applicationInfo.flags & 17011 ApplicationInfo.FLAG_SYSTEM) != 0; 17012 } 17013 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17014 } 17015 17016 int N = pkg.permissions.size(); 17017 for (int i = N-1; i >= 0; i--) { 17018 final PackageParser.Permission perm = pkg.permissions.get(i); 17019 final BasePermission bp = 17020 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17021 17022 // Don't allow anyone but the system to define ephemeral permissions. 17023 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17024 && !systemApp) { 17025 Slog.w(TAG, "Non-System package " + pkg.packageName 17026 + " attempting to delcare ephemeral permission " 17027 + perm.info.name + "; Removing ephemeral."); 17028 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17029 } 17030 17031 // Check whether the newly-scanned package wants to define an already-defined perm 17032 if (bp != null) { 17033 // If the defining package is signed with our cert, it's okay. This 17034 // also includes the "updating the same package" case, of course. 17035 // "updating same package" could also involve key-rotation. 17036 final boolean sigsOk; 17037 final String sourcePackageName = bp.getSourcePackageName(); 17038 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17039 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17040 if (sourcePackageName.equals(pkg.packageName) 17041 && (ksms.shouldCheckUpgradeKeySetLocked( 17042 sourcePackageSetting, scanFlags))) { 17043 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17044 } else { 17045 sigsOk = compareSignatures( 17046 sourcePackageSetting.signatures.mSigningDetails.signatures, 17047 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 17048 } 17049 if (!sigsOk) { 17050 // If the owning package is the system itself, we log but allow 17051 // install to proceed; we fail the install on all other permission 17052 // redefinitions. 17053 if (!sourcePackageName.equals("android")) { 17054 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17055 + pkg.packageName + " attempting to redeclare permission " 17056 + perm.info.name + " already owned by " + sourcePackageName); 17057 res.origPermission = perm.info.name; 17058 res.origPackage = sourcePackageName; 17059 return; 17060 } else { 17061 Slog.w(TAG, "Package " + pkg.packageName 17062 + " attempting to redeclare system permission " 17063 + perm.info.name + "; ignoring new declaration"); 17064 pkg.permissions.remove(i); 17065 } 17066 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17067 // Prevent apps to change protection level to dangerous from any other 17068 // type as this would allow a privilege escalation where an app adds a 17069 // normal/signature permission in other app's group and later redefines 17070 // it as dangerous leading to the group auto-grant. 17071 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17072 == PermissionInfo.PROTECTION_DANGEROUS) { 17073 if (bp != null && !bp.isRuntime()) { 17074 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17075 + "non-runtime permission " + perm.info.name 17076 + " to runtime; keeping old protection level"); 17077 perm.info.protectionLevel = bp.getProtectionLevel(); 17078 } 17079 } 17080 } 17081 } 17082 } 17083 } 17084 17085 if (systemApp) { 17086 if (onExternal) { 17087 // Abort update; system app can't be replaced with app on sdcard 17088 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17089 "Cannot install updates to system apps on sdcard"); 17090 return; 17091 } else if (instantApp) { 17092 // Abort update; system app can't be replaced with an instant app 17093 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17094 "Cannot update a system app with an instant app"); 17095 return; 17096 } 17097 } 17098 17099 if (args.move != null) { 17100 // We did an in-place move, so dex is ready to roll 17101 scanFlags |= SCAN_NO_DEX; 17102 scanFlags |= SCAN_MOVE; 17103 17104 synchronized (mPackages) { 17105 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17106 if (ps == null) { 17107 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17108 "Missing settings for moved package " + pkgName); 17109 } 17110 17111 // We moved the entire application as-is, so bring over the 17112 // previously derived ABI information. 17113 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17114 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17115 } 17116 17117 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17118 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17119 scanFlags |= SCAN_NO_DEX; 17120 17121 try { 17122 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17123 args.abiOverride : pkg.cpuAbiOverride); 17124 final boolean extractNativeLibs = !pkg.isLibrary(); 17125 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17126 } catch (PackageManagerException pme) { 17127 Slog.e(TAG, "Error deriving application ABI", pme); 17128 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17129 return; 17130 } 17131 17132 // Shared libraries for the package need to be updated. 17133 synchronized (mPackages) { 17134 try { 17135 updateSharedLibrariesLPr(pkg, null); 17136 } catch (PackageManagerException e) { 17137 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17138 } 17139 } 17140 } 17141 17142 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17143 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17144 return; 17145 } 17146 17147 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17148 String apkPath = null; 17149 synchronized (mPackages) { 17150 // Note that if the attacker managed to skip verify setup, for example by tampering 17151 // with the package settings, upon reboot we will do full apk verification when 17152 // verity is not detected. 17153 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17154 if (ps != null && ps.isPrivileged()) { 17155 apkPath = pkg.baseCodePath; 17156 } 17157 } 17158 17159 if (apkPath != null) { 17160 final VerityUtils.SetupResult result = 17161 VerityUtils.generateApkVeritySetupData(apkPath); 17162 if (result.isOk()) { 17163 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17164 FileDescriptor fd = result.getUnownedFileDescriptor(); 17165 try { 17166 mInstaller.installApkVerity(apkPath, fd); 17167 } catch (InstallerException e) { 17168 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17169 "Failed to set up verity: " + e); 17170 return; 17171 } finally { 17172 IoUtils.closeQuietly(fd); 17173 } 17174 } else if (result.isFailed()) { 17175 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17176 return; 17177 } else { 17178 // Do nothing if verity is skipped. Will fall back to full apk verification on 17179 // reboot. 17180 } 17181 } 17182 } 17183 17184 if (!instantApp) { 17185 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17186 } else { 17187 if (DEBUG_DOMAIN_VERIFICATION) { 17188 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17189 } 17190 } 17191 17192 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17193 "installPackageLI")) { 17194 if (replace) { 17195 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17196 // Static libs have a synthetic package name containing the version 17197 // and cannot be updated as an update would get a new package name, 17198 // unless this is the exact same version code which is useful for 17199 // development. 17200 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17201 if (existingPkg != null && 17202 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17203 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17204 + "static-shared libs cannot be updated"); 17205 return; 17206 } 17207 } 17208 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17209 installerPackageName, res, args.installReason); 17210 } else { 17211 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17212 args.user, installerPackageName, volumeUuid, res, args.installReason); 17213 } 17214 } 17215 17216 // Prepare the application profiles for the new code paths. 17217 // This needs to be done before invoking dexopt so that any install-time profile 17218 // can be used for optimizations. 17219 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17220 17221 // Check whether we need to dexopt the app. 17222 // 17223 // NOTE: it is IMPORTANT to call dexopt: 17224 // - after doRename which will sync the package data from PackageParser.Package and its 17225 // corresponding ApplicationInfo. 17226 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17227 // uid of the application (pkg.applicationInfo.uid). 17228 // This update happens in place! 17229 // 17230 // We only need to dexopt if the package meets ALL of the following conditions: 17231 // 1) it is not forward locked. 17232 // 2) it is not on on an external ASEC container. 17233 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17234 // 17235 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17236 // complete, so we skip this step during installation. Instead, we'll take extra time 17237 // the first time the instant app starts. It's preferred to do it this way to provide 17238 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17239 // middle of running an instant app. The default behaviour can be overridden 17240 // via gservices. 17241 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17242 && !forwardLocked 17243 && !pkg.applicationInfo.isExternalAsec() 17244 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17245 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17246 17247 if (performDexopt) { 17248 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17249 // Do not run PackageDexOptimizer through the local performDexOpt 17250 // method because `pkg` may not be in `mPackages` yet. 17251 // 17252 // Also, don't fail application installs if the dexopt step fails. 17253 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17254 REASON_INSTALL, 17255 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17256 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17257 null /* instructionSets */, 17258 getOrCreateCompilerPackageStats(pkg), 17259 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17260 dexoptOptions); 17261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17262 } 17263 17264 // Notify BackgroundDexOptService that the package has been changed. 17265 // If this is an update of a package which used to fail to compile, 17266 // BackgroundDexOptService will remove it from its blacklist. 17267 // TODO: Layering violation 17268 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17269 17270 synchronized (mPackages) { 17271 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17272 if (ps != null) { 17273 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17274 ps.setUpdateAvailable(false /*updateAvailable*/); 17275 } 17276 17277 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17278 for (int i = 0; i < childCount; i++) { 17279 PackageParser.Package childPkg = pkg.childPackages.get(i); 17280 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17281 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17282 if (childPs != null) { 17283 childRes.newUsers = childPs.queryInstalledUsers( 17284 sUserManager.getUserIds(), true); 17285 } 17286 } 17287 17288 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17289 updateSequenceNumberLP(ps, res.newUsers); 17290 updateInstantAppInstallerLocked(pkgName); 17291 } 17292 } 17293 } 17294 17295 private void startIntentFilterVerifications(int userId, boolean replacing, 17296 PackageParser.Package pkg) { 17297 if (mIntentFilterVerifierComponent == null) { 17298 Slog.w(TAG, "No IntentFilter verification will not be done as " 17299 + "there is no IntentFilterVerifier available!"); 17300 return; 17301 } 17302 17303 final int verifierUid = getPackageUid( 17304 mIntentFilterVerifierComponent.getPackageName(), 17305 MATCH_DEBUG_TRIAGED_MISSING, 17306 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17307 17308 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17309 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17310 mHandler.sendMessage(msg); 17311 17312 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17313 for (int i = 0; i < childCount; i++) { 17314 PackageParser.Package childPkg = pkg.childPackages.get(i); 17315 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17316 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17317 mHandler.sendMessage(msg); 17318 } 17319 } 17320 17321 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17322 PackageParser.Package pkg) { 17323 int size = pkg.activities.size(); 17324 if (size == 0) { 17325 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17326 "No activity, so no need to verify any IntentFilter!"); 17327 return; 17328 } 17329 17330 final boolean hasDomainURLs = hasDomainURLs(pkg); 17331 if (!hasDomainURLs) { 17332 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17333 "No domain URLs, so no need to verify any IntentFilter!"); 17334 return; 17335 } 17336 17337 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17338 + " if any IntentFilter from the " + size 17339 + " Activities needs verification ..."); 17340 17341 int count = 0; 17342 final String packageName = pkg.packageName; 17343 17344 synchronized (mPackages) { 17345 // If this is a new install and we see that we've already run verification for this 17346 // package, we have nothing to do: it means the state was restored from backup. 17347 if (!replacing) { 17348 IntentFilterVerificationInfo ivi = 17349 mSettings.getIntentFilterVerificationLPr(packageName); 17350 if (ivi != null) { 17351 if (DEBUG_DOMAIN_VERIFICATION) { 17352 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17353 + ivi.getStatusString()); 17354 } 17355 return; 17356 } 17357 } 17358 17359 // If any filters need to be verified, then all need to be. 17360 boolean needToVerify = false; 17361 for (PackageParser.Activity a : pkg.activities) { 17362 for (ActivityIntentInfo filter : a.intents) { 17363 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17364 if (DEBUG_DOMAIN_VERIFICATION) { 17365 Slog.d(TAG, 17366 "Intent filter needs verification, so processing all filters"); 17367 } 17368 needToVerify = true; 17369 break; 17370 } 17371 } 17372 } 17373 17374 if (needToVerify) { 17375 final int verificationId = mIntentFilterVerificationToken++; 17376 for (PackageParser.Activity a : pkg.activities) { 17377 for (ActivityIntentInfo filter : a.intents) { 17378 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17379 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17380 "Verification needed for IntentFilter:" + filter.toString()); 17381 mIntentFilterVerifier.addOneIntentFilterVerification( 17382 verifierUid, userId, verificationId, filter, packageName); 17383 count++; 17384 } 17385 } 17386 } 17387 } 17388 } 17389 17390 if (count > 0) { 17391 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17392 + " IntentFilter verification" + (count > 1 ? "s" : "") 17393 + " for userId:" + userId); 17394 mIntentFilterVerifier.startVerifications(userId); 17395 } else { 17396 if (DEBUG_DOMAIN_VERIFICATION) { 17397 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17398 } 17399 } 17400 } 17401 17402 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17403 final ComponentName cn = filter.activity.getComponentName(); 17404 final String packageName = cn.getPackageName(); 17405 17406 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17407 packageName); 17408 if (ivi == null) { 17409 return true; 17410 } 17411 int status = ivi.getStatus(); 17412 switch (status) { 17413 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17414 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17415 return true; 17416 17417 default: 17418 // Nothing to do 17419 return false; 17420 } 17421 } 17422 17423 private static boolean isMultiArch(ApplicationInfo info) { 17424 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17425 } 17426 17427 private static boolean isExternal(PackageParser.Package pkg) { 17428 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17429 } 17430 17431 private static boolean isExternal(PackageSetting ps) { 17432 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17433 } 17434 17435 private static boolean isSystemApp(PackageParser.Package pkg) { 17436 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17437 } 17438 17439 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17440 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17441 } 17442 17443 private static boolean isOemApp(PackageParser.Package pkg) { 17444 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17445 } 17446 17447 private static boolean isVendorApp(PackageParser.Package pkg) { 17448 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17449 } 17450 17451 private static boolean isProductApp(PackageParser.Package pkg) { 17452 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17453 } 17454 17455 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17456 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17457 } 17458 17459 private static boolean isSystemApp(PackageSetting ps) { 17460 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17461 } 17462 17463 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17464 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17465 } 17466 17467 private int packageFlagsToInstallFlags(PackageSetting ps) { 17468 int installFlags = 0; 17469 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17470 // This existing package was an external ASEC install when we have 17471 // the external flag without a UUID 17472 installFlags |= PackageManager.INSTALL_EXTERNAL; 17473 } 17474 if (ps.isForwardLocked()) { 17475 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17476 } 17477 return installFlags; 17478 } 17479 17480 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17481 if (isExternal(pkg)) { 17482 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17483 return mSettings.getExternalVersion(); 17484 } else { 17485 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17486 } 17487 } else { 17488 return mSettings.getInternalVersion(); 17489 } 17490 } 17491 17492 private void deleteTempPackageFiles() { 17493 final FilenameFilter filter = new FilenameFilter() { 17494 public boolean accept(File dir, String name) { 17495 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17496 } 17497 }; 17498 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17499 file.delete(); 17500 } 17501 } 17502 17503 @Override 17504 public void deletePackageAsUser(String packageName, int versionCode, 17505 IPackageDeleteObserver observer, int userId, int flags) { 17506 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17507 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17508 } 17509 17510 @Override 17511 public void deletePackageVersioned(VersionedPackage versionedPackage, 17512 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17513 final int callingUid = Binder.getCallingUid(); 17514 mContext.enforceCallingOrSelfPermission( 17515 android.Manifest.permission.DELETE_PACKAGES, null); 17516 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17517 Preconditions.checkNotNull(versionedPackage); 17518 Preconditions.checkNotNull(observer); 17519 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17520 PackageManager.VERSION_CODE_HIGHEST, 17521 Long.MAX_VALUE, "versionCode must be >= -1"); 17522 17523 final String packageName = versionedPackage.getPackageName(); 17524 final long versionCode = versionedPackage.getLongVersionCode(); 17525 final String internalPackageName; 17526 synchronized (mPackages) { 17527 // Normalize package name to handle renamed packages and static libs 17528 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17529 } 17530 17531 final int uid = Binder.getCallingUid(); 17532 if (!isOrphaned(internalPackageName) 17533 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17534 try { 17535 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17536 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17537 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17538 observer.onUserActionRequired(intent); 17539 } catch (RemoteException re) { 17540 } 17541 return; 17542 } 17543 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17544 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17545 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17546 mContext.enforceCallingOrSelfPermission( 17547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17548 "deletePackage for user " + userId); 17549 } 17550 17551 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17552 try { 17553 observer.onPackageDeleted(packageName, 17554 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17555 } catch (RemoteException re) { 17556 } 17557 return; 17558 } 17559 17560 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17561 try { 17562 observer.onPackageDeleted(packageName, 17563 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17564 } catch (RemoteException re) { 17565 } 17566 return; 17567 } 17568 17569 if (DEBUG_REMOVE) { 17570 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17571 + " deleteAllUsers: " + deleteAllUsers + " version=" 17572 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17573 ? "VERSION_CODE_HIGHEST" : versionCode)); 17574 } 17575 // Queue up an async operation since the package deletion may take a little while. 17576 mHandler.post(new Runnable() { 17577 public void run() { 17578 mHandler.removeCallbacks(this); 17579 int returnCode; 17580 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17581 boolean doDeletePackage = true; 17582 if (ps != null) { 17583 final boolean targetIsInstantApp = 17584 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17585 doDeletePackage = !targetIsInstantApp 17586 || canViewInstantApps; 17587 } 17588 if (doDeletePackage) { 17589 if (!deleteAllUsers) { 17590 returnCode = deletePackageX(internalPackageName, versionCode, 17591 userId, deleteFlags); 17592 } else { 17593 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17594 internalPackageName, users); 17595 // If nobody is blocking uninstall, proceed with delete for all users 17596 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17597 returnCode = deletePackageX(internalPackageName, versionCode, 17598 userId, deleteFlags); 17599 } else { 17600 // Otherwise uninstall individually for users with blockUninstalls=false 17601 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17602 for (int userId : users) { 17603 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17604 returnCode = deletePackageX(internalPackageName, versionCode, 17605 userId, userFlags); 17606 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17607 Slog.w(TAG, "Package delete failed for user " + userId 17608 + ", returnCode " + returnCode); 17609 } 17610 } 17611 } 17612 // The app has only been marked uninstalled for certain users. 17613 // We still need to report that delete was blocked 17614 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17615 } 17616 } 17617 } else { 17618 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17619 } 17620 try { 17621 observer.onPackageDeleted(packageName, returnCode, null); 17622 } catch (RemoteException e) { 17623 Log.i(TAG, "Observer no longer exists."); 17624 } //end catch 17625 } //end run 17626 }); 17627 } 17628 17629 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17630 if (pkg.staticSharedLibName != null) { 17631 return pkg.manifestPackageName; 17632 } 17633 return pkg.packageName; 17634 } 17635 17636 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17637 // Handle renamed packages 17638 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17639 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17640 17641 // Is this a static library? 17642 LongSparseArray<SharedLibraryEntry> versionedLib = 17643 mStaticLibsByDeclaringPackage.get(packageName); 17644 if (versionedLib == null || versionedLib.size() <= 0) { 17645 return packageName; 17646 } 17647 17648 // Figure out which lib versions the caller can see 17649 LongSparseLongArray versionsCallerCanSee = null; 17650 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17651 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17652 && callingAppId != Process.ROOT_UID) { 17653 versionsCallerCanSee = new LongSparseLongArray(); 17654 String libName = versionedLib.valueAt(0).info.getName(); 17655 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17656 if (uidPackages != null) { 17657 for (String uidPackage : uidPackages) { 17658 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17659 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17660 if (libIdx >= 0) { 17661 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17662 versionsCallerCanSee.append(libVersion, libVersion); 17663 } 17664 } 17665 } 17666 } 17667 17668 // Caller can see nothing - done 17669 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17670 return packageName; 17671 } 17672 17673 // Find the version the caller can see and the app version code 17674 SharedLibraryEntry highestVersion = null; 17675 final int versionCount = versionedLib.size(); 17676 for (int i = 0; i < versionCount; i++) { 17677 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17678 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17679 libEntry.info.getLongVersion()) < 0) { 17680 continue; 17681 } 17682 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17683 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17684 if (libVersionCode == versionCode) { 17685 return libEntry.apk; 17686 } 17687 } else if (highestVersion == null) { 17688 highestVersion = libEntry; 17689 } else if (libVersionCode > highestVersion.info 17690 .getDeclaringPackage().getLongVersionCode()) { 17691 highestVersion = libEntry; 17692 } 17693 } 17694 17695 if (highestVersion != null) { 17696 return highestVersion.apk; 17697 } 17698 17699 return packageName; 17700 } 17701 17702 boolean isCallerVerifier(int callingUid) { 17703 final int callingUserId = UserHandle.getUserId(callingUid); 17704 return mRequiredVerifierPackage != null && 17705 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17706 } 17707 17708 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17709 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17710 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17711 return true; 17712 } 17713 final int callingUserId = UserHandle.getUserId(callingUid); 17714 // If the caller installed the pkgName, then allow it to silently uninstall. 17715 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17716 return true; 17717 } 17718 17719 // Allow package verifier to silently uninstall. 17720 if (mRequiredVerifierPackage != null && 17721 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17722 return true; 17723 } 17724 17725 // Allow package uninstaller to silently uninstall. 17726 if (mRequiredUninstallerPackage != null && 17727 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17728 return true; 17729 } 17730 17731 // Allow storage manager to silently uninstall. 17732 if (mStorageManagerPackage != null && 17733 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17734 return true; 17735 } 17736 17737 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17738 // uninstall for device owner provisioning. 17739 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17740 == PERMISSION_GRANTED) { 17741 return true; 17742 } 17743 17744 return false; 17745 } 17746 17747 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17748 int[] result = EMPTY_INT_ARRAY; 17749 for (int userId : userIds) { 17750 if (getBlockUninstallForUser(packageName, userId)) { 17751 result = ArrayUtils.appendInt(result, userId); 17752 } 17753 } 17754 return result; 17755 } 17756 17757 @Override 17758 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17759 final int callingUid = Binder.getCallingUid(); 17760 if (getInstantAppPackageName(callingUid) != null 17761 && !isCallerSameApp(packageName, callingUid)) { 17762 return false; 17763 } 17764 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17765 } 17766 17767 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17768 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17769 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17770 try { 17771 if (dpm != null) { 17772 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17773 /* callingUserOnly =*/ false); 17774 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17775 : deviceOwnerComponentName.getPackageName(); 17776 // Does the package contains the device owner? 17777 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17778 // this check is probably not needed, since DO should be registered as a device 17779 // admin on some user too. (Original bug for this: b/17657954) 17780 if (packageName.equals(deviceOwnerPackageName)) { 17781 return true; 17782 } 17783 // Does it contain a device admin for any user? 17784 int[] users; 17785 if (userId == UserHandle.USER_ALL) { 17786 users = sUserManager.getUserIds(); 17787 } else { 17788 users = new int[]{userId}; 17789 } 17790 for (int i = 0; i < users.length; ++i) { 17791 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17792 return true; 17793 } 17794 } 17795 } 17796 } catch (RemoteException e) { 17797 } 17798 return false; 17799 } 17800 17801 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17802 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17803 } 17804 17805 /** 17806 * This method is an internal method that could be get invoked either 17807 * to delete an installed package or to clean up a failed installation. 17808 * After deleting an installed package, a broadcast is sent to notify any 17809 * listeners that the package has been removed. For cleaning up a failed 17810 * installation, the broadcast is not necessary since the package's 17811 * installation wouldn't have sent the initial broadcast either 17812 * The key steps in deleting a package are 17813 * deleting the package information in internal structures like mPackages, 17814 * deleting the packages base directories through installd 17815 * updating mSettings to reflect current status 17816 * persisting settings for later use 17817 * sending a broadcast if necessary 17818 */ 17819 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17820 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17821 final boolean res; 17822 17823 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17824 ? UserHandle.USER_ALL : userId; 17825 17826 if (isPackageDeviceAdmin(packageName, removeUser)) { 17827 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17828 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17829 } 17830 17831 PackageSetting uninstalledPs = null; 17832 PackageParser.Package pkg = null; 17833 17834 // for the uninstall-updates case and restricted profiles, remember the per- 17835 // user handle installed state 17836 int[] allUsers; 17837 synchronized (mPackages) { 17838 uninstalledPs = mSettings.mPackages.get(packageName); 17839 if (uninstalledPs == null) { 17840 Slog.w(TAG, "Not removing non-existent package " + packageName); 17841 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17842 } 17843 17844 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17845 && uninstalledPs.versionCode != versionCode) { 17846 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17847 + uninstalledPs.versionCode + " != " + versionCode); 17848 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17849 } 17850 17851 // Static shared libs can be declared by any package, so let us not 17852 // allow removing a package if it provides a lib others depend on. 17853 pkg = mPackages.get(packageName); 17854 17855 allUsers = sUserManager.getUserIds(); 17856 17857 if (pkg != null && pkg.staticSharedLibName != null) { 17858 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17859 pkg.staticSharedLibVersion); 17860 if (libEntry != null) { 17861 for (int currUserId : allUsers) { 17862 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17863 continue; 17864 } 17865 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17866 libEntry.info, 0, currUserId); 17867 if (!ArrayUtils.isEmpty(libClientPackages)) { 17868 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17869 + " hosting lib " + libEntry.info.getName() + " version " 17870 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17871 + " for user " + currUserId); 17872 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17873 } 17874 } 17875 } 17876 } 17877 17878 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17879 } 17880 17881 final int freezeUser; 17882 if (isUpdatedSystemApp(uninstalledPs) 17883 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17884 // We're downgrading a system app, which will apply to all users, so 17885 // freeze them all during the downgrade 17886 freezeUser = UserHandle.USER_ALL; 17887 } else { 17888 freezeUser = removeUser; 17889 } 17890 17891 synchronized (mInstallLock) { 17892 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17893 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17894 deleteFlags, "deletePackageX")) { 17895 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17896 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17897 } 17898 synchronized (mPackages) { 17899 if (res) { 17900 if (pkg != null) { 17901 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17902 } 17903 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17904 updateInstantAppInstallerLocked(packageName); 17905 } 17906 } 17907 } 17908 17909 if (res) { 17910 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17911 info.sendPackageRemovedBroadcasts(killApp); 17912 info.sendSystemPackageUpdatedBroadcasts(); 17913 info.sendSystemPackageAppearedBroadcasts(); 17914 } 17915 // Force a gc here. 17916 Runtime.getRuntime().gc(); 17917 // Delete the resources here after sending the broadcast to let 17918 // other processes clean up before deleting resources. 17919 if (info.args != null) { 17920 synchronized (mInstallLock) { 17921 info.args.doPostDeleteLI(true); 17922 } 17923 } 17924 17925 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17926 } 17927 17928 static class PackageRemovedInfo { 17929 final PackageSender packageSender; 17930 String removedPackage; 17931 String installerPackageName; 17932 int uid = -1; 17933 int removedAppId = -1; 17934 int[] origUsers; 17935 int[] removedUsers = null; 17936 int[] broadcastUsers = null; 17937 int[] instantUserIds = null; 17938 SparseArray<Integer> installReasons; 17939 boolean isRemovedPackageSystemUpdate = false; 17940 boolean isUpdate; 17941 boolean dataRemoved; 17942 boolean removedForAllUsers; 17943 boolean isStaticSharedLib; 17944 // Clean up resources deleted packages. 17945 InstallArgs args = null; 17946 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17947 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17948 17949 PackageRemovedInfo(PackageSender packageSender) { 17950 this.packageSender = packageSender; 17951 } 17952 17953 void sendPackageRemovedBroadcasts(boolean killApp) { 17954 sendPackageRemovedBroadcastInternal(killApp); 17955 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17956 for (int i = 0; i < childCount; i++) { 17957 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17958 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17959 } 17960 } 17961 17962 void sendSystemPackageUpdatedBroadcasts() { 17963 if (isRemovedPackageSystemUpdate) { 17964 sendSystemPackageUpdatedBroadcastsInternal(); 17965 final int childCount = (removedChildPackages != null) 17966 ? removedChildPackages.size() : 0; 17967 for (int i = 0; i < childCount; i++) { 17968 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17969 if (childInfo.isRemovedPackageSystemUpdate) { 17970 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17971 } 17972 } 17973 } 17974 } 17975 17976 void sendSystemPackageAppearedBroadcasts() { 17977 final int packageCount = (appearedChildPackages != null) 17978 ? appearedChildPackages.size() : 0; 17979 for (int i = 0; i < packageCount; i++) { 17980 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17981 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17982 true /*sendBootCompleted*/, false /*startReceiver*/, 17983 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17984 } 17985 } 17986 17987 private void sendSystemPackageUpdatedBroadcastsInternal() { 17988 Bundle extras = new Bundle(2); 17989 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17990 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17991 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17992 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17993 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17994 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17995 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17996 null, null, 0, removedPackage, null, null, null); 17997 if (installerPackageName != null) { 17998 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17999 removedPackage, extras, 0 /*flags*/, 18000 installerPackageName, null, null, null); 18001 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18002 removedPackage, extras, 0 /*flags*/, 18003 installerPackageName, null, null, null); 18004 } 18005 } 18006 18007 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18008 // Don't send static shared library removal broadcasts as these 18009 // libs are visible only the the apps that depend on them an one 18010 // cannot remove the library if it has a dependency. 18011 if (isStaticSharedLib) { 18012 return; 18013 } 18014 Bundle extras = new Bundle(2); 18015 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18016 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18017 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18018 if (isUpdate || isRemovedPackageSystemUpdate) { 18019 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18020 } 18021 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18022 if (removedPackage != null) { 18023 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18024 removedPackage, extras, 0, null /*targetPackage*/, null, 18025 broadcastUsers, instantUserIds); 18026 if (installerPackageName != null) { 18027 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18028 removedPackage, extras, 0 /*flags*/, 18029 installerPackageName, null, broadcastUsers, instantUserIds); 18030 } 18031 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18032 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18033 removedPackage, extras, 18034 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18035 null, null, broadcastUsers, instantUserIds); 18036 packageSender.notifyPackageRemoved(removedPackage); 18037 } 18038 } 18039 if (removedAppId >= 0) { 18040 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18041 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18042 null, null, broadcastUsers, instantUserIds); 18043 } 18044 } 18045 18046 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18047 removedUsers = userIds; 18048 if (removedUsers == null) { 18049 broadcastUsers = null; 18050 return; 18051 } 18052 18053 broadcastUsers = EMPTY_INT_ARRAY; 18054 instantUserIds = EMPTY_INT_ARRAY; 18055 for (int i = userIds.length - 1; i >= 0; --i) { 18056 final int userId = userIds[i]; 18057 if (deletedPackageSetting.getInstantApp(userId)) { 18058 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18059 } else { 18060 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18061 } 18062 } 18063 } 18064 } 18065 18066 /* 18067 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18068 * flag is not set, the data directory is removed as well. 18069 * make sure this flag is set for partially installed apps. If not its meaningless to 18070 * delete a partially installed application. 18071 */ 18072 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18073 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18074 String packageName = ps.name; 18075 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18076 // Retrieve object to delete permissions for shared user later on 18077 final PackageParser.Package deletedPkg; 18078 final PackageSetting deletedPs; 18079 // reader 18080 synchronized (mPackages) { 18081 deletedPkg = mPackages.get(packageName); 18082 deletedPs = mSettings.mPackages.get(packageName); 18083 if (outInfo != null) { 18084 outInfo.removedPackage = packageName; 18085 outInfo.installerPackageName = ps.installerPackageName; 18086 outInfo.isStaticSharedLib = deletedPkg != null 18087 && deletedPkg.staticSharedLibName != null; 18088 outInfo.populateUsers(deletedPs == null ? null 18089 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18090 } 18091 } 18092 18093 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18094 18095 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18096 final PackageParser.Package resolvedPkg; 18097 if (deletedPkg != null) { 18098 resolvedPkg = deletedPkg; 18099 } else { 18100 // We don't have a parsed package when it lives on an ejected 18101 // adopted storage device, so fake something together 18102 resolvedPkg = new PackageParser.Package(ps.name); 18103 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18104 } 18105 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18106 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18107 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18108 if (outInfo != null) { 18109 outInfo.dataRemoved = true; 18110 } 18111 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18112 } 18113 18114 int removedAppId = -1; 18115 18116 // writer 18117 synchronized (mPackages) { 18118 boolean installedStateChanged = false; 18119 if (deletedPs != null) { 18120 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18121 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18122 clearDefaultBrowserIfNeeded(packageName); 18123 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18124 removedAppId = mSettings.removePackageLPw(packageName); 18125 if (outInfo != null) { 18126 outInfo.removedAppId = removedAppId; 18127 } 18128 mPermissionManager.updatePermissions( 18129 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18130 if (deletedPs.sharedUser != null) { 18131 // Remove permissions associated with package. Since runtime 18132 // permissions are per user we have to kill the removed package 18133 // or packages running under the shared user of the removed 18134 // package if revoking the permissions requested only by the removed 18135 // package is successful and this causes a change in gids. 18136 for (int userId : UserManagerService.getInstance().getUserIds()) { 18137 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18138 userId); 18139 if (userIdToKill == UserHandle.USER_ALL 18140 || userIdToKill >= UserHandle.USER_SYSTEM) { 18141 // If gids changed for this user, kill all affected packages. 18142 mHandler.post(new Runnable() { 18143 @Override 18144 public void run() { 18145 // This has to happen with no lock held. 18146 killApplication(deletedPs.name, deletedPs.appId, 18147 KILL_APP_REASON_GIDS_CHANGED); 18148 } 18149 }); 18150 break; 18151 } 18152 } 18153 } 18154 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18155 } 18156 // make sure to preserve per-user disabled state if this removal was just 18157 // a downgrade of a system app to the factory package 18158 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18159 if (DEBUG_REMOVE) { 18160 Slog.d(TAG, "Propagating install state across downgrade"); 18161 } 18162 for (int userId : allUserHandles) { 18163 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18164 if (DEBUG_REMOVE) { 18165 Slog.d(TAG, " user " + userId + " => " + installed); 18166 } 18167 if (installed != ps.getInstalled(userId)) { 18168 installedStateChanged = true; 18169 } 18170 ps.setInstalled(installed, userId); 18171 } 18172 } 18173 } 18174 // can downgrade to reader 18175 if (writeSettings) { 18176 // Save settings now 18177 mSettings.writeLPr(); 18178 } 18179 if (installedStateChanged) { 18180 mSettings.writeKernelMappingLPr(ps); 18181 } 18182 } 18183 if (removedAppId != -1) { 18184 // A user ID was deleted here. Go through all users and remove it 18185 // from KeyStore. 18186 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18187 } 18188 } 18189 18190 static boolean locationIsPrivileged(String path) { 18191 try { 18192 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18193 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18194 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18195 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18196 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18197 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18198 } catch (IOException e) { 18199 Slog.e(TAG, "Unable to access code path " + path); 18200 } 18201 return false; 18202 } 18203 18204 static boolean locationIsOem(String path) { 18205 try { 18206 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18207 } catch (IOException e) { 18208 Slog.e(TAG, "Unable to access code path " + path); 18209 } 18210 return false; 18211 } 18212 18213 static boolean locationIsVendor(String path) { 18214 try { 18215 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18216 } catch (IOException e) { 18217 Slog.e(TAG, "Unable to access code path " + path); 18218 } 18219 return false; 18220 } 18221 18222 static boolean locationIsProduct(String path) { 18223 try { 18224 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18225 } catch (IOException e) { 18226 Slog.e(TAG, "Unable to access code path " + path); 18227 } 18228 return false; 18229 } 18230 18231 /* 18232 * Tries to delete system package. 18233 */ 18234 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18235 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18236 boolean writeSettings) { 18237 if (deletedPs.parentPackageName != null) { 18238 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18239 return false; 18240 } 18241 18242 final boolean applyUserRestrictions 18243 = (allUserHandles != null) && (outInfo.origUsers != null); 18244 final PackageSetting disabledPs; 18245 // Confirm if the system package has been updated 18246 // An updated system app can be deleted. This will also have to restore 18247 // the system pkg from system partition 18248 // reader 18249 synchronized (mPackages) { 18250 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18251 } 18252 18253 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18254 + " disabledPs=" + disabledPs); 18255 18256 if (disabledPs == null) { 18257 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18258 return false; 18259 } else if (DEBUG_REMOVE) { 18260 Slog.d(TAG, "Deleting system pkg from data partition"); 18261 } 18262 18263 if (DEBUG_REMOVE) { 18264 if (applyUserRestrictions) { 18265 Slog.d(TAG, "Remembering install states:"); 18266 for (int userId : allUserHandles) { 18267 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18268 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18269 } 18270 } 18271 } 18272 18273 // Delete the updated package 18274 outInfo.isRemovedPackageSystemUpdate = true; 18275 if (outInfo.removedChildPackages != null) { 18276 final int childCount = (deletedPs.childPackageNames != null) 18277 ? deletedPs.childPackageNames.size() : 0; 18278 for (int i = 0; i < childCount; i++) { 18279 String childPackageName = deletedPs.childPackageNames.get(i); 18280 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18281 .contains(childPackageName)) { 18282 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18283 childPackageName); 18284 if (childInfo != null) { 18285 childInfo.isRemovedPackageSystemUpdate = true; 18286 } 18287 } 18288 } 18289 } 18290 18291 if (disabledPs.versionCode < deletedPs.versionCode) { 18292 // Delete data for downgrades 18293 flags &= ~PackageManager.DELETE_KEEP_DATA; 18294 } else { 18295 // Preserve data by setting flag 18296 flags |= PackageManager.DELETE_KEEP_DATA; 18297 } 18298 18299 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18300 outInfo, writeSettings, disabledPs.pkg); 18301 if (!ret) { 18302 return false; 18303 } 18304 18305 // writer 18306 synchronized (mPackages) { 18307 // NOTE: The system package always needs to be enabled; even if it's for 18308 // a compressed stub. If we don't, installing the system package fails 18309 // during scan [scanning checks the disabled packages]. We will reverse 18310 // this later, after we've "installed" the stub. 18311 // Reinstate the old system package 18312 enableSystemPackageLPw(disabledPs.pkg); 18313 // Remove any native libraries from the upgraded package. 18314 removeNativeBinariesLI(deletedPs); 18315 } 18316 18317 // Install the system package 18318 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18319 try { 18320 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18321 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18322 } catch (PackageManagerException e) { 18323 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18324 + e.getMessage()); 18325 return false; 18326 } finally { 18327 if (disabledPs.pkg.isStub) { 18328 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18329 } 18330 } 18331 return true; 18332 } 18333 18334 /** 18335 * Installs a package that's already on the system partition. 18336 */ 18337 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18338 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18339 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18340 throws PackageManagerException { 18341 @ParseFlags int parseFlags = 18342 mDefParseFlags 18343 | PackageParser.PARSE_MUST_BE_APK 18344 | PackageParser.PARSE_IS_SYSTEM_DIR; 18345 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18346 if (isPrivileged || locationIsPrivileged(codePathString)) { 18347 scanFlags |= SCAN_AS_PRIVILEGED; 18348 } 18349 if (locationIsOem(codePathString)) { 18350 scanFlags |= SCAN_AS_OEM; 18351 } 18352 if (locationIsVendor(codePathString)) { 18353 scanFlags |= SCAN_AS_VENDOR; 18354 } 18355 if (locationIsProduct(codePathString)) { 18356 scanFlags |= SCAN_AS_PRODUCT; 18357 } 18358 18359 final File codePath = new File(codePathString); 18360 final PackageParser.Package pkg = 18361 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18362 18363 try { 18364 // update shared libraries for the newly re-installed system package 18365 updateSharedLibrariesLPr(pkg, null); 18366 } catch (PackageManagerException e) { 18367 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18368 } 18369 18370 prepareAppDataAfterInstallLIF(pkg); 18371 18372 // writer 18373 synchronized (mPackages) { 18374 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18375 18376 // Propagate the permissions state as we do not want to drop on the floor 18377 // runtime permissions. The update permissions method below will take 18378 // care of removing obsolete permissions and grant install permissions. 18379 if (origPermissionState != null) { 18380 ps.getPermissionsState().copyFrom(origPermissionState); 18381 } 18382 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18383 mPermissionCallback); 18384 18385 final boolean applyUserRestrictions 18386 = (allUserHandles != null) && (origUserHandles != null); 18387 if (applyUserRestrictions) { 18388 boolean installedStateChanged = false; 18389 if (DEBUG_REMOVE) { 18390 Slog.d(TAG, "Propagating install state across reinstall"); 18391 } 18392 for (int userId : allUserHandles) { 18393 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18394 if (DEBUG_REMOVE) { 18395 Slog.d(TAG, " user " + userId + " => " + installed); 18396 } 18397 if (installed != ps.getInstalled(userId)) { 18398 installedStateChanged = true; 18399 } 18400 ps.setInstalled(installed, userId); 18401 18402 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18403 } 18404 // Regardless of writeSettings we need to ensure that this restriction 18405 // state propagation is persisted 18406 mSettings.writeAllUsersPackageRestrictionsLPr(); 18407 if (installedStateChanged) { 18408 mSettings.writeKernelMappingLPr(ps); 18409 } 18410 } 18411 // can downgrade to reader here 18412 if (writeSettings) { 18413 mSettings.writeLPr(); 18414 } 18415 } 18416 return pkg; 18417 } 18418 18419 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18420 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18421 PackageRemovedInfo outInfo, boolean writeSettings, 18422 PackageParser.Package replacingPackage) { 18423 synchronized (mPackages) { 18424 if (outInfo != null) { 18425 outInfo.uid = ps.appId; 18426 } 18427 18428 if (outInfo != null && outInfo.removedChildPackages != null) { 18429 final int childCount = (ps.childPackageNames != null) 18430 ? ps.childPackageNames.size() : 0; 18431 for (int i = 0; i < childCount; i++) { 18432 String childPackageName = ps.childPackageNames.get(i); 18433 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18434 if (childPs == null) { 18435 return false; 18436 } 18437 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18438 childPackageName); 18439 if (childInfo != null) { 18440 childInfo.uid = childPs.appId; 18441 } 18442 } 18443 } 18444 } 18445 18446 // Delete package data from internal structures and also remove data if flag is set 18447 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18448 18449 // Delete the child packages data 18450 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18451 for (int i = 0; i < childCount; i++) { 18452 PackageSetting childPs; 18453 synchronized (mPackages) { 18454 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18455 } 18456 if (childPs != null) { 18457 PackageRemovedInfo childOutInfo = (outInfo != null 18458 && outInfo.removedChildPackages != null) 18459 ? outInfo.removedChildPackages.get(childPs.name) : null; 18460 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18461 && (replacingPackage != null 18462 && !replacingPackage.hasChildPackage(childPs.name)) 18463 ? flags & ~DELETE_KEEP_DATA : flags; 18464 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18465 deleteFlags, writeSettings); 18466 } 18467 } 18468 18469 // Delete application code and resources only for parent packages 18470 if (ps.parentPackageName == null) { 18471 if (deleteCodeAndResources && (outInfo != null)) { 18472 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18473 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18474 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18475 } 18476 } 18477 18478 return true; 18479 } 18480 18481 @Override 18482 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18483 int userId) { 18484 mContext.enforceCallingOrSelfPermission( 18485 android.Manifest.permission.DELETE_PACKAGES, null); 18486 synchronized (mPackages) { 18487 // Cannot block uninstall of static shared libs as they are 18488 // considered a part of the using app (emulating static linking). 18489 // Also static libs are installed always on internal storage. 18490 PackageParser.Package pkg = mPackages.get(packageName); 18491 if (pkg != null && pkg.staticSharedLibName != null) { 18492 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18493 + " providing static shared library: " + pkg.staticSharedLibName); 18494 return false; 18495 } 18496 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18497 mSettings.writePackageRestrictionsLPr(userId); 18498 } 18499 return true; 18500 } 18501 18502 @Override 18503 public boolean getBlockUninstallForUser(String packageName, int userId) { 18504 synchronized (mPackages) { 18505 final PackageSetting ps = mSettings.mPackages.get(packageName); 18506 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18507 return false; 18508 } 18509 return mSettings.getBlockUninstallLPr(userId, packageName); 18510 } 18511 } 18512 18513 @Override 18514 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18515 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18516 synchronized (mPackages) { 18517 PackageSetting ps = mSettings.mPackages.get(packageName); 18518 if (ps == null) { 18519 Log.w(TAG, "Package doesn't exist: " + packageName); 18520 return false; 18521 } 18522 if (systemUserApp) { 18523 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18524 } else { 18525 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18526 } 18527 mSettings.writeLPr(); 18528 } 18529 return true; 18530 } 18531 18532 /* 18533 * This method handles package deletion in general 18534 */ 18535 private boolean deletePackageLIF(String packageName, UserHandle user, 18536 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18537 PackageRemovedInfo outInfo, boolean writeSettings, 18538 PackageParser.Package replacingPackage) { 18539 if (packageName == null) { 18540 Slog.w(TAG, "Attempt to delete null packageName."); 18541 return false; 18542 } 18543 18544 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18545 18546 PackageSetting ps; 18547 synchronized (mPackages) { 18548 ps = mSettings.mPackages.get(packageName); 18549 if (ps == null) { 18550 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18551 return false; 18552 } 18553 18554 if (ps.parentPackageName != null && (!isSystemApp(ps) 18555 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18556 if (DEBUG_REMOVE) { 18557 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18558 + ((user == null) ? UserHandle.USER_ALL : user)); 18559 } 18560 final int removedUserId = (user != null) ? user.getIdentifier() 18561 : UserHandle.USER_ALL; 18562 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18563 return false; 18564 } 18565 markPackageUninstalledForUserLPw(ps, user); 18566 scheduleWritePackageRestrictionsLocked(user); 18567 return true; 18568 } 18569 } 18570 18571 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18572 && user.getIdentifier() != UserHandle.USER_ALL)) { 18573 // The caller is asking that the package only be deleted for a single 18574 // user. To do this, we just mark its uninstalled state and delete 18575 // its data. If this is a system app, we only allow this to happen if 18576 // they have set the special DELETE_SYSTEM_APP which requests different 18577 // semantics than normal for uninstalling system apps. 18578 markPackageUninstalledForUserLPw(ps, user); 18579 18580 if (!isSystemApp(ps)) { 18581 // Do not uninstall the APK if an app should be cached 18582 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18583 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18584 // Other user still have this package installed, so all 18585 // we need to do is clear this user's data and save that 18586 // it is uninstalled. 18587 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18588 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18589 return false; 18590 } 18591 scheduleWritePackageRestrictionsLocked(user); 18592 return true; 18593 } else { 18594 // We need to set it back to 'installed' so the uninstall 18595 // broadcasts will be sent correctly. 18596 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18597 ps.setInstalled(true, user.getIdentifier()); 18598 mSettings.writeKernelMappingLPr(ps); 18599 } 18600 } else { 18601 // This is a system app, so we assume that the 18602 // other users still have this package installed, so all 18603 // we need to do is clear this user's data and save that 18604 // it is uninstalled. 18605 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18606 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18607 return false; 18608 } 18609 scheduleWritePackageRestrictionsLocked(user); 18610 return true; 18611 } 18612 } 18613 18614 // If we are deleting a composite package for all users, keep track 18615 // of result for each child. 18616 if (ps.childPackageNames != null && outInfo != null) { 18617 synchronized (mPackages) { 18618 final int childCount = ps.childPackageNames.size(); 18619 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18620 for (int i = 0; i < childCount; i++) { 18621 String childPackageName = ps.childPackageNames.get(i); 18622 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18623 childInfo.removedPackage = childPackageName; 18624 childInfo.installerPackageName = ps.installerPackageName; 18625 outInfo.removedChildPackages.put(childPackageName, childInfo); 18626 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18627 if (childPs != null) { 18628 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18629 } 18630 } 18631 } 18632 } 18633 18634 boolean ret = false; 18635 if (isSystemApp(ps)) { 18636 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18637 // When an updated system application is deleted we delete the existing resources 18638 // as well and fall back to existing code in system partition 18639 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18640 } else { 18641 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18642 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18643 outInfo, writeSettings, replacingPackage); 18644 } 18645 18646 // Take a note whether we deleted the package for all users 18647 if (outInfo != null) { 18648 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18649 if (outInfo.removedChildPackages != null) { 18650 synchronized (mPackages) { 18651 final int childCount = outInfo.removedChildPackages.size(); 18652 for (int i = 0; i < childCount; i++) { 18653 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18654 if (childInfo != null) { 18655 childInfo.removedForAllUsers = mPackages.get( 18656 childInfo.removedPackage) == null; 18657 } 18658 } 18659 } 18660 } 18661 // If we uninstalled an update to a system app there may be some 18662 // child packages that appeared as they are declared in the system 18663 // app but were not declared in the update. 18664 if (isSystemApp(ps)) { 18665 synchronized (mPackages) { 18666 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18667 final int childCount = (updatedPs.childPackageNames != null) 18668 ? updatedPs.childPackageNames.size() : 0; 18669 for (int i = 0; i < childCount; i++) { 18670 String childPackageName = updatedPs.childPackageNames.get(i); 18671 if (outInfo.removedChildPackages == null 18672 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18673 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18674 if (childPs == null) { 18675 continue; 18676 } 18677 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18678 installRes.name = childPackageName; 18679 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18680 installRes.pkg = mPackages.get(childPackageName); 18681 installRes.uid = childPs.pkg.applicationInfo.uid; 18682 if (outInfo.appearedChildPackages == null) { 18683 outInfo.appearedChildPackages = new ArrayMap<>(); 18684 } 18685 outInfo.appearedChildPackages.put(childPackageName, installRes); 18686 } 18687 } 18688 } 18689 } 18690 } 18691 18692 return ret; 18693 } 18694 18695 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18696 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18697 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18698 for (int nextUserId : userIds) { 18699 if (DEBUG_REMOVE) { 18700 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18701 } 18702 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18703 false /*installed*/, 18704 true /*stopped*/, 18705 true /*notLaunched*/, 18706 false /*hidden*/, 18707 false /*suspended*/, 18708 false /*instantApp*/, 18709 false /*virtualPreload*/, 18710 null /*lastDisableAppCaller*/, 18711 null /*enabledComponents*/, 18712 null /*disabledComponents*/, 18713 ps.readUserState(nextUserId).domainVerificationStatus, 18714 0, PackageManager.INSTALL_REASON_UNKNOWN, 18715 null /*harmfulAppWarning*/); 18716 } 18717 mSettings.writeKernelMappingLPr(ps); 18718 } 18719 18720 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18721 PackageRemovedInfo outInfo) { 18722 final PackageParser.Package pkg; 18723 synchronized (mPackages) { 18724 pkg = mPackages.get(ps.name); 18725 } 18726 18727 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18728 : new int[] {userId}; 18729 for (int nextUserId : userIds) { 18730 if (DEBUG_REMOVE) { 18731 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18732 + nextUserId); 18733 } 18734 18735 destroyAppDataLIF(pkg, userId, 18736 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18737 destroyAppProfilesLIF(pkg, userId); 18738 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18739 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18740 schedulePackageCleaning(ps.name, nextUserId, false); 18741 synchronized (mPackages) { 18742 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18743 scheduleWritePackageRestrictionsLocked(nextUserId); 18744 } 18745 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18746 } 18747 } 18748 18749 if (outInfo != null) { 18750 outInfo.removedPackage = ps.name; 18751 outInfo.installerPackageName = ps.installerPackageName; 18752 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18753 outInfo.removedAppId = ps.appId; 18754 outInfo.removedUsers = userIds; 18755 outInfo.broadcastUsers = userIds; 18756 } 18757 18758 return true; 18759 } 18760 18761 private final class ClearStorageConnection implements ServiceConnection { 18762 IMediaContainerService mContainerService; 18763 18764 @Override 18765 public void onServiceConnected(ComponentName name, IBinder service) { 18766 synchronized (this) { 18767 mContainerService = IMediaContainerService.Stub 18768 .asInterface(Binder.allowBlocking(service)); 18769 notifyAll(); 18770 } 18771 } 18772 18773 @Override 18774 public void onServiceDisconnected(ComponentName name) { 18775 } 18776 } 18777 18778 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18779 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18780 18781 final boolean mounted; 18782 if (Environment.isExternalStorageEmulated()) { 18783 mounted = true; 18784 } else { 18785 final String status = Environment.getExternalStorageState(); 18786 18787 mounted = status.equals(Environment.MEDIA_MOUNTED) 18788 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18789 } 18790 18791 if (!mounted) { 18792 return; 18793 } 18794 18795 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18796 int[] users; 18797 if (userId == UserHandle.USER_ALL) { 18798 users = sUserManager.getUserIds(); 18799 } else { 18800 users = new int[] { userId }; 18801 } 18802 final ClearStorageConnection conn = new ClearStorageConnection(); 18803 if (mContext.bindServiceAsUser( 18804 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18805 try { 18806 for (int curUser : users) { 18807 long timeout = SystemClock.uptimeMillis() + 5000; 18808 synchronized (conn) { 18809 long now; 18810 while (conn.mContainerService == null && 18811 (now = SystemClock.uptimeMillis()) < timeout) { 18812 try { 18813 conn.wait(timeout - now); 18814 } catch (InterruptedException e) { 18815 } 18816 } 18817 } 18818 if (conn.mContainerService == null) { 18819 return; 18820 } 18821 18822 final UserEnvironment userEnv = new UserEnvironment(curUser); 18823 clearDirectory(conn.mContainerService, 18824 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18825 if (allData) { 18826 clearDirectory(conn.mContainerService, 18827 userEnv.buildExternalStorageAppDataDirs(packageName)); 18828 clearDirectory(conn.mContainerService, 18829 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18830 } 18831 } 18832 } finally { 18833 mContext.unbindService(conn); 18834 } 18835 } 18836 } 18837 18838 @Override 18839 public void clearApplicationProfileData(String packageName) { 18840 enforceSystemOrRoot("Only the system can clear all profile data"); 18841 18842 final PackageParser.Package pkg; 18843 synchronized (mPackages) { 18844 pkg = mPackages.get(packageName); 18845 } 18846 18847 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18848 synchronized (mInstallLock) { 18849 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18850 } 18851 } 18852 } 18853 18854 @Override 18855 public void clearApplicationUserData(final String packageName, 18856 final IPackageDataObserver observer, final int userId) { 18857 mContext.enforceCallingOrSelfPermission( 18858 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18859 18860 final int callingUid = Binder.getCallingUid(); 18861 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18862 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18863 18864 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18865 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18866 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18867 throw new SecurityException("Cannot clear data for a protected package: " 18868 + packageName); 18869 } 18870 // Queue up an async operation since the package deletion may take a little while. 18871 mHandler.post(new Runnable() { 18872 public void run() { 18873 mHandler.removeCallbacks(this); 18874 final boolean succeeded; 18875 if (!filterApp) { 18876 try (PackageFreezer freezer = freezePackage(packageName, 18877 "clearApplicationUserData")) { 18878 synchronized (mInstallLock) { 18879 succeeded = clearApplicationUserDataLIF(packageName, userId); 18880 } 18881 clearExternalStorageDataSync(packageName, userId, true); 18882 synchronized (mPackages) { 18883 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18884 packageName, userId); 18885 } 18886 } 18887 if (succeeded) { 18888 // invoke DeviceStorageMonitor's update method to clear any notifications 18889 DeviceStorageMonitorInternal dsm = LocalServices 18890 .getService(DeviceStorageMonitorInternal.class); 18891 if (dsm != null) { 18892 dsm.checkMemory(); 18893 } 18894 } 18895 } else { 18896 succeeded = false; 18897 } 18898 if (observer != null) { 18899 try { 18900 observer.onRemoveCompleted(packageName, succeeded); 18901 } catch (RemoteException e) { 18902 Log.i(TAG, "Observer no longer exists."); 18903 } 18904 } //end if observer 18905 } //end run 18906 }); 18907 } 18908 18909 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18910 if (packageName == null) { 18911 Slog.w(TAG, "Attempt to delete null packageName."); 18912 return false; 18913 } 18914 18915 // Try finding details about the requested package 18916 PackageParser.Package pkg; 18917 synchronized (mPackages) { 18918 pkg = mPackages.get(packageName); 18919 if (pkg == null) { 18920 final PackageSetting ps = mSettings.mPackages.get(packageName); 18921 if (ps != null) { 18922 pkg = ps.pkg; 18923 } 18924 } 18925 18926 if (pkg == null) { 18927 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18928 return false; 18929 } 18930 18931 PackageSetting ps = (PackageSetting) pkg.mExtras; 18932 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18933 } 18934 18935 clearAppDataLIF(pkg, userId, 18936 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18937 18938 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18939 removeKeystoreDataIfNeeded(userId, appId); 18940 18941 UserManagerInternal umInternal = getUserManagerInternal(); 18942 final int flags; 18943 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18944 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18945 } else if (umInternal.isUserRunning(userId)) { 18946 flags = StorageManager.FLAG_STORAGE_DE; 18947 } else { 18948 flags = 0; 18949 } 18950 prepareAppDataContentsLIF(pkg, userId, flags); 18951 18952 return true; 18953 } 18954 18955 /** 18956 * Reverts user permission state changes (permissions and flags) in 18957 * all packages for a given user. 18958 * 18959 * @param userId The device user for which to do a reset. 18960 */ 18961 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18962 final int packageCount = mPackages.size(); 18963 for (int i = 0; i < packageCount; i++) { 18964 PackageParser.Package pkg = mPackages.valueAt(i); 18965 PackageSetting ps = (PackageSetting) pkg.mExtras; 18966 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18967 } 18968 } 18969 18970 private void resetNetworkPolicies(int userId) { 18971 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18972 } 18973 18974 /** 18975 * Reverts user permission state changes (permissions and flags). 18976 * 18977 * @param ps The package for which to reset. 18978 * @param userId The device user for which to do a reset. 18979 */ 18980 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18981 final PackageSetting ps, final int userId) { 18982 if (ps.pkg == null) { 18983 return; 18984 } 18985 18986 // These are flags that can change base on user actions. 18987 final int userSettableMask = FLAG_PERMISSION_USER_SET 18988 | FLAG_PERMISSION_USER_FIXED 18989 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18990 | FLAG_PERMISSION_REVIEW_REQUIRED; 18991 18992 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18993 | FLAG_PERMISSION_POLICY_FIXED; 18994 18995 boolean writeInstallPermissions = false; 18996 boolean writeRuntimePermissions = false; 18997 18998 final int permissionCount = ps.pkg.requestedPermissions.size(); 18999 for (int i = 0; i < permissionCount; i++) { 19000 final String permName = ps.pkg.requestedPermissions.get(i); 19001 final BasePermission bp = 19002 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19003 if (bp == null) { 19004 continue; 19005 } 19006 19007 // If shared user we just reset the state to which only this app contributed. 19008 if (ps.sharedUser != null) { 19009 boolean used = false; 19010 final int packageCount = ps.sharedUser.packages.size(); 19011 for (int j = 0; j < packageCount; j++) { 19012 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19013 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19014 && pkg.pkg.requestedPermissions.contains(permName)) { 19015 used = true; 19016 break; 19017 } 19018 } 19019 if (used) { 19020 continue; 19021 } 19022 } 19023 19024 final PermissionsState permissionsState = ps.getPermissionsState(); 19025 19026 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19027 19028 // Always clear the user settable flags. 19029 final boolean hasInstallState = 19030 permissionsState.getInstallPermissionState(permName) != null; 19031 // If permission review is enabled and this is a legacy app, mark the 19032 // permission as requiring a review as this is the initial state. 19033 int flags = 0; 19034 if (mSettings.mPermissions.mPermissionReviewRequired 19035 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19036 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19037 } 19038 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19039 if (hasInstallState) { 19040 writeInstallPermissions = true; 19041 } else { 19042 writeRuntimePermissions = true; 19043 } 19044 } 19045 19046 // Below is only runtime permission handling. 19047 if (!bp.isRuntime()) { 19048 continue; 19049 } 19050 19051 // Never clobber system or policy. 19052 if ((oldFlags & policyOrSystemFlags) != 0) { 19053 continue; 19054 } 19055 19056 // If this permission was granted by default, make sure it is. 19057 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19058 if (permissionsState.grantRuntimePermission(bp, userId) 19059 != PERMISSION_OPERATION_FAILURE) { 19060 writeRuntimePermissions = true; 19061 } 19062 // If permission review is enabled the permissions for a legacy apps 19063 // are represented as constantly granted runtime ones, so don't revoke. 19064 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19065 // Otherwise, reset the permission. 19066 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19067 switch (revokeResult) { 19068 case PERMISSION_OPERATION_SUCCESS: 19069 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19070 writeRuntimePermissions = true; 19071 final int appId = ps.appId; 19072 mHandler.post(new Runnable() { 19073 @Override 19074 public void run() { 19075 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19076 } 19077 }); 19078 } break; 19079 } 19080 } 19081 } 19082 19083 // Synchronously write as we are taking permissions away. 19084 if (writeRuntimePermissions) { 19085 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19086 } 19087 19088 // Synchronously write as we are taking permissions away. 19089 if (writeInstallPermissions) { 19090 mSettings.writeLPr(); 19091 } 19092 } 19093 19094 /** 19095 * Remove entries from the keystore daemon. Will only remove it if the 19096 * {@code appId} is valid. 19097 */ 19098 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19099 if (appId < 0) { 19100 return; 19101 } 19102 19103 final KeyStore keyStore = KeyStore.getInstance(); 19104 if (keyStore != null) { 19105 if (userId == UserHandle.USER_ALL) { 19106 for (final int individual : sUserManager.getUserIds()) { 19107 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19108 } 19109 } else { 19110 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19111 } 19112 } else { 19113 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19114 } 19115 } 19116 19117 @Override 19118 public void deleteApplicationCacheFiles(final String packageName, 19119 final IPackageDataObserver observer) { 19120 final int userId = UserHandle.getCallingUserId(); 19121 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19122 } 19123 19124 @Override 19125 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19126 final IPackageDataObserver observer) { 19127 final int callingUid = Binder.getCallingUid(); 19128 mContext.enforceCallingOrSelfPermission( 19129 android.Manifest.permission.DELETE_CACHE_FILES, null); 19130 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19131 /* requireFullPermission= */ true, /* checkShell= */ false, 19132 "delete application cache files"); 19133 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19134 android.Manifest.permission.ACCESS_INSTANT_APPS); 19135 19136 final PackageParser.Package pkg; 19137 synchronized (mPackages) { 19138 pkg = mPackages.get(packageName); 19139 } 19140 19141 // Queue up an async operation since the package deletion may take a little while. 19142 mHandler.post(new Runnable() { 19143 public void run() { 19144 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19145 boolean doClearData = true; 19146 if (ps != null) { 19147 final boolean targetIsInstantApp = 19148 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19149 doClearData = !targetIsInstantApp 19150 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19151 } 19152 if (doClearData) { 19153 synchronized (mInstallLock) { 19154 final int flags = StorageManager.FLAG_STORAGE_DE 19155 | StorageManager.FLAG_STORAGE_CE; 19156 // We're only clearing cache files, so we don't care if the 19157 // app is unfrozen and still able to run 19158 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19159 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19160 } 19161 clearExternalStorageDataSync(packageName, userId, false); 19162 } 19163 if (observer != null) { 19164 try { 19165 observer.onRemoveCompleted(packageName, true); 19166 } catch (RemoteException e) { 19167 Log.i(TAG, "Observer no longer exists."); 19168 } 19169 } 19170 } 19171 }); 19172 } 19173 19174 @Override 19175 public void getPackageSizeInfo(final String packageName, int userHandle, 19176 final IPackageStatsObserver observer) { 19177 throw new UnsupportedOperationException( 19178 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19179 } 19180 19181 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19182 final PackageSetting ps; 19183 synchronized (mPackages) { 19184 ps = mSettings.mPackages.get(packageName); 19185 if (ps == null) { 19186 Slog.w(TAG, "Failed to find settings for " + packageName); 19187 return false; 19188 } 19189 } 19190 19191 final String[] packageNames = { packageName }; 19192 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19193 final String[] codePaths = { ps.codePathString }; 19194 19195 try { 19196 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19197 ps.appId, ceDataInodes, codePaths, stats); 19198 19199 // For now, ignore code size of packages on system partition 19200 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19201 stats.codeSize = 0; 19202 } 19203 19204 // External clients expect these to be tracked separately 19205 stats.dataSize -= stats.cacheSize; 19206 19207 } catch (InstallerException e) { 19208 Slog.w(TAG, String.valueOf(e)); 19209 return false; 19210 } 19211 19212 return true; 19213 } 19214 19215 private int getUidTargetSdkVersionLockedLPr(int uid) { 19216 Object obj = mSettings.getUserIdLPr(uid); 19217 if (obj instanceof SharedUserSetting) { 19218 final SharedUserSetting sus = (SharedUserSetting) obj; 19219 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19220 final Iterator<PackageSetting> it = sus.packages.iterator(); 19221 while (it.hasNext()) { 19222 final PackageSetting ps = it.next(); 19223 if (ps.pkg != null) { 19224 int v = ps.pkg.applicationInfo.targetSdkVersion; 19225 if (v < vers) vers = v; 19226 } 19227 } 19228 return vers; 19229 } else if (obj instanceof PackageSetting) { 19230 final PackageSetting ps = (PackageSetting) obj; 19231 if (ps.pkg != null) { 19232 return ps.pkg.applicationInfo.targetSdkVersion; 19233 } 19234 } 19235 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19236 } 19237 19238 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19239 final PackageParser.Package p = mPackages.get(packageName); 19240 if (p != null) { 19241 return p.applicationInfo.targetSdkVersion; 19242 } 19243 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19244 } 19245 19246 @Override 19247 public void addPreferredActivity(IntentFilter filter, int match, 19248 ComponentName[] set, ComponentName activity, int userId) { 19249 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19250 "Adding preferred"); 19251 } 19252 19253 private void addPreferredActivityInternal(IntentFilter filter, int match, 19254 ComponentName[] set, ComponentName activity, boolean always, int userId, 19255 String opname) { 19256 // writer 19257 int callingUid = Binder.getCallingUid(); 19258 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19259 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19260 if (filter.countActions() == 0) { 19261 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19262 return; 19263 } 19264 synchronized (mPackages) { 19265 if (mContext.checkCallingOrSelfPermission( 19266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19267 != PackageManager.PERMISSION_GRANTED) { 19268 if (getUidTargetSdkVersionLockedLPr(callingUid) 19269 < Build.VERSION_CODES.FROYO) { 19270 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19271 + callingUid); 19272 return; 19273 } 19274 mContext.enforceCallingOrSelfPermission( 19275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19276 } 19277 19278 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19279 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19280 + userId + ":"); 19281 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19282 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19283 scheduleWritePackageRestrictionsLocked(userId); 19284 postPreferredActivityChangedBroadcast(userId); 19285 } 19286 } 19287 19288 private void postPreferredActivityChangedBroadcast(int userId) { 19289 mHandler.post(() -> { 19290 final IActivityManager am = ActivityManager.getService(); 19291 if (am == null) { 19292 return; 19293 } 19294 19295 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19296 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19297 try { 19298 am.broadcastIntent(null, intent, null, null, 19299 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19300 null, false, false, userId); 19301 } catch (RemoteException e) { 19302 } 19303 }); 19304 } 19305 19306 @Override 19307 public void replacePreferredActivity(IntentFilter filter, int match, 19308 ComponentName[] set, ComponentName activity, int userId) { 19309 if (filter.countActions() != 1) { 19310 throw new IllegalArgumentException( 19311 "replacePreferredActivity expects filter to have only 1 action."); 19312 } 19313 if (filter.countDataAuthorities() != 0 19314 || filter.countDataPaths() != 0 19315 || filter.countDataSchemes() > 1 19316 || filter.countDataTypes() != 0) { 19317 throw new IllegalArgumentException( 19318 "replacePreferredActivity expects filter to have no data authorities, " + 19319 "paths, or types; and at most one scheme."); 19320 } 19321 19322 final int callingUid = Binder.getCallingUid(); 19323 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19324 true /* requireFullPermission */, false /* checkShell */, 19325 "replace preferred activity"); 19326 synchronized (mPackages) { 19327 if (mContext.checkCallingOrSelfPermission( 19328 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19329 != PackageManager.PERMISSION_GRANTED) { 19330 if (getUidTargetSdkVersionLockedLPr(callingUid) 19331 < Build.VERSION_CODES.FROYO) { 19332 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19333 + Binder.getCallingUid()); 19334 return; 19335 } 19336 mContext.enforceCallingOrSelfPermission( 19337 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19338 } 19339 19340 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19341 if (pir != null) { 19342 // Get all of the existing entries that exactly match this filter. 19343 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19344 if (existing != null && existing.size() == 1) { 19345 PreferredActivity cur = existing.get(0); 19346 if (DEBUG_PREFERRED) { 19347 Slog.i(TAG, "Checking replace of preferred:"); 19348 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19349 if (!cur.mPref.mAlways) { 19350 Slog.i(TAG, " -- CUR; not mAlways!"); 19351 } else { 19352 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19353 Slog.i(TAG, " -- CUR: mSet=" 19354 + Arrays.toString(cur.mPref.mSetComponents)); 19355 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19356 Slog.i(TAG, " -- NEW: mMatch=" 19357 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19358 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19359 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19360 } 19361 } 19362 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19363 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19364 && cur.mPref.sameSet(set)) { 19365 // Setting the preferred activity to what it happens to be already 19366 if (DEBUG_PREFERRED) { 19367 Slog.i(TAG, "Replacing with same preferred activity " 19368 + cur.mPref.mShortComponent + " for user " 19369 + userId + ":"); 19370 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19371 } 19372 return; 19373 } 19374 } 19375 19376 if (existing != null) { 19377 if (DEBUG_PREFERRED) { 19378 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19379 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19380 } 19381 for (int i = 0; i < existing.size(); i++) { 19382 PreferredActivity pa = existing.get(i); 19383 if (DEBUG_PREFERRED) { 19384 Slog.i(TAG, "Removing existing preferred activity " 19385 + pa.mPref.mComponent + ":"); 19386 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19387 } 19388 pir.removeFilter(pa); 19389 } 19390 } 19391 } 19392 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19393 "Replacing preferred"); 19394 } 19395 } 19396 19397 @Override 19398 public void clearPackagePreferredActivities(String packageName) { 19399 final int callingUid = Binder.getCallingUid(); 19400 if (getInstantAppPackageName(callingUid) != null) { 19401 return; 19402 } 19403 // writer 19404 synchronized (mPackages) { 19405 PackageParser.Package pkg = mPackages.get(packageName); 19406 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19407 if (mContext.checkCallingOrSelfPermission( 19408 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19409 != PackageManager.PERMISSION_GRANTED) { 19410 if (getUidTargetSdkVersionLockedLPr(callingUid) 19411 < Build.VERSION_CODES.FROYO) { 19412 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19413 + callingUid); 19414 return; 19415 } 19416 mContext.enforceCallingOrSelfPermission( 19417 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19418 } 19419 } 19420 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19421 if (ps != null 19422 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19423 return; 19424 } 19425 int user = UserHandle.getCallingUserId(); 19426 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19427 scheduleWritePackageRestrictionsLocked(user); 19428 } 19429 } 19430 } 19431 19432 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19433 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19434 ArrayList<PreferredActivity> removed = null; 19435 boolean changed = false; 19436 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19437 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19438 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19439 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19440 continue; 19441 } 19442 Iterator<PreferredActivity> it = pir.filterIterator(); 19443 while (it.hasNext()) { 19444 PreferredActivity pa = it.next(); 19445 // Mark entry for removal only if it matches the package name 19446 // and the entry is of type "always". 19447 if (packageName == null || 19448 (pa.mPref.mComponent.getPackageName().equals(packageName) 19449 && pa.mPref.mAlways)) { 19450 if (removed == null) { 19451 removed = new ArrayList<PreferredActivity>(); 19452 } 19453 removed.add(pa); 19454 } 19455 } 19456 if (removed != null) { 19457 for (int j=0; j<removed.size(); j++) { 19458 PreferredActivity pa = removed.get(j); 19459 pir.removeFilter(pa); 19460 } 19461 changed = true; 19462 } 19463 } 19464 if (changed) { 19465 postPreferredActivityChangedBroadcast(userId); 19466 } 19467 return changed; 19468 } 19469 19470 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19471 private void clearIntentFilterVerificationsLPw(int userId) { 19472 final int packageCount = mPackages.size(); 19473 for (int i = 0; i < packageCount; i++) { 19474 PackageParser.Package pkg = mPackages.valueAt(i); 19475 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19476 } 19477 } 19478 19479 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19480 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19481 if (userId == UserHandle.USER_ALL) { 19482 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19483 sUserManager.getUserIds())) { 19484 for (int oneUserId : sUserManager.getUserIds()) { 19485 scheduleWritePackageRestrictionsLocked(oneUserId); 19486 } 19487 } 19488 } else { 19489 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19490 scheduleWritePackageRestrictionsLocked(userId); 19491 } 19492 } 19493 } 19494 19495 /** Clears state for all users, and touches intent filter verification policy */ 19496 void clearDefaultBrowserIfNeeded(String packageName) { 19497 for (int oneUserId : sUserManager.getUserIds()) { 19498 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19499 } 19500 } 19501 19502 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19503 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19504 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19505 if (packageName.equals(defaultBrowserPackageName)) { 19506 setDefaultBrowserPackageName(null, userId); 19507 } 19508 } 19509 } 19510 19511 @Override 19512 public void resetApplicationPreferences(int userId) { 19513 mContext.enforceCallingOrSelfPermission( 19514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19515 final long identity = Binder.clearCallingIdentity(); 19516 // writer 19517 try { 19518 synchronized (mPackages) { 19519 clearPackagePreferredActivitiesLPw(null, userId); 19520 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19521 // TODO: We have to reset the default SMS and Phone. This requires 19522 // significant refactoring to keep all default apps in the package 19523 // manager (cleaner but more work) or have the services provide 19524 // callbacks to the package manager to request a default app reset. 19525 applyFactoryDefaultBrowserLPw(userId); 19526 clearIntentFilterVerificationsLPw(userId); 19527 primeDomainVerificationsLPw(userId); 19528 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19529 scheduleWritePackageRestrictionsLocked(userId); 19530 } 19531 resetNetworkPolicies(userId); 19532 } finally { 19533 Binder.restoreCallingIdentity(identity); 19534 } 19535 } 19536 19537 @Override 19538 public int getPreferredActivities(List<IntentFilter> outFilters, 19539 List<ComponentName> outActivities, String packageName) { 19540 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19541 return 0; 19542 } 19543 int num = 0; 19544 final int userId = UserHandle.getCallingUserId(); 19545 // reader 19546 synchronized (mPackages) { 19547 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19548 if (pir != null) { 19549 final Iterator<PreferredActivity> it = pir.filterIterator(); 19550 while (it.hasNext()) { 19551 final PreferredActivity pa = it.next(); 19552 if (packageName == null 19553 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19554 && pa.mPref.mAlways)) { 19555 if (outFilters != null) { 19556 outFilters.add(new IntentFilter(pa)); 19557 } 19558 if (outActivities != null) { 19559 outActivities.add(pa.mPref.mComponent); 19560 } 19561 } 19562 } 19563 } 19564 } 19565 19566 return num; 19567 } 19568 19569 @Override 19570 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19571 int userId) { 19572 int callingUid = Binder.getCallingUid(); 19573 if (callingUid != Process.SYSTEM_UID) { 19574 throw new SecurityException( 19575 "addPersistentPreferredActivity can only be run by the system"); 19576 } 19577 if (filter.countActions() == 0) { 19578 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19579 return; 19580 } 19581 synchronized (mPackages) { 19582 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19583 ":"); 19584 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19585 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19586 new PersistentPreferredActivity(filter, activity)); 19587 scheduleWritePackageRestrictionsLocked(userId); 19588 postPreferredActivityChangedBroadcast(userId); 19589 } 19590 } 19591 19592 @Override 19593 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19594 int callingUid = Binder.getCallingUid(); 19595 if (callingUid != Process.SYSTEM_UID) { 19596 throw new SecurityException( 19597 "clearPackagePersistentPreferredActivities can only be run by the system"); 19598 } 19599 ArrayList<PersistentPreferredActivity> removed = null; 19600 boolean changed = false; 19601 synchronized (mPackages) { 19602 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19603 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19604 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19605 .valueAt(i); 19606 if (userId != thisUserId) { 19607 continue; 19608 } 19609 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19610 while (it.hasNext()) { 19611 PersistentPreferredActivity ppa = it.next(); 19612 // Mark entry for removal only if it matches the package name. 19613 if (ppa.mComponent.getPackageName().equals(packageName)) { 19614 if (removed == null) { 19615 removed = new ArrayList<PersistentPreferredActivity>(); 19616 } 19617 removed.add(ppa); 19618 } 19619 } 19620 if (removed != null) { 19621 for (int j=0; j<removed.size(); j++) { 19622 PersistentPreferredActivity ppa = removed.get(j); 19623 ppir.removeFilter(ppa); 19624 } 19625 changed = true; 19626 } 19627 } 19628 19629 if (changed) { 19630 scheduleWritePackageRestrictionsLocked(userId); 19631 postPreferredActivityChangedBroadcast(userId); 19632 } 19633 } 19634 } 19635 19636 /** 19637 * Common machinery for picking apart a restored XML blob and passing 19638 * it to a caller-supplied functor to be applied to the running system. 19639 */ 19640 private void restoreFromXml(XmlPullParser parser, int userId, 19641 String expectedStartTag, BlobXmlRestorer functor) 19642 throws IOException, XmlPullParserException { 19643 int type; 19644 while ((type = parser.next()) != XmlPullParser.START_TAG 19645 && type != XmlPullParser.END_DOCUMENT) { 19646 } 19647 if (type != XmlPullParser.START_TAG) { 19648 // oops didn't find a start tag?! 19649 if (DEBUG_BACKUP) { 19650 Slog.e(TAG, "Didn't find start tag during restore"); 19651 } 19652 return; 19653 } 19654Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19655 // this is supposed to be TAG_PREFERRED_BACKUP 19656 if (!expectedStartTag.equals(parser.getName())) { 19657 if (DEBUG_BACKUP) { 19658 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19659 } 19660 return; 19661 } 19662 19663 // skip interfering stuff, then we're aligned with the backing implementation 19664 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19665Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19666 functor.apply(parser, userId); 19667 } 19668 19669 private interface BlobXmlRestorer { 19670 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19671 } 19672 19673 /** 19674 * Non-Binder method, support for the backup/restore mechanism: write the 19675 * full set of preferred activities in its canonical XML format. Returns the 19676 * XML output as a byte array, or null if there is none. 19677 */ 19678 @Override 19679 public byte[] getPreferredActivityBackup(int userId) { 19680 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19681 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19682 } 19683 19684 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19685 try { 19686 final XmlSerializer serializer = new FastXmlSerializer(); 19687 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19688 serializer.startDocument(null, true); 19689 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19690 19691 synchronized (mPackages) { 19692 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19693 } 19694 19695 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19696 serializer.endDocument(); 19697 serializer.flush(); 19698 } catch (Exception e) { 19699 if (DEBUG_BACKUP) { 19700 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19701 } 19702 return null; 19703 } 19704 19705 return dataStream.toByteArray(); 19706 } 19707 19708 @Override 19709 public void restorePreferredActivities(byte[] backup, int userId) { 19710 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19711 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19712 } 19713 19714 try { 19715 final XmlPullParser parser = Xml.newPullParser(); 19716 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19717 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19718 new BlobXmlRestorer() { 19719 @Override 19720 public void apply(XmlPullParser parser, int userId) 19721 throws XmlPullParserException, IOException { 19722 synchronized (mPackages) { 19723 mSettings.readPreferredActivitiesLPw(parser, userId); 19724 } 19725 } 19726 } ); 19727 } catch (Exception e) { 19728 if (DEBUG_BACKUP) { 19729 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19730 } 19731 } 19732 } 19733 19734 /** 19735 * Non-Binder method, support for the backup/restore mechanism: write the 19736 * default browser (etc) settings in its canonical XML format. Returns the default 19737 * browser XML representation as a byte array, or null if there is none. 19738 */ 19739 @Override 19740 public byte[] getDefaultAppsBackup(int userId) { 19741 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19742 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19743 } 19744 19745 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19746 try { 19747 final XmlSerializer serializer = new FastXmlSerializer(); 19748 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19749 serializer.startDocument(null, true); 19750 serializer.startTag(null, TAG_DEFAULT_APPS); 19751 19752 synchronized (mPackages) { 19753 mSettings.writeDefaultAppsLPr(serializer, userId); 19754 } 19755 19756 serializer.endTag(null, TAG_DEFAULT_APPS); 19757 serializer.endDocument(); 19758 serializer.flush(); 19759 } catch (Exception e) { 19760 if (DEBUG_BACKUP) { 19761 Slog.e(TAG, "Unable to write default apps for backup", e); 19762 } 19763 return null; 19764 } 19765 19766 return dataStream.toByteArray(); 19767 } 19768 19769 @Override 19770 public void restoreDefaultApps(byte[] backup, int userId) { 19771 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19772 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19773 } 19774 19775 try { 19776 final XmlPullParser parser = Xml.newPullParser(); 19777 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19778 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19779 new BlobXmlRestorer() { 19780 @Override 19781 public void apply(XmlPullParser parser, int userId) 19782 throws XmlPullParserException, IOException { 19783 synchronized (mPackages) { 19784 mSettings.readDefaultAppsLPw(parser, userId); 19785 } 19786 } 19787 } ); 19788 } catch (Exception e) { 19789 if (DEBUG_BACKUP) { 19790 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19791 } 19792 } 19793 } 19794 19795 @Override 19796 public byte[] getIntentFilterVerificationBackup(int userId) { 19797 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19798 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19799 } 19800 19801 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19802 try { 19803 final XmlSerializer serializer = new FastXmlSerializer(); 19804 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19805 serializer.startDocument(null, true); 19806 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19807 19808 synchronized (mPackages) { 19809 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19810 } 19811 19812 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19813 serializer.endDocument(); 19814 serializer.flush(); 19815 } catch (Exception e) { 19816 if (DEBUG_BACKUP) { 19817 Slog.e(TAG, "Unable to write default apps for backup", e); 19818 } 19819 return null; 19820 } 19821 19822 return dataStream.toByteArray(); 19823 } 19824 19825 @Override 19826 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19827 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19828 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19829 } 19830 19831 try { 19832 final XmlPullParser parser = Xml.newPullParser(); 19833 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19834 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19835 new BlobXmlRestorer() { 19836 @Override 19837 public void apply(XmlPullParser parser, int userId) 19838 throws XmlPullParserException, IOException { 19839 synchronized (mPackages) { 19840 mSettings.readAllDomainVerificationsLPr(parser, userId); 19841 mSettings.writeLPr(); 19842 } 19843 } 19844 } ); 19845 } catch (Exception e) { 19846 if (DEBUG_BACKUP) { 19847 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19848 } 19849 } 19850 } 19851 19852 @Override 19853 public byte[] getPermissionGrantBackup(int userId) { 19854 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19855 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19856 } 19857 19858 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19859 try { 19860 final XmlSerializer serializer = new FastXmlSerializer(); 19861 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19862 serializer.startDocument(null, true); 19863 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19864 19865 synchronized (mPackages) { 19866 serializeRuntimePermissionGrantsLPr(serializer, userId); 19867 } 19868 19869 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19870 serializer.endDocument(); 19871 serializer.flush(); 19872 } catch (Exception e) { 19873 if (DEBUG_BACKUP) { 19874 Slog.e(TAG, "Unable to write default apps for backup", e); 19875 } 19876 return null; 19877 } 19878 19879 return dataStream.toByteArray(); 19880 } 19881 19882 @Override 19883 public void restorePermissionGrants(byte[] backup, int userId) { 19884 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19885 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19886 } 19887 19888 try { 19889 final XmlPullParser parser = Xml.newPullParser(); 19890 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19891 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19892 new BlobXmlRestorer() { 19893 @Override 19894 public void apply(XmlPullParser parser, int userId) 19895 throws XmlPullParserException, IOException { 19896 synchronized (mPackages) { 19897 processRestoredPermissionGrantsLPr(parser, userId); 19898 } 19899 } 19900 } ); 19901 } catch (Exception e) { 19902 if (DEBUG_BACKUP) { 19903 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19904 } 19905 } 19906 } 19907 19908 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19909 throws IOException { 19910 serializer.startTag(null, TAG_ALL_GRANTS); 19911 19912 final int N = mSettings.mPackages.size(); 19913 for (int i = 0; i < N; i++) { 19914 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19915 boolean pkgGrantsKnown = false; 19916 19917 PermissionsState packagePerms = ps.getPermissionsState(); 19918 19919 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19920 final int grantFlags = state.getFlags(); 19921 // only look at grants that are not system/policy fixed 19922 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19923 final boolean isGranted = state.isGranted(); 19924 // And only back up the user-twiddled state bits 19925 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19926 final String packageName = mSettings.mPackages.keyAt(i); 19927 if (!pkgGrantsKnown) { 19928 serializer.startTag(null, TAG_GRANT); 19929 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19930 pkgGrantsKnown = true; 19931 } 19932 19933 final boolean userSet = 19934 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19935 final boolean userFixed = 19936 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19937 final boolean revoke = 19938 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19939 19940 serializer.startTag(null, TAG_PERMISSION); 19941 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19942 if (isGranted) { 19943 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19944 } 19945 if (userSet) { 19946 serializer.attribute(null, ATTR_USER_SET, "true"); 19947 } 19948 if (userFixed) { 19949 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19950 } 19951 if (revoke) { 19952 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19953 } 19954 serializer.endTag(null, TAG_PERMISSION); 19955 } 19956 } 19957 } 19958 19959 if (pkgGrantsKnown) { 19960 serializer.endTag(null, TAG_GRANT); 19961 } 19962 } 19963 19964 serializer.endTag(null, TAG_ALL_GRANTS); 19965 } 19966 19967 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19968 throws XmlPullParserException, IOException { 19969 String pkgName = null; 19970 int outerDepth = parser.getDepth(); 19971 int type; 19972 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19973 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19974 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19975 continue; 19976 } 19977 19978 final String tagName = parser.getName(); 19979 if (tagName.equals(TAG_GRANT)) { 19980 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19981 if (DEBUG_BACKUP) { 19982 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19983 } 19984 } else if (tagName.equals(TAG_PERMISSION)) { 19985 19986 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19987 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19988 19989 int newFlagSet = 0; 19990 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19991 newFlagSet |= FLAG_PERMISSION_USER_SET; 19992 } 19993 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19994 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19995 } 19996 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19997 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19998 } 19999 if (DEBUG_BACKUP) { 20000 Slog.v(TAG, " + Restoring grant:" 20001 + " pkg=" + pkgName 20002 + " perm=" + permName 20003 + " granted=" + isGranted 20004 + " bits=0x" + Integer.toHexString(newFlagSet)); 20005 } 20006 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20007 if (ps != null) { 20008 // Already installed so we apply the grant immediately 20009 if (DEBUG_BACKUP) { 20010 Slog.v(TAG, " + already installed; applying"); 20011 } 20012 PermissionsState perms = ps.getPermissionsState(); 20013 BasePermission bp = 20014 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20015 if (bp != null) { 20016 if (isGranted) { 20017 perms.grantRuntimePermission(bp, userId); 20018 } 20019 if (newFlagSet != 0) { 20020 perms.updatePermissionFlags( 20021 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20022 } 20023 } 20024 } else { 20025 // Need to wait for post-restore install to apply the grant 20026 if (DEBUG_BACKUP) { 20027 Slog.v(TAG, " - not yet installed; saving for later"); 20028 } 20029 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20030 isGranted, newFlagSet, userId); 20031 } 20032 } else { 20033 PackageManagerService.reportSettingsProblem(Log.WARN, 20034 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20035 XmlUtils.skipCurrentTag(parser); 20036 } 20037 } 20038 20039 scheduleWriteSettingsLocked(); 20040 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20041 } 20042 20043 @Override 20044 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20045 int sourceUserId, int targetUserId, int flags) { 20046 mContext.enforceCallingOrSelfPermission( 20047 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20048 int callingUid = Binder.getCallingUid(); 20049 enforceOwnerRights(ownerPackage, callingUid); 20050 PackageManagerServiceUtils.enforceShellRestriction( 20051 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20052 if (intentFilter.countActions() == 0) { 20053 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20054 return; 20055 } 20056 synchronized (mPackages) { 20057 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20058 ownerPackage, targetUserId, flags); 20059 CrossProfileIntentResolver resolver = 20060 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20061 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20062 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20063 if (existing != null) { 20064 int size = existing.size(); 20065 for (int i = 0; i < size; i++) { 20066 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20067 return; 20068 } 20069 } 20070 } 20071 resolver.addFilter(newFilter); 20072 scheduleWritePackageRestrictionsLocked(sourceUserId); 20073 } 20074 } 20075 20076 @Override 20077 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20078 mContext.enforceCallingOrSelfPermission( 20079 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20080 final int callingUid = Binder.getCallingUid(); 20081 enforceOwnerRights(ownerPackage, callingUid); 20082 PackageManagerServiceUtils.enforceShellRestriction( 20083 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20084 synchronized (mPackages) { 20085 CrossProfileIntentResolver resolver = 20086 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20087 ArraySet<CrossProfileIntentFilter> set = 20088 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20089 for (CrossProfileIntentFilter filter : set) { 20090 if (filter.getOwnerPackage().equals(ownerPackage)) { 20091 resolver.removeFilter(filter); 20092 } 20093 } 20094 scheduleWritePackageRestrictionsLocked(sourceUserId); 20095 } 20096 } 20097 20098 // Enforcing that callingUid is owning pkg on userId 20099 private void enforceOwnerRights(String pkg, int callingUid) { 20100 // The system owns everything. 20101 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20102 return; 20103 } 20104 final int callingUserId = UserHandle.getUserId(callingUid); 20105 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20106 if (pi == null) { 20107 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20108 + callingUserId); 20109 } 20110 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20111 throw new SecurityException("Calling uid " + callingUid 20112 + " does not own package " + pkg); 20113 } 20114 } 20115 20116 @Override 20117 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20118 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20119 return null; 20120 } 20121 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20122 } 20123 20124 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20125 UserManagerService ums = UserManagerService.getInstance(); 20126 if (ums != null) { 20127 final UserInfo parent = ums.getProfileParent(userId); 20128 final int launcherUid = (parent != null) ? parent.id : userId; 20129 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20130 if (launcherComponent != null) { 20131 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20132 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20133 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20134 .setPackage(launcherComponent.getPackageName()); 20135 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20136 } 20137 } 20138 } 20139 20140 /** 20141 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20142 * then reports the most likely home activity or null if there are more than one. 20143 */ 20144 private ComponentName getDefaultHomeActivity(int userId) { 20145 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20146 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20147 if (cn != null) { 20148 return cn; 20149 } 20150 20151 // Find the launcher with the highest priority and return that component if there are no 20152 // other home activity with the same priority. 20153 int lastPriority = Integer.MIN_VALUE; 20154 ComponentName lastComponent = null; 20155 final int size = allHomeCandidates.size(); 20156 for (int i = 0; i < size; i++) { 20157 final ResolveInfo ri = allHomeCandidates.get(i); 20158 if (ri.priority > lastPriority) { 20159 lastComponent = ri.activityInfo.getComponentName(); 20160 lastPriority = ri.priority; 20161 } else if (ri.priority == lastPriority) { 20162 // Two components found with same priority. 20163 lastComponent = null; 20164 } 20165 } 20166 return lastComponent; 20167 } 20168 20169 private Intent getHomeIntent() { 20170 Intent intent = new Intent(Intent.ACTION_MAIN); 20171 intent.addCategory(Intent.CATEGORY_HOME); 20172 intent.addCategory(Intent.CATEGORY_DEFAULT); 20173 return intent; 20174 } 20175 20176 private IntentFilter getHomeFilter() { 20177 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20178 filter.addCategory(Intent.CATEGORY_HOME); 20179 filter.addCategory(Intent.CATEGORY_DEFAULT); 20180 return filter; 20181 } 20182 20183 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20184 int userId) { 20185 Intent intent = getHomeIntent(); 20186 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20187 PackageManager.GET_META_DATA, userId); 20188 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20189 true, false, false, userId); 20190 20191 allHomeCandidates.clear(); 20192 if (list != null) { 20193 for (ResolveInfo ri : list) { 20194 allHomeCandidates.add(ri); 20195 } 20196 } 20197 return (preferred == null || preferred.activityInfo == null) 20198 ? null 20199 : new ComponentName(preferred.activityInfo.packageName, 20200 preferred.activityInfo.name); 20201 } 20202 20203 @Override 20204 public void setHomeActivity(ComponentName comp, int userId) { 20205 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20206 return; 20207 } 20208 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20209 getHomeActivitiesAsUser(homeActivities, userId); 20210 20211 boolean found = false; 20212 20213 final int size = homeActivities.size(); 20214 final ComponentName[] set = new ComponentName[size]; 20215 for (int i = 0; i < size; i++) { 20216 final ResolveInfo candidate = homeActivities.get(i); 20217 final ActivityInfo info = candidate.activityInfo; 20218 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20219 set[i] = activityName; 20220 if (!found && activityName.equals(comp)) { 20221 found = true; 20222 } 20223 } 20224 if (!found) { 20225 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20226 + userId); 20227 } 20228 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20229 set, comp, userId); 20230 } 20231 20232 private @Nullable String getSetupWizardPackageName() { 20233 final Intent intent = new Intent(Intent.ACTION_MAIN); 20234 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20235 20236 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20237 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20238 | MATCH_DISABLED_COMPONENTS, 20239 UserHandle.myUserId()); 20240 if (matches.size() == 1) { 20241 return matches.get(0).getComponentInfo().packageName; 20242 } else { 20243 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20244 + ": matches=" + matches); 20245 return null; 20246 } 20247 } 20248 20249 private @Nullable String getStorageManagerPackageName() { 20250 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 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 storage manager; found " 20260 + matches.size() + ": matches=" + matches); 20261 return null; 20262 } 20263 } 20264 20265 @Override 20266 public void setApplicationEnabledSetting(String appPackageName, 20267 int newState, int flags, int userId, String callingPackage) { 20268 if (!sUserManager.exists(userId)) return; 20269 if (callingPackage == null) { 20270 callingPackage = Integer.toString(Binder.getCallingUid()); 20271 } 20272 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20273 } 20274 20275 @Override 20276 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20277 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20278 synchronized (mPackages) { 20279 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20280 if (pkgSetting != null) { 20281 pkgSetting.setUpdateAvailable(updateAvailable); 20282 } 20283 } 20284 } 20285 20286 @Override 20287 public void setComponentEnabledSetting(ComponentName componentName, 20288 int newState, int flags, int userId) { 20289 if (!sUserManager.exists(userId)) return; 20290 setEnabledSetting(componentName.getPackageName(), 20291 componentName.getClassName(), newState, flags, userId, null); 20292 } 20293 20294 private void setEnabledSetting(final String packageName, String className, int newState, 20295 final int flags, int userId, String callingPackage) { 20296 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20297 || newState == COMPONENT_ENABLED_STATE_ENABLED 20298 || newState == COMPONENT_ENABLED_STATE_DISABLED 20299 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20300 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20301 throw new IllegalArgumentException("Invalid new component state: " 20302 + newState); 20303 } 20304 PackageSetting pkgSetting; 20305 final int callingUid = Binder.getCallingUid(); 20306 final int permission; 20307 if (callingUid == Process.SYSTEM_UID) { 20308 permission = PackageManager.PERMISSION_GRANTED; 20309 } else { 20310 permission = mContext.checkCallingOrSelfPermission( 20311 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20312 } 20313 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20314 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20315 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20316 boolean sendNow = false; 20317 boolean isApp = (className == null); 20318 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20319 String componentName = isApp ? packageName : className; 20320 int packageUid = -1; 20321 ArrayList<String> components; 20322 20323 // reader 20324 synchronized (mPackages) { 20325 pkgSetting = mSettings.mPackages.get(packageName); 20326 if (pkgSetting == null) { 20327 if (!isCallerInstantApp) { 20328 if (className == null) { 20329 throw new IllegalArgumentException("Unknown package: " + packageName); 20330 } 20331 throw new IllegalArgumentException( 20332 "Unknown component: " + packageName + "/" + className); 20333 } else { 20334 // throw SecurityException to prevent leaking package information 20335 throw new SecurityException( 20336 "Attempt to change component state; " 20337 + "pid=" + Binder.getCallingPid() 20338 + ", uid=" + callingUid 20339 + (className == null 20340 ? ", package=" + packageName 20341 : ", component=" + packageName + "/" + className)); 20342 } 20343 } 20344 } 20345 20346 // Limit who can change which apps 20347 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20348 // Don't allow apps that don't have permission to modify other apps 20349 if (!allowedByPermission 20350 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 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 // Don't allow changing protected packages. 20360 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20361 throw new SecurityException("Cannot disable a protected package: " + packageName); 20362 } 20363 } 20364 20365 synchronized (mPackages) { 20366 if (callingUid == Process.SHELL_UID 20367 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20368 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20369 // unless it is a test package. 20370 int oldState = pkgSetting.getEnabled(userId); 20371 if (className == null 20372 && 20373 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20374 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20375 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20376 && 20377 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20378 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20379 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20380 // ok 20381 } else { 20382 throw new SecurityException( 20383 "Shell cannot change component state for " + packageName + "/" 20384 + className + " to " + newState); 20385 } 20386 } 20387 } 20388 if (className == null) { 20389 // We're dealing with an application/package level state change 20390 synchronized (mPackages) { 20391 if (pkgSetting.getEnabled(userId) == newState) { 20392 // Nothing to do 20393 return; 20394 } 20395 } 20396 // If we're enabling a system stub, there's a little more work to do. 20397 // Prior to enabling the package, we need to decompress the APK(s) to the 20398 // data partition and then replace the version on the system partition. 20399 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20400 final boolean isSystemStub = deletedPkg.isStub 20401 && deletedPkg.isSystem(); 20402 if (isSystemStub 20403 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20404 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20405 final File codePath = decompressPackage(deletedPkg); 20406 if (codePath == null) { 20407 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20408 return; 20409 } 20410 // TODO remove direct parsing of the package object during internal cleanup 20411 // of scan package 20412 // We need to call parse directly here for no other reason than we need 20413 // the new package in order to disable the old one [we use the information 20414 // for some internal optimization to optionally create a new package setting 20415 // object on replace]. However, we can't get the package from the scan 20416 // because the scan modifies live structures and we need to remove the 20417 // old [system] package from the system before a scan can be attempted. 20418 // Once scan is indempotent we can remove this parse and use the package 20419 // object we scanned, prior to adding it to package settings. 20420 final PackageParser pp = new PackageParser(); 20421 pp.setSeparateProcesses(mSeparateProcesses); 20422 pp.setDisplayMetrics(mMetrics); 20423 pp.setCallback(mPackageParserCallback); 20424 final PackageParser.Package tmpPkg; 20425 try { 20426 final @ParseFlags int parseFlags = mDefParseFlags 20427 | PackageParser.PARSE_MUST_BE_APK 20428 | PackageParser.PARSE_IS_SYSTEM_DIR; 20429 tmpPkg = pp.parsePackage(codePath, parseFlags); 20430 } catch (PackageParserException e) { 20431 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20432 return; 20433 } 20434 synchronized (mInstallLock) { 20435 // Disable the stub and remove any package entries 20436 removePackageLI(deletedPkg, true); 20437 synchronized (mPackages) { 20438 disableSystemPackageLPw(deletedPkg, tmpPkg); 20439 } 20440 final PackageParser.Package pkg; 20441 try (PackageFreezer freezer = 20442 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20443 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20444 | PackageParser.PARSE_ENFORCE_CODE; 20445 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20446 0 /*currentTime*/, null /*user*/); 20447 prepareAppDataAfterInstallLIF(pkg); 20448 synchronized (mPackages) { 20449 try { 20450 updateSharedLibrariesLPr(pkg, null); 20451 } catch (PackageManagerException e) { 20452 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20453 } 20454 mPermissionManager.updatePermissions( 20455 pkg.packageName, pkg, true, mPackages.values(), 20456 mPermissionCallback); 20457 mSettings.writeLPr(); 20458 } 20459 } catch (PackageManagerException e) { 20460 // Whoops! Something went wrong; try to roll back to the stub 20461 Slog.w(TAG, "Failed to install compressed system package:" 20462 + pkgSetting.name, e); 20463 // Remove the failed install 20464 removeCodePathLI(codePath); 20465 20466 // Install the system package 20467 try (PackageFreezer freezer = 20468 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20469 synchronized (mPackages) { 20470 // NOTE: The system package always needs to be enabled; even 20471 // if it's for a compressed stub. If we don't, installing the 20472 // system package fails during scan [scanning checks the disabled 20473 // packages]. We will reverse this later, after we've "installed" 20474 // the stub. 20475 // This leaves us in a fragile state; the stub should never be 20476 // enabled, so, cross your fingers and hope nothing goes wrong 20477 // until we can disable the package later. 20478 enableSystemPackageLPw(deletedPkg); 20479 } 20480 installPackageFromSystemLIF(deletedPkg.codePath, 20481 false /*isPrivileged*/, null /*allUserHandles*/, 20482 null /*origUserHandles*/, null /*origPermissionsState*/, 20483 true /*writeSettings*/); 20484 } catch (PackageManagerException pme) { 20485 Slog.w(TAG, "Failed to restore system package:" 20486 + deletedPkg.packageName, pme); 20487 } finally { 20488 synchronized (mPackages) { 20489 mSettings.disableSystemPackageLPw( 20490 deletedPkg.packageName, true /*replaced*/); 20491 mSettings.writeLPr(); 20492 } 20493 } 20494 return; 20495 } 20496 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20497 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20498 mDexManager.notifyPackageUpdated(pkg.packageName, 20499 pkg.baseCodePath, pkg.splitCodePaths); 20500 } 20501 } 20502 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20503 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20504 // Don't care about who enables an app. 20505 callingPackage = null; 20506 } 20507 synchronized (mPackages) { 20508 pkgSetting.setEnabled(newState, userId, callingPackage); 20509 } 20510 } else { 20511 synchronized (mPackages) { 20512 // We're dealing with a component level state change 20513 // First, verify that this is a valid class name. 20514 PackageParser.Package pkg = pkgSetting.pkg; 20515 if (pkg == null || !pkg.hasComponentClassName(className)) { 20516 if (pkg != null && 20517 pkg.applicationInfo.targetSdkVersion >= 20518 Build.VERSION_CODES.JELLY_BEAN) { 20519 throw new IllegalArgumentException("Component class " + className 20520 + " does not exist in " + packageName); 20521 } else { 20522 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20523 + className + " does not exist in " + packageName); 20524 } 20525 } 20526 switch (newState) { 20527 case COMPONENT_ENABLED_STATE_ENABLED: 20528 if (!pkgSetting.enableComponentLPw(className, userId)) { 20529 return; 20530 } 20531 break; 20532 case COMPONENT_ENABLED_STATE_DISABLED: 20533 if (!pkgSetting.disableComponentLPw(className, userId)) { 20534 return; 20535 } 20536 break; 20537 case COMPONENT_ENABLED_STATE_DEFAULT: 20538 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20539 return; 20540 } 20541 break; 20542 default: 20543 Slog.e(TAG, "Invalid new component state: " + newState); 20544 return; 20545 } 20546 } 20547 } 20548 synchronized (mPackages) { 20549 scheduleWritePackageRestrictionsLocked(userId); 20550 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20551 final long callingId = Binder.clearCallingIdentity(); 20552 try { 20553 updateInstantAppInstallerLocked(packageName); 20554 } finally { 20555 Binder.restoreCallingIdentity(callingId); 20556 } 20557 components = mPendingBroadcasts.get(userId, packageName); 20558 final boolean newPackage = components == null; 20559 if (newPackage) { 20560 components = new ArrayList<String>(); 20561 } 20562 if (!components.contains(componentName)) { 20563 components.add(componentName); 20564 } 20565 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20566 sendNow = true; 20567 // Purge entry from pending broadcast list if another one exists already 20568 // since we are sending one right away. 20569 mPendingBroadcasts.remove(userId, packageName); 20570 } else { 20571 if (newPackage) { 20572 mPendingBroadcasts.put(userId, packageName, components); 20573 } 20574 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20575 // Schedule a message 20576 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20577 } 20578 } 20579 } 20580 20581 long callingId = Binder.clearCallingIdentity(); 20582 try { 20583 if (sendNow) { 20584 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20585 sendPackageChangedBroadcast(packageName, 20586 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20587 } 20588 } finally { 20589 Binder.restoreCallingIdentity(callingId); 20590 } 20591 } 20592 20593 @Override 20594 public void flushPackageRestrictionsAsUser(int userId) { 20595 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20596 return; 20597 } 20598 if (!sUserManager.exists(userId)) { 20599 return; 20600 } 20601 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20602 false /* checkShell */, "flushPackageRestrictions"); 20603 synchronized (mPackages) { 20604 mSettings.writePackageRestrictionsLPr(userId); 20605 mDirtyUsers.remove(userId); 20606 if (mDirtyUsers.isEmpty()) { 20607 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20608 } 20609 } 20610 } 20611 20612 private void sendPackageChangedBroadcast(String packageName, 20613 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20614 if (DEBUG_INSTALL) 20615 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20616 + componentNames); 20617 Bundle extras = new Bundle(4); 20618 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20619 String nameList[] = new String[componentNames.size()]; 20620 componentNames.toArray(nameList); 20621 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20622 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20623 extras.putInt(Intent.EXTRA_UID, packageUid); 20624 // If this is not reporting a change of the overall package, then only send it 20625 // to registered receivers. We don't want to launch a swath of apps for every 20626 // little component state change. 20627 final int flags = !componentNames.contains(packageName) 20628 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20629 final int userId = UserHandle.getUserId(packageUid); 20630 final boolean isInstantApp = isInstantApp(packageName, userId); 20631 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20632 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20633 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20634 userIds, instantUserIds); 20635 } 20636 20637 @Override 20638 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20639 if (!sUserManager.exists(userId)) return; 20640 final int callingUid = Binder.getCallingUid(); 20641 if (getInstantAppPackageName(callingUid) != null) { 20642 return; 20643 } 20644 final int permission = mContext.checkCallingOrSelfPermission( 20645 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20646 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20647 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20648 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20649 // writer 20650 synchronized (mPackages) { 20651 final PackageSetting ps = mSettings.mPackages.get(packageName); 20652 if (!filterAppAccessLPr(ps, callingUid, userId) 20653 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20654 allowedByPermission, callingUid, userId)) { 20655 scheduleWritePackageRestrictionsLocked(userId); 20656 } 20657 } 20658 } 20659 20660 @Override 20661 public String getInstallerPackageName(String packageName) { 20662 final int callingUid = Binder.getCallingUid(); 20663 if (getInstantAppPackageName(callingUid) != null) { 20664 return null; 20665 } 20666 // reader 20667 synchronized (mPackages) { 20668 final PackageSetting ps = mSettings.mPackages.get(packageName); 20669 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20670 return null; 20671 } 20672 return mSettings.getInstallerPackageNameLPr(packageName); 20673 } 20674 } 20675 20676 public boolean isOrphaned(String packageName) { 20677 // reader 20678 synchronized (mPackages) { 20679 return mSettings.isOrphaned(packageName); 20680 } 20681 } 20682 20683 @Override 20684 public int getApplicationEnabledSetting(String packageName, int userId) { 20685 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20686 int callingUid = Binder.getCallingUid(); 20687 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20688 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20689 // reader 20690 synchronized (mPackages) { 20691 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20692 return COMPONENT_ENABLED_STATE_DISABLED; 20693 } 20694 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20695 } 20696 } 20697 20698 @Override 20699 public int getComponentEnabledSetting(ComponentName component, int userId) { 20700 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20701 int callingUid = Binder.getCallingUid(); 20702 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20703 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20704 synchronized (mPackages) { 20705 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20706 component, TYPE_UNKNOWN, userId)) { 20707 return COMPONENT_ENABLED_STATE_DISABLED; 20708 } 20709 return mSettings.getComponentEnabledSettingLPr(component, userId); 20710 } 20711 } 20712 20713 @Override 20714 public void enterSafeMode() { 20715 enforceSystemOrRoot("Only the system can request entering safe mode"); 20716 20717 if (!mSystemReady) { 20718 mSafeMode = true; 20719 } 20720 } 20721 20722 @Override 20723 public void systemReady() { 20724 enforceSystemOrRoot("Only the system can claim the system is ready"); 20725 20726 mSystemReady = true; 20727 final ContentResolver resolver = mContext.getContentResolver(); 20728 ContentObserver co = new ContentObserver(mHandler) { 20729 @Override 20730 public void onChange(boolean selfChange) { 20731 mEphemeralAppsDisabled = 20732 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20733 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20734 } 20735 }; 20736 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20737 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20738 false, co, UserHandle.USER_SYSTEM); 20739 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20740 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20741 co.onChange(true); 20742 20743 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20744 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20745 // it is done. 20746 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20747 @Override 20748 public void onChange(boolean selfChange) { 20749 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20750 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20751 oobEnabled == 1 ? "true" : "false"); 20752 } 20753 }; 20754 mContext.getContentResolver().registerContentObserver( 20755 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20756 UserHandle.USER_SYSTEM); 20757 // At boot, restore the value from the setting, which persists across reboot. 20758 privAppOobObserver.onChange(true); 20759 20760 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20761 // disabled after already being started. 20762 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20763 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20764 20765 // Read the compatibilty setting when the system is ready. 20766 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20767 mContext.getContentResolver(), 20768 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20769 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20770 if (DEBUG_SETTINGS) { 20771 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20772 } 20773 20774 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20775 20776 synchronized (mPackages) { 20777 // Verify that all of the preferred activity components actually 20778 // exist. It is possible for applications to be updated and at 20779 // that point remove a previously declared activity component that 20780 // had been set as a preferred activity. We try to clean this up 20781 // the next time we encounter that preferred activity, but it is 20782 // possible for the user flow to never be able to return to that 20783 // situation so here we do a sanity check to make sure we haven't 20784 // left any junk around. 20785 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20786 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20787 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20788 removed.clear(); 20789 for (PreferredActivity pa : pir.filterSet()) { 20790 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20791 removed.add(pa); 20792 } 20793 } 20794 if (removed.size() > 0) { 20795 for (int r=0; r<removed.size(); r++) { 20796 PreferredActivity pa = removed.get(r); 20797 Slog.w(TAG, "Removing dangling preferred activity: " 20798 + pa.mPref.mComponent); 20799 pir.removeFilter(pa); 20800 } 20801 mSettings.writePackageRestrictionsLPr( 20802 mSettings.mPreferredActivities.keyAt(i)); 20803 } 20804 } 20805 20806 for (int userId : UserManagerService.getInstance().getUserIds()) { 20807 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20808 grantPermissionsUserIds = ArrayUtils.appendInt( 20809 grantPermissionsUserIds, userId); 20810 } 20811 } 20812 } 20813 sUserManager.systemReady(); 20814 // If we upgraded grant all default permissions before kicking off. 20815 for (int userId : grantPermissionsUserIds) { 20816 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20817 } 20818 20819 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20820 // If we did not grant default permissions, we preload from this the 20821 // default permission exceptions lazily to ensure we don't hit the 20822 // disk on a new user creation. 20823 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20824 } 20825 20826 // Now that we've scanned all packages, and granted any default 20827 // permissions, ensure permissions are updated. Beware of dragons if you 20828 // try optimizing this. 20829 synchronized (mPackages) { 20830 mPermissionManager.updateAllPermissions( 20831 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20832 mPermissionCallback); 20833 } 20834 20835 // Kick off any messages waiting for system ready 20836 if (mPostSystemReadyMessages != null) { 20837 for (Message msg : mPostSystemReadyMessages) { 20838 msg.sendToTarget(); 20839 } 20840 mPostSystemReadyMessages = null; 20841 } 20842 20843 // Watch for external volumes that come and go over time 20844 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20845 storage.registerListener(mStorageListener); 20846 20847 mInstallerService.systemReady(); 20848 mPackageDexOptimizer.systemReady(); 20849 20850 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20851 StorageManagerInternal.class); 20852 StorageManagerInternal.addExternalStoragePolicy( 20853 new StorageManagerInternal.ExternalStorageMountPolicy() { 20854 @Override 20855 public int getMountMode(int uid, String packageName) { 20856 if (Process.isIsolated(uid)) { 20857 return Zygote.MOUNT_EXTERNAL_NONE; 20858 } 20859 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20860 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20861 } 20862 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20863 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20864 } 20865 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20866 return Zygote.MOUNT_EXTERNAL_READ; 20867 } 20868 return Zygote.MOUNT_EXTERNAL_WRITE; 20869 } 20870 20871 @Override 20872 public boolean hasExternalStorage(int uid, String packageName) { 20873 return true; 20874 } 20875 }); 20876 20877 // Now that we're mostly running, clean up stale users and apps 20878 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20879 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20880 20881 mPermissionManager.systemReady(); 20882 } 20883 20884 public void waitForAppDataPrepared() { 20885 if (mPrepareAppDataFuture == null) { 20886 return; 20887 } 20888 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20889 mPrepareAppDataFuture = null; 20890 } 20891 20892 @Override 20893 public boolean isSafeMode() { 20894 // allow instant applications 20895 return mSafeMode; 20896 } 20897 20898 @Override 20899 public boolean hasSystemUidErrors() { 20900 // allow instant applications 20901 return mHasSystemUidErrors; 20902 } 20903 20904 static String arrayToString(int[] array) { 20905 StringBuffer buf = new StringBuffer(128); 20906 buf.append('['); 20907 if (array != null) { 20908 for (int i=0; i<array.length; i++) { 20909 if (i > 0) buf.append(", "); 20910 buf.append(array[i]); 20911 } 20912 } 20913 buf.append(']'); 20914 return buf.toString(); 20915 } 20916 20917 @Override 20918 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20919 FileDescriptor err, String[] args, ShellCallback callback, 20920 ResultReceiver resultReceiver) { 20921 (new PackageManagerShellCommand(this)).exec( 20922 this, in, out, err, args, callback, resultReceiver); 20923 } 20924 20925 @Override 20926 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20927 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20928 20929 DumpState dumpState = new DumpState(); 20930 boolean fullPreferred = false; 20931 boolean checkin = false; 20932 20933 String packageName = null; 20934 ArraySet<String> permissionNames = null; 20935 20936 int opti = 0; 20937 while (opti < args.length) { 20938 String opt = args[opti]; 20939 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20940 break; 20941 } 20942 opti++; 20943 20944 if ("-a".equals(opt)) { 20945 // Right now we only know how to print all. 20946 } else if ("-h".equals(opt)) { 20947 pw.println("Package manager dump options:"); 20948 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20949 pw.println(" --checkin: dump for a checkin"); 20950 pw.println(" -f: print details of intent filters"); 20951 pw.println(" -h: print this help"); 20952 pw.println(" cmd may be one of:"); 20953 pw.println(" l[ibraries]: list known shared libraries"); 20954 pw.println(" f[eatures]: list device features"); 20955 pw.println(" k[eysets]: print known keysets"); 20956 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20957 pw.println(" perm[issions]: dump permissions"); 20958 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20959 pw.println(" pref[erred]: print preferred package settings"); 20960 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20961 pw.println(" prov[iders]: dump content providers"); 20962 pw.println(" p[ackages]: dump installed packages"); 20963 pw.println(" s[hared-users]: dump shared user IDs"); 20964 pw.println(" m[essages]: print collected runtime messages"); 20965 pw.println(" v[erifiers]: print package verifier info"); 20966 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20967 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20968 pw.println(" version: print database version info"); 20969 pw.println(" write: write current settings now"); 20970 pw.println(" installs: details about install sessions"); 20971 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20972 pw.println(" dexopt: dump dexopt state"); 20973 pw.println(" compiler-stats: dump compiler statistics"); 20974 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20975 pw.println(" service-permissions: dump permissions required by services"); 20976 pw.println(" <package.name>: info about given package"); 20977 return; 20978 } else if ("--checkin".equals(opt)) { 20979 checkin = true; 20980 } else if ("-f".equals(opt)) { 20981 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20982 } else if ("--proto".equals(opt)) { 20983 dumpProto(fd); 20984 return; 20985 } else { 20986 pw.println("Unknown argument: " + opt + "; use -h for help"); 20987 } 20988 } 20989 20990 // Is the caller requesting to dump a particular piece of data? 20991 if (opti < args.length) { 20992 String cmd = args[opti]; 20993 opti++; 20994 // Is this a package name? 20995 if ("android".equals(cmd) || cmd.contains(".")) { 20996 packageName = cmd; 20997 // When dumping a single package, we always dump all of its 20998 // filter information since the amount of data will be reasonable. 20999 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21000 } else if ("check-permission".equals(cmd)) { 21001 if (opti >= args.length) { 21002 pw.println("Error: check-permission missing permission argument"); 21003 return; 21004 } 21005 String perm = args[opti]; 21006 opti++; 21007 if (opti >= args.length) { 21008 pw.println("Error: check-permission missing package argument"); 21009 return; 21010 } 21011 21012 String pkg = args[opti]; 21013 opti++; 21014 int user = UserHandle.getUserId(Binder.getCallingUid()); 21015 if (opti < args.length) { 21016 try { 21017 user = Integer.parseInt(args[opti]); 21018 } catch (NumberFormatException e) { 21019 pw.println("Error: check-permission user argument is not a number: " 21020 + args[opti]); 21021 return; 21022 } 21023 } 21024 21025 // Normalize package name to handle renamed packages and static libs 21026 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21027 21028 pw.println(checkPermission(perm, pkg, user)); 21029 return; 21030 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21031 dumpState.setDump(DumpState.DUMP_LIBS); 21032 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21033 dumpState.setDump(DumpState.DUMP_FEATURES); 21034 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21035 if (opti >= args.length) { 21036 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21037 | DumpState.DUMP_SERVICE_RESOLVERS 21038 | DumpState.DUMP_RECEIVER_RESOLVERS 21039 | DumpState.DUMP_CONTENT_RESOLVERS); 21040 } else { 21041 while (opti < args.length) { 21042 String name = args[opti]; 21043 if ("a".equals(name) || "activity".equals(name)) { 21044 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21045 } else if ("s".equals(name) || "service".equals(name)) { 21046 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21047 } else if ("r".equals(name) || "receiver".equals(name)) { 21048 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21049 } else if ("c".equals(name) || "content".equals(name)) { 21050 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21051 } else { 21052 pw.println("Error: unknown resolver table type: " + name); 21053 return; 21054 } 21055 opti++; 21056 } 21057 } 21058 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21059 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21060 } else if ("permission".equals(cmd)) { 21061 if (opti >= args.length) { 21062 pw.println("Error: permission requires permission name"); 21063 return; 21064 } 21065 permissionNames = new ArraySet<>(); 21066 while (opti < args.length) { 21067 permissionNames.add(args[opti]); 21068 opti++; 21069 } 21070 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21071 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21072 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21073 dumpState.setDump(DumpState.DUMP_PREFERRED); 21074 } else if ("preferred-xml".equals(cmd)) { 21075 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21076 if (opti < args.length && "--full".equals(args[opti])) { 21077 fullPreferred = true; 21078 opti++; 21079 } 21080 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21081 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21082 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21083 dumpState.setDump(DumpState.DUMP_PACKAGES); 21084 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21085 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21086 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21087 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21088 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21089 dumpState.setDump(DumpState.DUMP_MESSAGES); 21090 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21091 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21092 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21093 || "intent-filter-verifiers".equals(cmd)) { 21094 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21095 } else if ("version".equals(cmd)) { 21096 dumpState.setDump(DumpState.DUMP_VERSION); 21097 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21098 dumpState.setDump(DumpState.DUMP_KEYSETS); 21099 } else if ("installs".equals(cmd)) { 21100 dumpState.setDump(DumpState.DUMP_INSTALLS); 21101 } else if ("frozen".equals(cmd)) { 21102 dumpState.setDump(DumpState.DUMP_FROZEN); 21103 } else if ("volumes".equals(cmd)) { 21104 dumpState.setDump(DumpState.DUMP_VOLUMES); 21105 } else if ("dexopt".equals(cmd)) { 21106 dumpState.setDump(DumpState.DUMP_DEXOPT); 21107 } else if ("compiler-stats".equals(cmd)) { 21108 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21109 } else if ("changes".equals(cmd)) { 21110 dumpState.setDump(DumpState.DUMP_CHANGES); 21111 } else if ("service-permissions".equals(cmd)) { 21112 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21113 } else if ("write".equals(cmd)) { 21114 synchronized (mPackages) { 21115 mSettings.writeLPr(); 21116 pw.println("Settings written."); 21117 return; 21118 } 21119 } 21120 } 21121 21122 if (checkin) { 21123 pw.println("vers,1"); 21124 } 21125 21126 // reader 21127 synchronized (mPackages) { 21128 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21129 if (!checkin) { 21130 if (dumpState.onTitlePrinted()) 21131 pw.println(); 21132 pw.println("Database versions:"); 21133 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21134 } 21135 } 21136 21137 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21138 if (!checkin) { 21139 if (dumpState.onTitlePrinted()) 21140 pw.println(); 21141 pw.println("Verifiers:"); 21142 pw.print(" Required: "); 21143 pw.print(mRequiredVerifierPackage); 21144 pw.print(" (uid="); 21145 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21146 UserHandle.USER_SYSTEM)); 21147 pw.println(")"); 21148 } else if (mRequiredVerifierPackage != null) { 21149 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21150 pw.print(","); 21151 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21152 UserHandle.USER_SYSTEM)); 21153 } 21154 } 21155 21156 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21157 packageName == null) { 21158 if (mIntentFilterVerifierComponent != null) { 21159 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21160 if (!checkin) { 21161 if (dumpState.onTitlePrinted()) 21162 pw.println(); 21163 pw.println("Intent Filter Verifier:"); 21164 pw.print(" Using: "); 21165 pw.print(verifierPackageName); 21166 pw.print(" (uid="); 21167 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21168 UserHandle.USER_SYSTEM)); 21169 pw.println(")"); 21170 } else if (verifierPackageName != null) { 21171 pw.print("ifv,"); pw.print(verifierPackageName); 21172 pw.print(","); 21173 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21174 UserHandle.USER_SYSTEM)); 21175 } 21176 } else { 21177 pw.println(); 21178 pw.println("No Intent Filter Verifier available!"); 21179 } 21180 } 21181 21182 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21183 boolean printedHeader = false; 21184 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21185 while (it.hasNext()) { 21186 String libName = it.next(); 21187 LongSparseArray<SharedLibraryEntry> versionedLib 21188 = mSharedLibraries.get(libName); 21189 if (versionedLib == null) { 21190 continue; 21191 } 21192 final int versionCount = versionedLib.size(); 21193 for (int i = 0; i < versionCount; i++) { 21194 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21195 if (!checkin) { 21196 if (!printedHeader) { 21197 if (dumpState.onTitlePrinted()) 21198 pw.println(); 21199 pw.println("Libraries:"); 21200 printedHeader = true; 21201 } 21202 pw.print(" "); 21203 } else { 21204 pw.print("lib,"); 21205 } 21206 pw.print(libEntry.info.getName()); 21207 if (libEntry.info.isStatic()) { 21208 pw.print(" version=" + libEntry.info.getLongVersion()); 21209 } 21210 if (!checkin) { 21211 pw.print(" -> "); 21212 } 21213 if (libEntry.path != null) { 21214 pw.print(" (jar) "); 21215 pw.print(libEntry.path); 21216 } else { 21217 pw.print(" (apk) "); 21218 pw.print(libEntry.apk); 21219 } 21220 pw.println(); 21221 } 21222 } 21223 } 21224 21225 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21226 if (dumpState.onTitlePrinted()) 21227 pw.println(); 21228 if (!checkin) { 21229 pw.println("Features:"); 21230 } 21231 21232 synchronized (mAvailableFeatures) { 21233 for (FeatureInfo feat : mAvailableFeatures.values()) { 21234 if (checkin) { 21235 pw.print("feat,"); 21236 pw.print(feat.name); 21237 pw.print(","); 21238 pw.println(feat.version); 21239 } else { 21240 pw.print(" "); 21241 pw.print(feat.name); 21242 if (feat.version > 0) { 21243 pw.print(" version="); 21244 pw.print(feat.version); 21245 } 21246 pw.println(); 21247 } 21248 } 21249 } 21250 } 21251 21252 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21253 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21254 : "Activity Resolver Table:", " ", packageName, 21255 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21256 dumpState.setTitlePrinted(true); 21257 } 21258 } 21259 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21260 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21261 : "Receiver Resolver Table:", " ", packageName, 21262 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21263 dumpState.setTitlePrinted(true); 21264 } 21265 } 21266 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21267 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21268 : "Service Resolver Table:", " ", packageName, 21269 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21270 dumpState.setTitlePrinted(true); 21271 } 21272 } 21273 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21274 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21275 : "Provider Resolver Table:", " ", packageName, 21276 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21277 dumpState.setTitlePrinted(true); 21278 } 21279 } 21280 21281 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21282 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21283 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21284 int user = mSettings.mPreferredActivities.keyAt(i); 21285 if (pir.dump(pw, 21286 dumpState.getTitlePrinted() 21287 ? "\nPreferred Activities User " + user + ":" 21288 : "Preferred Activities User " + user + ":", " ", 21289 packageName, true, false)) { 21290 dumpState.setTitlePrinted(true); 21291 } 21292 } 21293 } 21294 21295 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21296 pw.flush(); 21297 FileOutputStream fout = new FileOutputStream(fd); 21298 BufferedOutputStream str = new BufferedOutputStream(fout); 21299 XmlSerializer serializer = new FastXmlSerializer(); 21300 try { 21301 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21302 serializer.startDocument(null, true); 21303 serializer.setFeature( 21304 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21305 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21306 serializer.endDocument(); 21307 serializer.flush(); 21308 } catch (IllegalArgumentException e) { 21309 pw.println("Failed writing: " + e); 21310 } catch (IllegalStateException e) { 21311 pw.println("Failed writing: " + e); 21312 } catch (IOException e) { 21313 pw.println("Failed writing: " + e); 21314 } 21315 } 21316 21317 if (!checkin 21318 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21319 && packageName == null) { 21320 pw.println(); 21321 int count = mSettings.mPackages.size(); 21322 if (count == 0) { 21323 pw.println("No applications!"); 21324 pw.println(); 21325 } else { 21326 final String prefix = " "; 21327 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21328 if (allPackageSettings.size() == 0) { 21329 pw.println("No domain preferred apps!"); 21330 pw.println(); 21331 } else { 21332 pw.println("App verification status:"); 21333 pw.println(); 21334 count = 0; 21335 for (PackageSetting ps : allPackageSettings) { 21336 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21337 if (ivi == null || ivi.getPackageName() == null) continue; 21338 pw.println(prefix + "Package: " + ivi.getPackageName()); 21339 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21340 pw.println(prefix + "Status: " + ivi.getStatusString()); 21341 pw.println(); 21342 count++; 21343 } 21344 if (count == 0) { 21345 pw.println(prefix + "No app verification established."); 21346 pw.println(); 21347 } 21348 for (int userId : sUserManager.getUserIds()) { 21349 pw.println("App linkages for user " + userId + ":"); 21350 pw.println(); 21351 count = 0; 21352 for (PackageSetting ps : allPackageSettings) { 21353 final long status = ps.getDomainVerificationStatusForUser(userId); 21354 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21355 && !DEBUG_DOMAIN_VERIFICATION) { 21356 continue; 21357 } 21358 pw.println(prefix + "Package: " + ps.name); 21359 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21360 String statusStr = IntentFilterVerificationInfo. 21361 getStatusStringFromValue(status); 21362 pw.println(prefix + "Status: " + statusStr); 21363 pw.println(); 21364 count++; 21365 } 21366 if (count == 0) { 21367 pw.println(prefix + "No configured app linkages."); 21368 pw.println(); 21369 } 21370 } 21371 } 21372 } 21373 } 21374 21375 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21376 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21377 } 21378 21379 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21380 boolean printedSomething = false; 21381 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21382 if (packageName != null && !packageName.equals(p.info.packageName)) { 21383 continue; 21384 } 21385 if (!printedSomething) { 21386 if (dumpState.onTitlePrinted()) 21387 pw.println(); 21388 pw.println("Registered ContentProviders:"); 21389 printedSomething = true; 21390 } 21391 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21392 pw.print(" "); pw.println(p.toString()); 21393 } 21394 printedSomething = false; 21395 for (Map.Entry<String, PackageParser.Provider> entry : 21396 mProvidersByAuthority.entrySet()) { 21397 PackageParser.Provider p = entry.getValue(); 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("ContentProvider Authorities:"); 21405 printedSomething = true; 21406 } 21407 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21408 pw.print(" "); pw.println(p.toString()); 21409 if (p.info != null && p.info.applicationInfo != null) { 21410 final String appInfo = p.info.applicationInfo.toString(); 21411 pw.print(" applicationInfo="); pw.println(appInfo); 21412 } 21413 } 21414 } 21415 21416 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21417 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21418 } 21419 21420 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21421 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21422 } 21423 21424 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21425 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21426 } 21427 21428 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21429 if (dumpState.onTitlePrinted()) pw.println(); 21430 pw.println("Package Changes:"); 21431 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21432 final int K = mChangedPackages.size(); 21433 for (int i = 0; i < K; i++) { 21434 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21435 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21436 final int N = changes.size(); 21437 if (N == 0) { 21438 pw.print(" "); pw.println("No packages changed"); 21439 } else { 21440 for (int j = 0; j < N; j++) { 21441 final String pkgName = changes.valueAt(j); 21442 final int sequenceNumber = changes.keyAt(j); 21443 pw.print(" "); 21444 pw.print("seq="); 21445 pw.print(sequenceNumber); 21446 pw.print(", package="); 21447 pw.println(pkgName); 21448 } 21449 } 21450 } 21451 } 21452 21453 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21454 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21455 } 21456 21457 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21458 // XXX should handle packageName != null by dumping only install data that 21459 // the given package is involved with. 21460 if (dumpState.onTitlePrinted()) pw.println(); 21461 21462 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21463 ipw.println(); 21464 ipw.println("Frozen packages:"); 21465 ipw.increaseIndent(); 21466 if (mFrozenPackages.size() == 0) { 21467 ipw.println("(none)"); 21468 } else { 21469 for (int i = 0; i < mFrozenPackages.size(); i++) { 21470 ipw.println(mFrozenPackages.valueAt(i)); 21471 } 21472 } 21473 ipw.decreaseIndent(); 21474 } 21475 21476 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21477 if (dumpState.onTitlePrinted()) pw.println(); 21478 21479 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21480 ipw.println(); 21481 ipw.println("Loaded volumes:"); 21482 ipw.increaseIndent(); 21483 if (mLoadedVolumes.size() == 0) { 21484 ipw.println("(none)"); 21485 } else { 21486 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21487 ipw.println(mLoadedVolumes.valueAt(i)); 21488 } 21489 } 21490 ipw.decreaseIndent(); 21491 } 21492 21493 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21494 && packageName == null) { 21495 if (dumpState.onTitlePrinted()) pw.println(); 21496 pw.println("Service permissions:"); 21497 21498 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21499 while (filterIterator.hasNext()) { 21500 final ServiceIntentInfo info = filterIterator.next(); 21501 final ServiceInfo serviceInfo = info.service.info; 21502 final String permission = serviceInfo.permission; 21503 if (permission != null) { 21504 pw.print(" "); 21505 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21506 pw.print(": "); 21507 pw.println(permission); 21508 } 21509 } 21510 } 21511 21512 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21513 if (dumpState.onTitlePrinted()) pw.println(); 21514 dumpDexoptStateLPr(pw, packageName); 21515 } 21516 21517 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21518 if (dumpState.onTitlePrinted()) pw.println(); 21519 dumpCompilerStatsLPr(pw, packageName); 21520 } 21521 21522 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21523 if (dumpState.onTitlePrinted()) pw.println(); 21524 mSettings.dumpReadMessagesLPr(pw, dumpState); 21525 21526 pw.println(); 21527 pw.println("Package warning messages:"); 21528 dumpCriticalInfo(pw, null); 21529 } 21530 21531 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21532 dumpCriticalInfo(pw, "msg,"); 21533 } 21534 } 21535 21536 // PackageInstaller should be called outside of mPackages lock 21537 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21538 // XXX should handle packageName != null by dumping only install data that 21539 // the given package is involved with. 21540 if (dumpState.onTitlePrinted()) pw.println(); 21541 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21542 } 21543 } 21544 21545 private void dumpProto(FileDescriptor fd) { 21546 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21547 21548 synchronized (mPackages) { 21549 final long requiredVerifierPackageToken = 21550 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21551 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21552 proto.write( 21553 PackageServiceDumpProto.PackageShortProto.UID, 21554 getPackageUid( 21555 mRequiredVerifierPackage, 21556 MATCH_DEBUG_TRIAGED_MISSING, 21557 UserHandle.USER_SYSTEM)); 21558 proto.end(requiredVerifierPackageToken); 21559 21560 if (mIntentFilterVerifierComponent != null) { 21561 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21562 final long verifierPackageToken = 21563 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21564 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21565 proto.write( 21566 PackageServiceDumpProto.PackageShortProto.UID, 21567 getPackageUid( 21568 verifierPackageName, 21569 MATCH_DEBUG_TRIAGED_MISSING, 21570 UserHandle.USER_SYSTEM)); 21571 proto.end(verifierPackageToken); 21572 } 21573 21574 dumpSharedLibrariesProto(proto); 21575 dumpFeaturesProto(proto); 21576 mSettings.dumpPackagesProto(proto); 21577 mSettings.dumpSharedUsersProto(proto); 21578 dumpCriticalInfo(proto); 21579 } 21580 proto.flush(); 21581 } 21582 21583 private void dumpFeaturesProto(ProtoOutputStream proto) { 21584 synchronized (mAvailableFeatures) { 21585 final int count = mAvailableFeatures.size(); 21586 for (int i = 0; i < count; i++) { 21587 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21588 } 21589 } 21590 } 21591 21592 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21593 final int count = mSharedLibraries.size(); 21594 for (int i = 0; i < count; i++) { 21595 final String libName = mSharedLibraries.keyAt(i); 21596 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21597 if (versionedLib == null) { 21598 continue; 21599 } 21600 final int versionCount = versionedLib.size(); 21601 for (int j = 0; j < versionCount; j++) { 21602 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21603 final long sharedLibraryToken = 21604 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21605 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21606 final boolean isJar = (libEntry.path != null); 21607 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21608 if (isJar) { 21609 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21610 } else { 21611 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21612 } 21613 proto.end(sharedLibraryToken); 21614 } 21615 } 21616 } 21617 21618 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21619 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21620 ipw.println(); 21621 ipw.println("Dexopt state:"); 21622 ipw.increaseIndent(); 21623 Collection<PackageParser.Package> packages = null; 21624 if (packageName != null) { 21625 PackageParser.Package targetPackage = mPackages.get(packageName); 21626 if (targetPackage != null) { 21627 packages = Collections.singletonList(targetPackage); 21628 } else { 21629 ipw.println("Unable to find package: " + packageName); 21630 return; 21631 } 21632 } else { 21633 packages = mPackages.values(); 21634 } 21635 21636 for (PackageParser.Package pkg : packages) { 21637 ipw.println("[" + pkg.packageName + "]"); 21638 ipw.increaseIndent(); 21639 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21640 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21641 ipw.decreaseIndent(); 21642 } 21643 } 21644 21645 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21646 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21647 ipw.println(); 21648 ipw.println("Compiler stats:"); 21649 ipw.increaseIndent(); 21650 Collection<PackageParser.Package> packages = null; 21651 if (packageName != null) { 21652 PackageParser.Package targetPackage = mPackages.get(packageName); 21653 if (targetPackage != null) { 21654 packages = Collections.singletonList(targetPackage); 21655 } else { 21656 ipw.println("Unable to find package: " + packageName); 21657 return; 21658 } 21659 } else { 21660 packages = mPackages.values(); 21661 } 21662 21663 for (PackageParser.Package pkg : packages) { 21664 ipw.println("[" + pkg.packageName + "]"); 21665 ipw.increaseIndent(); 21666 21667 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21668 if (stats == null) { 21669 ipw.println("(No recorded stats)"); 21670 } else { 21671 stats.dump(ipw); 21672 } 21673 ipw.decreaseIndent(); 21674 } 21675 } 21676 21677 private String dumpDomainString(String packageName) { 21678 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21679 .getList(); 21680 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21681 21682 ArraySet<String> result = new ArraySet<>(); 21683 if (iviList.size() > 0) { 21684 for (IntentFilterVerificationInfo ivi : iviList) { 21685 for (String host : ivi.getDomains()) { 21686 result.add(host); 21687 } 21688 } 21689 } 21690 if (filters != null && filters.size() > 0) { 21691 for (IntentFilter filter : filters) { 21692 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21693 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21694 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21695 result.addAll(filter.getHostsList()); 21696 } 21697 } 21698 } 21699 21700 StringBuilder sb = new StringBuilder(result.size() * 16); 21701 for (String domain : result) { 21702 if (sb.length() > 0) sb.append(" "); 21703 sb.append(domain); 21704 } 21705 return sb.toString(); 21706 } 21707 21708 // ------- apps on sdcard specific code ------- 21709 static final boolean DEBUG_SD_INSTALL = false; 21710 21711 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21712 21713 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21714 21715 private boolean mMediaMounted = false; 21716 21717 static String getEncryptKey() { 21718 try { 21719 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21720 SD_ENCRYPTION_KEYSTORE_NAME); 21721 if (sdEncKey == null) { 21722 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21723 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21724 if (sdEncKey == null) { 21725 Slog.e(TAG, "Failed to create encryption keys"); 21726 return null; 21727 } 21728 } 21729 return sdEncKey; 21730 } catch (NoSuchAlgorithmException nsae) { 21731 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21732 return null; 21733 } catch (IOException ioe) { 21734 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21735 return null; 21736 } 21737 } 21738 21739 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21740 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21741 final int size = infos.size(); 21742 final String[] packageNames = new String[size]; 21743 final int[] packageUids = new int[size]; 21744 for (int i = 0; i < size; i++) { 21745 final ApplicationInfo info = infos.get(i); 21746 packageNames[i] = info.packageName; 21747 packageUids[i] = info.uid; 21748 } 21749 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21750 finishedReceiver); 21751 } 21752 21753 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21754 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21755 sendResourcesChangedBroadcast(mediaStatus, replacing, 21756 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21757 } 21758 21759 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21760 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21761 int size = pkgList.length; 21762 if (size > 0) { 21763 // Send broadcasts here 21764 Bundle extras = new Bundle(); 21765 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21766 if (uidArr != null) { 21767 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21768 } 21769 if (replacing) { 21770 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21771 } 21772 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21773 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21774 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21775 } 21776 } 21777 21778 private void loadPrivatePackages(final VolumeInfo vol) { 21779 mHandler.post(new Runnable() { 21780 @Override 21781 public void run() { 21782 loadPrivatePackagesInner(vol); 21783 } 21784 }); 21785 } 21786 21787 private void loadPrivatePackagesInner(VolumeInfo vol) { 21788 final String volumeUuid = vol.fsUuid; 21789 if (TextUtils.isEmpty(volumeUuid)) { 21790 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21791 return; 21792 } 21793 21794 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21795 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21796 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21797 21798 final VersionInfo ver; 21799 final List<PackageSetting> packages; 21800 synchronized (mPackages) { 21801 ver = mSettings.findOrCreateVersion(volumeUuid); 21802 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21803 } 21804 21805 for (PackageSetting ps : packages) { 21806 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21807 synchronized (mInstallLock) { 21808 final PackageParser.Package pkg; 21809 try { 21810 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21811 loaded.add(pkg.applicationInfo); 21812 21813 } catch (PackageManagerException e) { 21814 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21815 } 21816 21817 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21818 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21819 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21820 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21821 } 21822 } 21823 } 21824 21825 // Reconcile app data for all started/unlocked users 21826 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21827 final UserManager um = mContext.getSystemService(UserManager.class); 21828 UserManagerInternal umInternal = getUserManagerInternal(); 21829 for (UserInfo user : um.getUsers()) { 21830 final int flags; 21831 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21832 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21833 } else if (umInternal.isUserRunning(user.id)) { 21834 flags = StorageManager.FLAG_STORAGE_DE; 21835 } else { 21836 continue; 21837 } 21838 21839 try { 21840 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21841 synchronized (mInstallLock) { 21842 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21843 } 21844 } catch (IllegalStateException e) { 21845 // Device was probably ejected, and we'll process that event momentarily 21846 Slog.w(TAG, "Failed to prepare storage: " + e); 21847 } 21848 } 21849 21850 synchronized (mPackages) { 21851 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21852 if (sdkUpdated) { 21853 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21854 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21855 } 21856 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21857 mPermissionCallback); 21858 21859 // Yay, everything is now upgraded 21860 ver.forceCurrent(); 21861 21862 mSettings.writeLPr(); 21863 } 21864 21865 for (PackageFreezer freezer : freezers) { 21866 freezer.close(); 21867 } 21868 21869 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21870 sendResourcesChangedBroadcast(true, false, loaded, null); 21871 mLoadedVolumes.add(vol.getId()); 21872 } 21873 21874 private void unloadPrivatePackages(final VolumeInfo vol) { 21875 mHandler.post(new Runnable() { 21876 @Override 21877 public void run() { 21878 unloadPrivatePackagesInner(vol); 21879 } 21880 }); 21881 } 21882 21883 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21884 final String volumeUuid = vol.fsUuid; 21885 if (TextUtils.isEmpty(volumeUuid)) { 21886 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21887 return; 21888 } 21889 21890 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21891 synchronized (mInstallLock) { 21892 synchronized (mPackages) { 21893 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21894 for (PackageSetting ps : packages) { 21895 if (ps.pkg == null) continue; 21896 21897 final ApplicationInfo info = ps.pkg.applicationInfo; 21898 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21899 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21900 21901 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21902 "unloadPrivatePackagesInner")) { 21903 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21904 false, null)) { 21905 unloaded.add(info); 21906 } else { 21907 Slog.w(TAG, "Failed to unload " + ps.codePath); 21908 } 21909 } 21910 21911 // Try very hard to release any references to this package 21912 // so we don't risk the system server being killed due to 21913 // open FDs 21914 AttributeCache.instance().removePackage(ps.name); 21915 } 21916 21917 mSettings.writeLPr(); 21918 } 21919 } 21920 21921 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21922 sendResourcesChangedBroadcast(false, false, unloaded, null); 21923 mLoadedVolumes.remove(vol.getId()); 21924 21925 // Try very hard to release any references to this path so we don't risk 21926 // the system server being killed due to open FDs 21927 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21928 21929 for (int i = 0; i < 3; i++) { 21930 System.gc(); 21931 System.runFinalization(); 21932 } 21933 } 21934 21935 private void assertPackageKnown(String volumeUuid, String packageName) 21936 throws PackageManagerException { 21937 synchronized (mPackages) { 21938 // Normalize package name to handle renamed packages 21939 packageName = normalizePackageNameLPr(packageName); 21940 21941 final PackageSetting ps = mSettings.mPackages.get(packageName); 21942 if (ps == null) { 21943 throw new PackageManagerException("Package " + packageName + " is unknown"); 21944 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21945 throw new PackageManagerException( 21946 "Package " + packageName + " found on unknown volume " + volumeUuid 21947 + "; expected volume " + ps.volumeUuid); 21948 } 21949 } 21950 } 21951 21952 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21953 throws PackageManagerException { 21954 synchronized (mPackages) { 21955 // Normalize package name to handle renamed packages 21956 packageName = normalizePackageNameLPr(packageName); 21957 21958 final PackageSetting ps = mSettings.mPackages.get(packageName); 21959 if (ps == null) { 21960 throw new PackageManagerException("Package " + packageName + " is unknown"); 21961 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21962 throw new PackageManagerException( 21963 "Package " + packageName + " found on unknown volume " + volumeUuid 21964 + "; expected volume " + ps.volumeUuid); 21965 } else if (!ps.getInstalled(userId)) { 21966 throw new PackageManagerException( 21967 "Package " + packageName + " not installed for user " + userId); 21968 } 21969 } 21970 } 21971 21972 private List<String> collectAbsoluteCodePaths() { 21973 synchronized (mPackages) { 21974 List<String> codePaths = new ArrayList<>(); 21975 final int packageCount = mSettings.mPackages.size(); 21976 for (int i = 0; i < packageCount; i++) { 21977 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21978 codePaths.add(ps.codePath.getAbsolutePath()); 21979 } 21980 return codePaths; 21981 } 21982 } 21983 21984 /** 21985 * Examine all apps present on given mounted volume, and destroy apps that 21986 * aren't expected, either due to uninstallation or reinstallation on 21987 * another volume. 21988 */ 21989 private void reconcileApps(String volumeUuid) { 21990 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21991 List<File> filesToDelete = null; 21992 21993 final File[] files = FileUtils.listFilesOrEmpty( 21994 Environment.getDataAppDirectory(volumeUuid)); 21995 for (File file : files) { 21996 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21997 && !PackageInstallerService.isStageName(file.getName()); 21998 if (!isPackage) { 21999 // Ignore entries which are not packages 22000 continue; 22001 } 22002 22003 String absolutePath = file.getAbsolutePath(); 22004 22005 boolean pathValid = false; 22006 final int absoluteCodePathCount = absoluteCodePaths.size(); 22007 for (int i = 0; i < absoluteCodePathCount; i++) { 22008 String absoluteCodePath = absoluteCodePaths.get(i); 22009 if (absolutePath.startsWith(absoluteCodePath)) { 22010 pathValid = true; 22011 break; 22012 } 22013 } 22014 22015 if (!pathValid) { 22016 if (filesToDelete == null) { 22017 filesToDelete = new ArrayList<>(); 22018 } 22019 filesToDelete.add(file); 22020 } 22021 } 22022 22023 if (filesToDelete != null) { 22024 final int fileToDeleteCount = filesToDelete.size(); 22025 for (int i = 0; i < fileToDeleteCount; i++) { 22026 File fileToDelete = filesToDelete.get(i); 22027 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22028 synchronized (mInstallLock) { 22029 removeCodePathLI(fileToDelete); 22030 } 22031 } 22032 } 22033 } 22034 22035 /** 22036 * Reconcile all app data for the given user. 22037 * <p> 22038 * Verifies that directories exist and that ownership and labeling is 22039 * correct for all installed apps on all mounted volumes. 22040 */ 22041 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22042 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22043 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22044 final String volumeUuid = vol.getFsUuid(); 22045 synchronized (mInstallLock) { 22046 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22047 } 22048 } 22049 } 22050 22051 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22052 boolean migrateAppData) { 22053 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22054 } 22055 22056 /** 22057 * Reconcile all app data on given mounted volume. 22058 * <p> 22059 * Destroys app data that isn't expected, either due to uninstallation or 22060 * reinstallation on another volume. 22061 * <p> 22062 * Verifies that directories exist and that ownership and labeling is 22063 * correct for all installed apps. 22064 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22065 */ 22066 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22067 boolean migrateAppData, boolean onlyCoreApps) { 22068 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22069 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22070 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22071 22072 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22073 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22074 22075 // First look for stale data that doesn't belong, and check if things 22076 // have changed since we did our last restorecon 22077 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22078 if (StorageManager.isFileEncryptedNativeOrEmulated() 22079 && !StorageManager.isUserKeyUnlocked(userId)) { 22080 throw new RuntimeException( 22081 "Yikes, someone asked us to reconcile CE storage while " + userId 22082 + " was still locked; this would have caused massive data loss!"); 22083 } 22084 22085 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22086 for (File file : files) { 22087 final String packageName = file.getName(); 22088 try { 22089 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22090 } catch (PackageManagerException e) { 22091 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22092 try { 22093 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22094 StorageManager.FLAG_STORAGE_CE, 0); 22095 } catch (InstallerException e2) { 22096 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22097 } 22098 } 22099 } 22100 } 22101 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22102 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22103 for (File file : files) { 22104 final String packageName = file.getName(); 22105 try { 22106 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22107 } catch (PackageManagerException e) { 22108 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22109 try { 22110 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22111 StorageManager.FLAG_STORAGE_DE, 0); 22112 } catch (InstallerException e2) { 22113 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22114 } 22115 } 22116 } 22117 } 22118 22119 // Ensure that data directories are ready to roll for all packages 22120 // installed for this volume and user 22121 final List<PackageSetting> packages; 22122 synchronized (mPackages) { 22123 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22124 } 22125 int preparedCount = 0; 22126 for (PackageSetting ps : packages) { 22127 final String packageName = ps.name; 22128 if (ps.pkg == null) { 22129 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22130 // TODO: might be due to legacy ASEC apps; we should circle back 22131 // and reconcile again once they're scanned 22132 continue; 22133 } 22134 // Skip non-core apps if requested 22135 if (onlyCoreApps && !ps.pkg.coreApp) { 22136 result.add(packageName); 22137 continue; 22138 } 22139 22140 if (ps.getInstalled(userId)) { 22141 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22142 preparedCount++; 22143 } 22144 } 22145 22146 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22147 return result; 22148 } 22149 22150 /** 22151 * Prepare app data for the given app just after it was installed or 22152 * upgraded. This method carefully only touches users that it's installed 22153 * for, and it forces a restorecon to handle any seinfo changes. 22154 * <p> 22155 * Verifies that directories exist and that ownership and labeling is 22156 * correct for all installed apps. If there is an ownership mismatch, it 22157 * will try recovering system apps by wiping data; third-party app data is 22158 * left intact. 22159 * <p> 22160 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22161 */ 22162 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22163 final PackageSetting ps; 22164 synchronized (mPackages) { 22165 ps = mSettings.mPackages.get(pkg.packageName); 22166 mSettings.writeKernelMappingLPr(ps); 22167 } 22168 22169 final UserManager um = mContext.getSystemService(UserManager.class); 22170 UserManagerInternal umInternal = getUserManagerInternal(); 22171 for (UserInfo user : um.getUsers()) { 22172 final int flags; 22173 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22174 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22175 } else if (umInternal.isUserRunning(user.id)) { 22176 flags = StorageManager.FLAG_STORAGE_DE; 22177 } else { 22178 continue; 22179 } 22180 22181 if (ps.getInstalled(user.id)) { 22182 // TODO: when user data is locked, mark that we're still dirty 22183 prepareAppDataLIF(pkg, user.id, flags); 22184 } 22185 } 22186 } 22187 22188 /** 22189 * Prepare app data for the given app. 22190 * <p> 22191 * Verifies that directories exist and that ownership and labeling is 22192 * correct for all installed apps. If there is an ownership mismatch, this 22193 * will try recovering system apps by wiping data; third-party app data is 22194 * left intact. 22195 */ 22196 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22197 if (pkg == null) { 22198 Slog.wtf(TAG, "Package was null!", new Throwable()); 22199 return; 22200 } 22201 prepareAppDataLeafLIF(pkg, userId, flags); 22202 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22203 for (int i = 0; i < childCount; i++) { 22204 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22205 } 22206 } 22207 22208 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22209 boolean maybeMigrateAppData) { 22210 prepareAppDataLIF(pkg, userId, flags); 22211 22212 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22213 // We may have just shuffled around app data directories, so 22214 // prepare them one more time 22215 prepareAppDataLIF(pkg, userId, flags); 22216 } 22217 } 22218 22219 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22220 if (DEBUG_APP_DATA) { 22221 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22222 + Integer.toHexString(flags)); 22223 } 22224 22225 final String volumeUuid = pkg.volumeUuid; 22226 final String packageName = pkg.packageName; 22227 final ApplicationInfo app = pkg.applicationInfo; 22228 final int appId = UserHandle.getAppId(app.uid); 22229 22230 Preconditions.checkNotNull(app.seInfo); 22231 22232 long ceDataInode = -1; 22233 try { 22234 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22235 appId, app.seInfo, app.targetSdkVersion); 22236 } catch (InstallerException e) { 22237 if (app.isSystemApp()) { 22238 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22239 + ", but trying to recover: " + e); 22240 destroyAppDataLeafLIF(pkg, userId, flags); 22241 try { 22242 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22243 appId, app.seInfo, app.targetSdkVersion); 22244 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22245 } catch (InstallerException e2) { 22246 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22247 } 22248 } else { 22249 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22250 } 22251 } 22252 // Prepare the application profiles. 22253 mArtManagerService.prepareAppProfiles(pkg, userId); 22254 22255 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22256 // TODO: mark this structure as dirty so we persist it! 22257 synchronized (mPackages) { 22258 final PackageSetting ps = mSettings.mPackages.get(packageName); 22259 if (ps != null) { 22260 ps.setCeDataInode(ceDataInode, userId); 22261 } 22262 } 22263 } 22264 22265 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22266 } 22267 22268 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22269 if (pkg == null) { 22270 Slog.wtf(TAG, "Package was null!", new Throwable()); 22271 return; 22272 } 22273 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22275 for (int i = 0; i < childCount; i++) { 22276 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22277 } 22278 } 22279 22280 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22281 final String volumeUuid = pkg.volumeUuid; 22282 final String packageName = pkg.packageName; 22283 final ApplicationInfo app = pkg.applicationInfo; 22284 22285 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22286 // Create a native library symlink only if we have native libraries 22287 // and if the native libraries are 32 bit libraries. We do not provide 22288 // this symlink for 64 bit libraries. 22289 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22290 final String nativeLibPath = app.nativeLibraryDir; 22291 try { 22292 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22293 nativeLibPath, userId); 22294 } catch (InstallerException e) { 22295 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22296 } 22297 } 22298 } 22299 } 22300 22301 /** 22302 * For system apps on non-FBE devices, this method migrates any existing 22303 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22304 * requested by the app. 22305 */ 22306 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22307 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22308 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22309 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22310 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22311 try { 22312 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22313 storageTarget); 22314 } catch (InstallerException e) { 22315 logCriticalInfo(Log.WARN, 22316 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22317 } 22318 return true; 22319 } else { 22320 return false; 22321 } 22322 } 22323 22324 public PackageFreezer freezePackage(String packageName, String killReason) { 22325 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22326 } 22327 22328 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22329 return new PackageFreezer(packageName, userId, killReason); 22330 } 22331 22332 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22333 String killReason) { 22334 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22335 } 22336 22337 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22338 String killReason) { 22339 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22340 return new PackageFreezer(); 22341 } else { 22342 return freezePackage(packageName, userId, killReason); 22343 } 22344 } 22345 22346 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22347 String killReason) { 22348 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22349 } 22350 22351 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22352 String killReason) { 22353 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22354 return new PackageFreezer(); 22355 } else { 22356 return freezePackage(packageName, userId, killReason); 22357 } 22358 } 22359 22360 /** 22361 * Class that freezes and kills the given package upon creation, and 22362 * unfreezes it upon closing. This is typically used when doing surgery on 22363 * app code/data to prevent the app from running while you're working. 22364 */ 22365 private class PackageFreezer implements AutoCloseable { 22366 private final String mPackageName; 22367 private final PackageFreezer[] mChildren; 22368 22369 private final boolean mWeFroze; 22370 22371 private final AtomicBoolean mClosed = new AtomicBoolean(); 22372 private final CloseGuard mCloseGuard = CloseGuard.get(); 22373 22374 /** 22375 * Create and return a stub freezer that doesn't actually do anything, 22376 * typically used when someone requested 22377 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22378 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22379 */ 22380 public PackageFreezer() { 22381 mPackageName = null; 22382 mChildren = null; 22383 mWeFroze = false; 22384 mCloseGuard.open("close"); 22385 } 22386 22387 public PackageFreezer(String packageName, int userId, String killReason) { 22388 synchronized (mPackages) { 22389 mPackageName = packageName; 22390 mWeFroze = mFrozenPackages.add(mPackageName); 22391 22392 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22393 if (ps != null) { 22394 killApplication(ps.name, ps.appId, userId, killReason); 22395 } 22396 22397 final PackageParser.Package p = mPackages.get(packageName); 22398 if (p != null && p.childPackages != null) { 22399 final int N = p.childPackages.size(); 22400 mChildren = new PackageFreezer[N]; 22401 for (int i = 0; i < N; i++) { 22402 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22403 userId, killReason); 22404 } 22405 } else { 22406 mChildren = null; 22407 } 22408 } 22409 mCloseGuard.open("close"); 22410 } 22411 22412 @Override 22413 protected void finalize() throws Throwable { 22414 try { 22415 if (mCloseGuard != null) { 22416 mCloseGuard.warnIfOpen(); 22417 } 22418 22419 close(); 22420 } finally { 22421 super.finalize(); 22422 } 22423 } 22424 22425 @Override 22426 public void close() { 22427 mCloseGuard.close(); 22428 if (mClosed.compareAndSet(false, true)) { 22429 synchronized (mPackages) { 22430 if (mWeFroze) { 22431 mFrozenPackages.remove(mPackageName); 22432 } 22433 22434 if (mChildren != null) { 22435 for (PackageFreezer freezer : mChildren) { 22436 freezer.close(); 22437 } 22438 } 22439 } 22440 } 22441 } 22442 } 22443 22444 /** 22445 * Verify that given package is currently frozen. 22446 */ 22447 private void checkPackageFrozen(String packageName) { 22448 synchronized (mPackages) { 22449 if (!mFrozenPackages.contains(packageName)) { 22450 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22451 } 22452 } 22453 } 22454 22455 @Override 22456 public int movePackage(final String packageName, final String volumeUuid) { 22457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22458 22459 final int callingUid = Binder.getCallingUid(); 22460 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22461 final int moveId = mNextMoveId.getAndIncrement(); 22462 mHandler.post(new Runnable() { 22463 @Override 22464 public void run() { 22465 try { 22466 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22467 } catch (PackageManagerException e) { 22468 Slog.w(TAG, "Failed to move " + packageName, e); 22469 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22470 } 22471 } 22472 }); 22473 return moveId; 22474 } 22475 22476 private void movePackageInternal(final String packageName, final String volumeUuid, 22477 final int moveId, final int callingUid, UserHandle user) 22478 throws PackageManagerException { 22479 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22480 final PackageManager pm = mContext.getPackageManager(); 22481 22482 final boolean currentAsec; 22483 final String currentVolumeUuid; 22484 final File codeFile; 22485 final String installerPackageName; 22486 final String packageAbiOverride; 22487 final int appId; 22488 final String seinfo; 22489 final String label; 22490 final int targetSdkVersion; 22491 final PackageFreezer freezer; 22492 final int[] installedUserIds; 22493 22494 // reader 22495 synchronized (mPackages) { 22496 final PackageParser.Package pkg = mPackages.get(packageName); 22497 final PackageSetting ps = mSettings.mPackages.get(packageName); 22498 if (pkg == null 22499 || ps == null 22500 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22501 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22502 } 22503 if (pkg.applicationInfo.isSystemApp()) { 22504 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22505 "Cannot move system application"); 22506 } 22507 22508 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22509 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22510 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22511 if (isInternalStorage && !allow3rdPartyOnInternal) { 22512 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22513 "3rd party apps are not allowed on internal storage"); 22514 } 22515 22516 if (pkg.applicationInfo.isExternalAsec()) { 22517 currentAsec = true; 22518 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22519 } else if (pkg.applicationInfo.isForwardLocked()) { 22520 currentAsec = true; 22521 currentVolumeUuid = "forward_locked"; 22522 } else { 22523 currentAsec = false; 22524 currentVolumeUuid = ps.volumeUuid; 22525 22526 final File probe = new File(pkg.codePath); 22527 final File probeOat = new File(probe, "oat"); 22528 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22529 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22530 "Move only supported for modern cluster style installs"); 22531 } 22532 } 22533 22534 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22535 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22536 "Package already moved to " + volumeUuid); 22537 } 22538 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22539 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22540 "Device admin cannot be moved"); 22541 } 22542 22543 if (mFrozenPackages.contains(packageName)) { 22544 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22545 "Failed to move already frozen package"); 22546 } 22547 22548 codeFile = new File(pkg.codePath); 22549 installerPackageName = ps.installerPackageName; 22550 packageAbiOverride = ps.cpuAbiOverrideString; 22551 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22552 seinfo = pkg.applicationInfo.seInfo; 22553 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22554 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22555 freezer = freezePackage(packageName, "movePackageInternal"); 22556 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22557 } 22558 22559 final Bundle extras = new Bundle(); 22560 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22561 extras.putString(Intent.EXTRA_TITLE, label); 22562 mMoveCallbacks.notifyCreated(moveId, extras); 22563 22564 int installFlags; 22565 final boolean moveCompleteApp; 22566 final File measurePath; 22567 22568 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22569 installFlags = INSTALL_INTERNAL; 22570 moveCompleteApp = !currentAsec; 22571 measurePath = Environment.getDataAppDirectory(volumeUuid); 22572 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22573 installFlags = INSTALL_EXTERNAL; 22574 moveCompleteApp = false; 22575 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22576 } else { 22577 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22578 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22579 || !volume.isMountedWritable()) { 22580 freezer.close(); 22581 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22582 "Move location not mounted private volume"); 22583 } 22584 22585 Preconditions.checkState(!currentAsec); 22586 22587 installFlags = INSTALL_INTERNAL; 22588 moveCompleteApp = true; 22589 measurePath = Environment.getDataAppDirectory(volumeUuid); 22590 } 22591 22592 // If we're moving app data around, we need all the users unlocked 22593 if (moveCompleteApp) { 22594 for (int userId : installedUserIds) { 22595 if (StorageManager.isFileEncryptedNativeOrEmulated() 22596 && !StorageManager.isUserKeyUnlocked(userId)) { 22597 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22598 "User " + userId + " must be unlocked"); 22599 } 22600 } 22601 } 22602 22603 final PackageStats stats = new PackageStats(null, -1); 22604 synchronized (mInstaller) { 22605 for (int userId : installedUserIds) { 22606 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22607 freezer.close(); 22608 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22609 "Failed to measure package size"); 22610 } 22611 } 22612 } 22613 22614 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22615 + stats.dataSize); 22616 22617 final long startFreeBytes = measurePath.getUsableSpace(); 22618 final long sizeBytes; 22619 if (moveCompleteApp) { 22620 sizeBytes = stats.codeSize + stats.dataSize; 22621 } else { 22622 sizeBytes = stats.codeSize; 22623 } 22624 22625 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22626 freezer.close(); 22627 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22628 "Not enough free space to move"); 22629 } 22630 22631 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22632 22633 final CountDownLatch installedLatch = new CountDownLatch(1); 22634 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22635 @Override 22636 public void onUserActionRequired(Intent intent) throws RemoteException { 22637 throw new IllegalStateException(); 22638 } 22639 22640 @Override 22641 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22642 Bundle extras) throws RemoteException { 22643 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22644 + PackageManager.installStatusToString(returnCode, msg)); 22645 22646 installedLatch.countDown(); 22647 freezer.close(); 22648 22649 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22650 switch (status) { 22651 case PackageInstaller.STATUS_SUCCESS: 22652 mMoveCallbacks.notifyStatusChanged(moveId, 22653 PackageManager.MOVE_SUCCEEDED); 22654 break; 22655 case PackageInstaller.STATUS_FAILURE_STORAGE: 22656 mMoveCallbacks.notifyStatusChanged(moveId, 22657 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22658 break; 22659 default: 22660 mMoveCallbacks.notifyStatusChanged(moveId, 22661 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22662 break; 22663 } 22664 } 22665 }; 22666 22667 final MoveInfo move; 22668 if (moveCompleteApp) { 22669 // Kick off a thread to report progress estimates 22670 new Thread() { 22671 @Override 22672 public void run() { 22673 while (true) { 22674 try { 22675 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22676 break; 22677 } 22678 } catch (InterruptedException ignored) { 22679 } 22680 22681 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22682 final int progress = 10 + (int) MathUtils.constrain( 22683 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22684 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22685 } 22686 } 22687 }.start(); 22688 22689 final String dataAppName = codeFile.getName(); 22690 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22691 dataAppName, appId, seinfo, targetSdkVersion); 22692 } else { 22693 move = null; 22694 } 22695 22696 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22697 22698 final Message msg = mHandler.obtainMessage(INIT_COPY); 22699 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22700 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22701 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22702 packageAbiOverride, null /*grantedPermissions*/, 22703 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22704 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22705 msg.obj = params; 22706 22707 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22708 System.identityHashCode(msg.obj)); 22709 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22710 System.identityHashCode(msg.obj)); 22711 22712 mHandler.sendMessage(msg); 22713 } 22714 22715 @Override 22716 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22717 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22718 22719 final int realMoveId = mNextMoveId.getAndIncrement(); 22720 final Bundle extras = new Bundle(); 22721 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22722 mMoveCallbacks.notifyCreated(realMoveId, extras); 22723 22724 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22725 @Override 22726 public void onCreated(int moveId, Bundle extras) { 22727 // Ignored 22728 } 22729 22730 @Override 22731 public void onStatusChanged(int moveId, int status, long estMillis) { 22732 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22733 } 22734 }; 22735 22736 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22737 storage.setPrimaryStorageUuid(volumeUuid, callback); 22738 return realMoveId; 22739 } 22740 22741 @Override 22742 public int getMoveStatus(int moveId) { 22743 mContext.enforceCallingOrSelfPermission( 22744 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22745 return mMoveCallbacks.mLastStatus.get(moveId); 22746 } 22747 22748 @Override 22749 public void registerMoveCallback(IPackageMoveObserver callback) { 22750 mContext.enforceCallingOrSelfPermission( 22751 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22752 mMoveCallbacks.register(callback); 22753 } 22754 22755 @Override 22756 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22757 mContext.enforceCallingOrSelfPermission( 22758 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22759 mMoveCallbacks.unregister(callback); 22760 } 22761 22762 @Override 22763 public boolean setInstallLocation(int loc) { 22764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22765 null); 22766 if (getInstallLocation() == loc) { 22767 return true; 22768 } 22769 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22770 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22771 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22772 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22773 return true; 22774 } 22775 return false; 22776 } 22777 22778 @Override 22779 public int getInstallLocation() { 22780 // allow instant app access 22781 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22782 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22783 PackageHelper.APP_INSTALL_AUTO); 22784 } 22785 22786 /** Called by UserManagerService */ 22787 void cleanUpUser(UserManagerService userManager, int userHandle) { 22788 synchronized (mPackages) { 22789 mDirtyUsers.remove(userHandle); 22790 mUserNeedsBadging.delete(userHandle); 22791 mSettings.removeUserLPw(userHandle); 22792 mPendingBroadcasts.remove(userHandle); 22793 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22794 removeUnusedPackagesLPw(userManager, userHandle); 22795 } 22796 } 22797 22798 /** 22799 * We're removing userHandle and would like to remove any downloaded packages 22800 * that are no longer in use by any other user. 22801 * @param userHandle the user being removed 22802 */ 22803 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22804 final boolean DEBUG_CLEAN_APKS = false; 22805 int [] users = userManager.getUserIds(); 22806 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22807 while (psit.hasNext()) { 22808 PackageSetting ps = psit.next(); 22809 if (ps.pkg == null) { 22810 continue; 22811 } 22812 final String packageName = ps.pkg.packageName; 22813 // Skip over if system app 22814 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22815 continue; 22816 } 22817 if (DEBUG_CLEAN_APKS) { 22818 Slog.i(TAG, "Checking package " + packageName); 22819 } 22820 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22821 if (keep) { 22822 if (DEBUG_CLEAN_APKS) { 22823 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22824 } 22825 } else { 22826 for (int i = 0; i < users.length; i++) { 22827 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22828 keep = true; 22829 if (DEBUG_CLEAN_APKS) { 22830 Slog.i(TAG, " Keeping package " + packageName + " for user " 22831 + users[i]); 22832 } 22833 break; 22834 } 22835 } 22836 } 22837 if (!keep) { 22838 if (DEBUG_CLEAN_APKS) { 22839 Slog.i(TAG, " Removing package " + packageName); 22840 } 22841 mHandler.post(new Runnable() { 22842 public void run() { 22843 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22844 userHandle, 0); 22845 } //end run 22846 }); 22847 } 22848 } 22849 } 22850 22851 /** Called by UserManagerService */ 22852 void createNewUser(int userId, String[] disallowedPackages) { 22853 synchronized (mInstallLock) { 22854 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22855 } 22856 synchronized (mPackages) { 22857 scheduleWritePackageRestrictionsLocked(userId); 22858 scheduleWritePackageListLocked(userId); 22859 applyFactoryDefaultBrowserLPw(userId); 22860 primeDomainVerificationsLPw(userId); 22861 } 22862 } 22863 22864 void onNewUserCreated(final int userId) { 22865 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22866 synchronized(mPackages) { 22867 // If permission review for legacy apps is required, we represent 22868 // dagerous permissions for such apps as always granted runtime 22869 // permissions to keep per user flag state whether review is needed. 22870 // Hence, if a new user is added we have to propagate dangerous 22871 // permission grants for these legacy apps. 22872 if (mSettings.mPermissions.mPermissionReviewRequired) { 22873// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22874 mPermissionManager.updateAllPermissions( 22875 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22876 mPermissionCallback); 22877 } 22878 } 22879 } 22880 22881 @Override 22882 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22883 mContext.enforceCallingOrSelfPermission( 22884 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22885 "Only package verification agents can read the verifier device identity"); 22886 22887 synchronized (mPackages) { 22888 return mSettings.getVerifierDeviceIdentityLPw(); 22889 } 22890 } 22891 22892 @Override 22893 public void setPermissionEnforced(String permission, boolean enforced) { 22894 // TODO: Now that we no longer change GID for storage, this should to away. 22895 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22896 "setPermissionEnforced"); 22897 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22898 synchronized (mPackages) { 22899 if (mSettings.mReadExternalStorageEnforced == null 22900 || mSettings.mReadExternalStorageEnforced != enforced) { 22901 mSettings.mReadExternalStorageEnforced = 22902 enforced ? Boolean.TRUE : Boolean.FALSE; 22903 mSettings.writeLPr(); 22904 } 22905 } 22906 // kill any non-foreground processes so we restart them and 22907 // grant/revoke the GID. 22908 final IActivityManager am = ActivityManager.getService(); 22909 if (am != null) { 22910 final long token = Binder.clearCallingIdentity(); 22911 try { 22912 am.killProcessesBelowForeground("setPermissionEnforcement"); 22913 } catch (RemoteException e) { 22914 } finally { 22915 Binder.restoreCallingIdentity(token); 22916 } 22917 } 22918 } else { 22919 throw new IllegalArgumentException("No selective enforcement for " + permission); 22920 } 22921 } 22922 22923 @Override 22924 @Deprecated 22925 public boolean isPermissionEnforced(String permission) { 22926 // allow instant applications 22927 return true; 22928 } 22929 22930 @Override 22931 public boolean isStorageLow() { 22932 // allow instant applications 22933 final long token = Binder.clearCallingIdentity(); 22934 try { 22935 final DeviceStorageMonitorInternal 22936 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22937 if (dsm != null) { 22938 return dsm.isMemoryLow(); 22939 } else { 22940 return false; 22941 } 22942 } finally { 22943 Binder.restoreCallingIdentity(token); 22944 } 22945 } 22946 22947 @Override 22948 public IPackageInstaller getPackageInstaller() { 22949 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22950 return null; 22951 } 22952 return mInstallerService; 22953 } 22954 22955 @Override 22956 public IArtManager getArtManager() { 22957 return mArtManagerService; 22958 } 22959 22960 private boolean userNeedsBadging(int userId) { 22961 int index = mUserNeedsBadging.indexOfKey(userId); 22962 if (index < 0) { 22963 final UserInfo userInfo; 22964 final long token = Binder.clearCallingIdentity(); 22965 try { 22966 userInfo = sUserManager.getUserInfo(userId); 22967 } finally { 22968 Binder.restoreCallingIdentity(token); 22969 } 22970 final boolean b; 22971 if (userInfo != null && userInfo.isManagedProfile()) { 22972 b = true; 22973 } else { 22974 b = false; 22975 } 22976 mUserNeedsBadging.put(userId, b); 22977 return b; 22978 } 22979 return mUserNeedsBadging.valueAt(index); 22980 } 22981 22982 @Override 22983 public KeySet getKeySetByAlias(String packageName, String alias) { 22984 if (packageName == null || alias == null) { 22985 return null; 22986 } 22987 synchronized(mPackages) { 22988 final PackageParser.Package pkg = mPackages.get(packageName); 22989 if (pkg == null) { 22990 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22991 throw new IllegalArgumentException("Unknown package: " + packageName); 22992 } 22993 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22994 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22995 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22996 throw new IllegalArgumentException("Unknown package: " + packageName); 22997 } 22998 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22999 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23000 } 23001 } 23002 23003 @Override 23004 public KeySet getSigningKeySet(String packageName) { 23005 if (packageName == null) { 23006 return null; 23007 } 23008 synchronized(mPackages) { 23009 final int callingUid = Binder.getCallingUid(); 23010 final int callingUserId = UserHandle.getUserId(callingUid); 23011 final PackageParser.Package pkg = mPackages.get(packageName); 23012 if (pkg == null) { 23013 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23014 throw new IllegalArgumentException("Unknown package: " + packageName); 23015 } 23016 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23017 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23018 // filter and pretend the package doesn't exist 23019 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23020 + ", uid:" + callingUid); 23021 throw new IllegalArgumentException("Unknown package: " + packageName); 23022 } 23023 if (pkg.applicationInfo.uid != callingUid 23024 && Process.SYSTEM_UID != callingUid) { 23025 throw new SecurityException("May not access signing KeySet of other apps."); 23026 } 23027 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23028 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23029 } 23030 } 23031 23032 @Override 23033 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23034 final int callingUid = Binder.getCallingUid(); 23035 if (getInstantAppPackageName(callingUid) != null) { 23036 return false; 23037 } 23038 if (packageName == null || ks == null) { 23039 return false; 23040 } 23041 synchronized(mPackages) { 23042 final PackageParser.Package pkg = mPackages.get(packageName); 23043 if (pkg == null 23044 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23045 UserHandle.getUserId(callingUid))) { 23046 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23047 throw new IllegalArgumentException("Unknown package: " + packageName); 23048 } 23049 IBinder ksh = ks.getToken(); 23050 if (ksh instanceof KeySetHandle) { 23051 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23052 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23053 } 23054 return false; 23055 } 23056 } 23057 23058 @Override 23059 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23060 final int callingUid = Binder.getCallingUid(); 23061 if (getInstantAppPackageName(callingUid) != null) { 23062 return false; 23063 } 23064 if (packageName == null || ks == null) { 23065 return false; 23066 } 23067 synchronized(mPackages) { 23068 final PackageParser.Package pkg = mPackages.get(packageName); 23069 if (pkg == null 23070 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23071 UserHandle.getUserId(callingUid))) { 23072 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23073 throw new IllegalArgumentException("Unknown package: " + packageName); 23074 } 23075 IBinder ksh = ks.getToken(); 23076 if (ksh instanceof KeySetHandle) { 23077 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23078 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23079 } 23080 return false; 23081 } 23082 } 23083 23084 private void deletePackageIfUnusedLPr(final String packageName) { 23085 PackageSetting ps = mSettings.mPackages.get(packageName); 23086 if (ps == null) { 23087 return; 23088 } 23089 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23090 // TODO Implement atomic delete if package is unused 23091 // It is currently possible that the package will be deleted even if it is installed 23092 // after this method returns. 23093 mHandler.post(new Runnable() { 23094 public void run() { 23095 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23096 0, PackageManager.DELETE_ALL_USERS); 23097 } 23098 }); 23099 } 23100 } 23101 23102 /** 23103 * Check and throw if the given before/after packages would be considered a 23104 * downgrade. 23105 */ 23106 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23107 throws PackageManagerException { 23108 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23109 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23110 "Update version code " + after.versionCode + " is older than current " 23111 + before.getLongVersionCode()); 23112 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23113 if (after.baseRevisionCode < before.baseRevisionCode) { 23114 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23115 "Update base revision code " + after.baseRevisionCode 23116 + " is older than current " + before.baseRevisionCode); 23117 } 23118 23119 if (!ArrayUtils.isEmpty(after.splitNames)) { 23120 for (int i = 0; i < after.splitNames.length; i++) { 23121 final String splitName = after.splitNames[i]; 23122 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23123 if (j != -1) { 23124 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23125 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23126 "Update split " + splitName + " revision code " 23127 + after.splitRevisionCodes[i] + " is older than current " 23128 + before.splitRevisionCodes[j]); 23129 } 23130 } 23131 } 23132 } 23133 } 23134 } 23135 23136 private static class MoveCallbacks extends Handler { 23137 private static final int MSG_CREATED = 1; 23138 private static final int MSG_STATUS_CHANGED = 2; 23139 23140 private final RemoteCallbackList<IPackageMoveObserver> 23141 mCallbacks = new RemoteCallbackList<>(); 23142 23143 private final SparseIntArray mLastStatus = new SparseIntArray(); 23144 23145 public MoveCallbacks(Looper looper) { 23146 super(looper); 23147 } 23148 23149 public void register(IPackageMoveObserver callback) { 23150 mCallbacks.register(callback); 23151 } 23152 23153 public void unregister(IPackageMoveObserver callback) { 23154 mCallbacks.unregister(callback); 23155 } 23156 23157 @Override 23158 public void handleMessage(Message msg) { 23159 final SomeArgs args = (SomeArgs) msg.obj; 23160 final int n = mCallbacks.beginBroadcast(); 23161 for (int i = 0; i < n; i++) { 23162 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23163 try { 23164 invokeCallback(callback, msg.what, args); 23165 } catch (RemoteException ignored) { 23166 } 23167 } 23168 mCallbacks.finishBroadcast(); 23169 args.recycle(); 23170 } 23171 23172 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23173 throws RemoteException { 23174 switch (what) { 23175 case MSG_CREATED: { 23176 callback.onCreated(args.argi1, (Bundle) args.arg2); 23177 break; 23178 } 23179 case MSG_STATUS_CHANGED: { 23180 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23181 break; 23182 } 23183 } 23184 } 23185 23186 private void notifyCreated(int moveId, Bundle extras) { 23187 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23188 23189 final SomeArgs args = SomeArgs.obtain(); 23190 args.argi1 = moveId; 23191 args.arg2 = extras; 23192 obtainMessage(MSG_CREATED, args).sendToTarget(); 23193 } 23194 23195 private void notifyStatusChanged(int moveId, int status) { 23196 notifyStatusChanged(moveId, status, -1); 23197 } 23198 23199 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23200 Slog.v(TAG, "Move " + moveId + " status " + status); 23201 23202 final SomeArgs args = SomeArgs.obtain(); 23203 args.argi1 = moveId; 23204 args.argi2 = status; 23205 args.arg3 = estMillis; 23206 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23207 23208 synchronized (mLastStatus) { 23209 mLastStatus.put(moveId, status); 23210 } 23211 } 23212 } 23213 23214 private final static class OnPermissionChangeListeners extends Handler { 23215 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23216 23217 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23218 new RemoteCallbackList<>(); 23219 23220 public OnPermissionChangeListeners(Looper looper) { 23221 super(looper); 23222 } 23223 23224 @Override 23225 public void handleMessage(Message msg) { 23226 switch (msg.what) { 23227 case MSG_ON_PERMISSIONS_CHANGED: { 23228 final int uid = msg.arg1; 23229 handleOnPermissionsChanged(uid); 23230 } break; 23231 } 23232 } 23233 23234 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23235 mPermissionListeners.register(listener); 23236 23237 } 23238 23239 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23240 mPermissionListeners.unregister(listener); 23241 } 23242 23243 public void onPermissionsChanged(int uid) { 23244 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23245 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23246 } 23247 } 23248 23249 private void handleOnPermissionsChanged(int uid) { 23250 final int count = mPermissionListeners.beginBroadcast(); 23251 try { 23252 for (int i = 0; i < count; i++) { 23253 IOnPermissionsChangeListener callback = mPermissionListeners 23254 .getBroadcastItem(i); 23255 try { 23256 callback.onPermissionsChanged(uid); 23257 } catch (RemoteException e) { 23258 Log.e(TAG, "Permission listener is dead", e); 23259 } 23260 } 23261 } finally { 23262 mPermissionListeners.finishBroadcast(); 23263 } 23264 } 23265 } 23266 23267 private class PackageManagerNative extends IPackageManagerNative.Stub { 23268 @Override 23269 public String[] getNamesForUids(int[] uids) throws RemoteException { 23270 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23271 // massage results so they can be parsed by the native binder 23272 for (int i = results.length - 1; i >= 0; --i) { 23273 if (results[i] == null) { 23274 results[i] = ""; 23275 } 23276 } 23277 return results; 23278 } 23279 23280 // NB: this differentiates between preloads and sideloads 23281 @Override 23282 public String getInstallerForPackage(String packageName) throws RemoteException { 23283 final String installerName = getInstallerPackageName(packageName); 23284 if (!TextUtils.isEmpty(installerName)) { 23285 return installerName; 23286 } 23287 // differentiate between preload and sideload 23288 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23289 ApplicationInfo appInfo = getApplicationInfo(packageName, 23290 /*flags*/ 0, 23291 /*userId*/ callingUser); 23292 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23293 return "preload"; 23294 } 23295 return ""; 23296 } 23297 23298 @Override 23299 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23300 try { 23301 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23302 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23303 if (pInfo != null) { 23304 return pInfo.getLongVersionCode(); 23305 } 23306 } catch (Exception e) { 23307 } 23308 return 0; 23309 } 23310 } 23311 23312 private class PackageManagerInternalImpl extends PackageManagerInternal { 23313 @Override 23314 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23315 int flagValues, int userId) { 23316 PackageManagerService.this.updatePermissionFlags( 23317 permName, packageName, flagMask, flagValues, userId); 23318 } 23319 23320 @Override 23321 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23322 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23323 } 23324 23325 @Override 23326 public boolean isInstantApp(String packageName, int userId) { 23327 return PackageManagerService.this.isInstantApp(packageName, userId); 23328 } 23329 23330 @Override 23331 public String getInstantAppPackageName(int uid) { 23332 return PackageManagerService.this.getInstantAppPackageName(uid); 23333 } 23334 23335 @Override 23336 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23337 synchronized (mPackages) { 23338 return PackageManagerService.this.filterAppAccessLPr( 23339 (PackageSetting) pkg.mExtras, callingUid, userId); 23340 } 23341 } 23342 23343 @Override 23344 public PackageParser.Package getPackage(String packageName) { 23345 synchronized (mPackages) { 23346 packageName = resolveInternalPackageNameLPr( 23347 packageName, PackageManager.VERSION_CODE_HIGHEST); 23348 return mPackages.get(packageName); 23349 } 23350 } 23351 23352 @Override 23353 public PackageList getPackageList(PackageListObserver observer) { 23354 synchronized (mPackages) { 23355 final int N = mPackages.size(); 23356 final ArrayList<String> list = new ArrayList<>(N); 23357 for (int i = 0; i < N; i++) { 23358 list.add(mPackages.keyAt(i)); 23359 } 23360 final PackageList packageList = new PackageList(list, observer); 23361 if (observer != null) { 23362 mPackageListObservers.add(packageList); 23363 } 23364 return packageList; 23365 } 23366 } 23367 23368 @Override 23369 public void removePackageListObserver(PackageListObserver observer) { 23370 synchronized (mPackages) { 23371 mPackageListObservers.remove(observer); 23372 } 23373 } 23374 23375 @Override 23376 public PackageParser.Package getDisabledPackage(String packageName) { 23377 synchronized (mPackages) { 23378 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23379 return (ps != null) ? ps.pkg : null; 23380 } 23381 } 23382 23383 @Override 23384 public String getKnownPackageName(int knownPackage, int userId) { 23385 switch(knownPackage) { 23386 case PackageManagerInternal.PACKAGE_BROWSER: 23387 return getDefaultBrowserPackageName(userId); 23388 case PackageManagerInternal.PACKAGE_INSTALLER: 23389 return mRequiredInstallerPackage; 23390 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23391 return mSetupWizardPackage; 23392 case PackageManagerInternal.PACKAGE_SYSTEM: 23393 return "android"; 23394 case PackageManagerInternal.PACKAGE_VERIFIER: 23395 return mRequiredVerifierPackage; 23396 } 23397 return null; 23398 } 23399 23400 @Override 23401 public boolean isResolveActivityComponent(ComponentInfo component) { 23402 return mResolveActivity.packageName.equals(component.packageName) 23403 && mResolveActivity.name.equals(component.name); 23404 } 23405 23406 @Override 23407 public void setLocationPackagesProvider(PackagesProvider provider) { 23408 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23409 } 23410 23411 @Override 23412 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23413 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23414 } 23415 23416 @Override 23417 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23418 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23419 } 23420 23421 @Override 23422 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23423 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23424 } 23425 23426 @Override 23427 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23428 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23429 } 23430 23431 @Override 23432 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23433 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23434 } 23435 23436 @Override 23437 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23438 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23439 } 23440 23441 @Override 23442 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23443 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23444 } 23445 23446 @Override 23447 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23448 synchronized (mPackages) { 23449 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23450 } 23451 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23452 } 23453 23454 @Override 23455 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23456 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23457 packageName, userId); 23458 } 23459 23460 @Override 23461 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23462 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23463 packageName, userId); 23464 } 23465 23466 @Override 23467 public void setKeepUninstalledPackages(final List<String> packageList) { 23468 Preconditions.checkNotNull(packageList); 23469 List<String> removedFromList = null; 23470 synchronized (mPackages) { 23471 if (mKeepUninstalledPackages != null) { 23472 final int packagesCount = mKeepUninstalledPackages.size(); 23473 for (int i = 0; i < packagesCount; i++) { 23474 String oldPackage = mKeepUninstalledPackages.get(i); 23475 if (packageList != null && packageList.contains(oldPackage)) { 23476 continue; 23477 } 23478 if (removedFromList == null) { 23479 removedFromList = new ArrayList<>(); 23480 } 23481 removedFromList.add(oldPackage); 23482 } 23483 } 23484 mKeepUninstalledPackages = new ArrayList<>(packageList); 23485 if (removedFromList != null) { 23486 final int removedCount = removedFromList.size(); 23487 for (int i = 0; i < removedCount; i++) { 23488 deletePackageIfUnusedLPr(removedFromList.get(i)); 23489 } 23490 } 23491 } 23492 } 23493 23494 @Override 23495 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23496 synchronized (mPackages) { 23497 return mPermissionManager.isPermissionsReviewRequired( 23498 mPackages.get(packageName), userId); 23499 } 23500 } 23501 23502 @Override 23503 public PackageInfo getPackageInfo( 23504 String packageName, int flags, int filterCallingUid, int userId) { 23505 return PackageManagerService.this 23506 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23507 flags, filterCallingUid, userId); 23508 } 23509 23510 @Override 23511 public int getPackageUid(String packageName, int flags, int userId) { 23512 return PackageManagerService.this 23513 .getPackageUid(packageName, flags, userId); 23514 } 23515 23516 @Override 23517 public ApplicationInfo getApplicationInfo( 23518 String packageName, int flags, int filterCallingUid, int userId) { 23519 return PackageManagerService.this 23520 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23521 } 23522 23523 @Override 23524 public ActivityInfo getActivityInfo( 23525 ComponentName component, int flags, int filterCallingUid, int userId) { 23526 return PackageManagerService.this 23527 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23528 } 23529 23530 @Override 23531 public List<ResolveInfo> queryIntentActivities( 23532 Intent intent, int flags, int filterCallingUid, int userId) { 23533 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23534 return PackageManagerService.this 23535 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23536 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23537 } 23538 23539 @Override 23540 public List<ResolveInfo> queryIntentServices( 23541 Intent intent, int flags, int callingUid, int userId) { 23542 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23543 return PackageManagerService.this 23544 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23545 false); 23546 } 23547 23548 @Override 23549 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23550 int userId) { 23551 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23552 } 23553 23554 @Override 23555 public void setDeviceAndProfileOwnerPackages( 23556 int deviceOwnerUserId, String deviceOwnerPackage, 23557 SparseArray<String> profileOwnerPackages) { 23558 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23559 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23560 } 23561 23562 @Override 23563 public boolean isPackageDataProtected(int userId, String packageName) { 23564 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23565 } 23566 23567 @Override 23568 public boolean isPackageEphemeral(int userId, String packageName) { 23569 synchronized (mPackages) { 23570 final PackageSetting ps = mSettings.mPackages.get(packageName); 23571 return ps != null ? ps.getInstantApp(userId) : false; 23572 } 23573 } 23574 23575 @Override 23576 public boolean wasPackageEverLaunched(String packageName, int userId) { 23577 synchronized (mPackages) { 23578 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23579 } 23580 } 23581 23582 @Override 23583 public void grantRuntimePermission(String packageName, String permName, int userId, 23584 boolean overridePolicy) { 23585 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23586 permName, packageName, overridePolicy, getCallingUid(), userId, 23587 mPermissionCallback); 23588 } 23589 23590 @Override 23591 public void revokeRuntimePermission(String packageName, String permName, int userId, 23592 boolean overridePolicy) { 23593 mPermissionManager.revokeRuntimePermission( 23594 permName, packageName, overridePolicy, getCallingUid(), userId, 23595 mPermissionCallback); 23596 } 23597 23598 @Override 23599 public String getNameForUid(int uid) { 23600 return PackageManagerService.this.getNameForUid(uid); 23601 } 23602 23603 @Override 23604 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23605 Intent origIntent, String resolvedType, String callingPackage, 23606 Bundle verificationBundle, int userId) { 23607 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23608 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23609 userId); 23610 } 23611 23612 @Override 23613 public void grantEphemeralAccess(int userId, Intent intent, 23614 int targetAppId, int ephemeralAppId) { 23615 synchronized (mPackages) { 23616 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23617 targetAppId, ephemeralAppId); 23618 } 23619 } 23620 23621 @Override 23622 public boolean isInstantAppInstallerComponent(ComponentName component) { 23623 synchronized (mPackages) { 23624 return mInstantAppInstallerActivity != null 23625 && mInstantAppInstallerActivity.getComponentName().equals(component); 23626 } 23627 } 23628 23629 @Override 23630 public void pruneInstantApps() { 23631 mInstantAppRegistry.pruneInstantApps(); 23632 } 23633 23634 @Override 23635 public String getSetupWizardPackageName() { 23636 return mSetupWizardPackage; 23637 } 23638 23639 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23640 if (policy != null) { 23641 mExternalSourcesPolicy = policy; 23642 } 23643 } 23644 23645 @Override 23646 public boolean isPackagePersistent(String packageName) { 23647 synchronized (mPackages) { 23648 PackageParser.Package pkg = mPackages.get(packageName); 23649 return pkg != null 23650 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23651 | ApplicationInfo.FLAG_PERSISTENT)) == 23652 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23653 : false; 23654 } 23655 } 23656 23657 @Override 23658 public boolean isLegacySystemApp(Package pkg) { 23659 synchronized (mPackages) { 23660 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23661 return mPromoteSystemApps 23662 && ps.isSystem() 23663 && mExistingSystemPackages.contains(ps.name); 23664 } 23665 } 23666 23667 @Override 23668 public List<PackageInfo> getOverlayPackages(int userId) { 23669 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23670 synchronized (mPackages) { 23671 for (PackageParser.Package p : mPackages.values()) { 23672 if (p.mOverlayTarget != null) { 23673 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23674 if (pkg != null) { 23675 overlayPackages.add(pkg); 23676 } 23677 } 23678 } 23679 } 23680 return overlayPackages; 23681 } 23682 23683 @Override 23684 public List<String> getTargetPackageNames(int userId) { 23685 List<String> targetPackages = new ArrayList<>(); 23686 synchronized (mPackages) { 23687 for (PackageParser.Package p : mPackages.values()) { 23688 if (p.mOverlayTarget == null) { 23689 targetPackages.add(p.packageName); 23690 } 23691 } 23692 } 23693 return targetPackages; 23694 } 23695 23696 @Override 23697 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23698 @Nullable List<String> overlayPackageNames) { 23699 synchronized (mPackages) { 23700 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23701 Slog.e(TAG, "failed to find package " + targetPackageName); 23702 return false; 23703 } 23704 ArrayList<String> overlayPaths = null; 23705 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23706 final int N = overlayPackageNames.size(); 23707 overlayPaths = new ArrayList<>(N); 23708 for (int i = 0; i < N; i++) { 23709 final String packageName = overlayPackageNames.get(i); 23710 final PackageParser.Package pkg = mPackages.get(packageName); 23711 if (pkg == null) { 23712 Slog.e(TAG, "failed to find package " + packageName); 23713 return false; 23714 } 23715 overlayPaths.add(pkg.baseCodePath); 23716 } 23717 } 23718 23719 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23720 ps.setOverlayPaths(overlayPaths, userId); 23721 return true; 23722 } 23723 } 23724 23725 @Override 23726 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23727 int flags, int userId, boolean resolveForStart) { 23728 return resolveIntentInternal( 23729 intent, resolvedType, flags, userId, resolveForStart); 23730 } 23731 23732 @Override 23733 public ResolveInfo resolveService(Intent intent, String resolvedType, 23734 int flags, int userId, int callingUid) { 23735 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23736 } 23737 23738 @Override 23739 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23740 return PackageManagerService.this.resolveContentProviderInternal( 23741 name, flags, userId); 23742 } 23743 23744 @Override 23745 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23746 synchronized (mPackages) { 23747 mIsolatedOwners.put(isolatedUid, ownerUid); 23748 } 23749 } 23750 23751 @Override 23752 public void removeIsolatedUid(int isolatedUid) { 23753 synchronized (mPackages) { 23754 mIsolatedOwners.delete(isolatedUid); 23755 } 23756 } 23757 23758 @Override 23759 public int getUidTargetSdkVersion(int uid) { 23760 synchronized (mPackages) { 23761 return getUidTargetSdkVersionLockedLPr(uid); 23762 } 23763 } 23764 23765 @Override 23766 public int getPackageTargetSdkVersion(String packageName) { 23767 synchronized (mPackages) { 23768 return getPackageTargetSdkVersionLockedLPr(packageName); 23769 } 23770 } 23771 23772 @Override 23773 public boolean canAccessInstantApps(int callingUid, int userId) { 23774 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23775 } 23776 23777 @Override 23778 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23779 synchronized (mPackages) { 23780 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23781 } 23782 } 23783 23784 @Override 23785 public void notifyPackageUse(String packageName, int reason) { 23786 synchronized (mPackages) { 23787 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23788 } 23789 } 23790 } 23791 23792 @Override 23793 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23794 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23795 synchronized (mPackages) { 23796 final long identity = Binder.clearCallingIdentity(); 23797 try { 23798 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23799 packageNames, userId); 23800 } finally { 23801 Binder.restoreCallingIdentity(identity); 23802 } 23803 } 23804 } 23805 23806 @Override 23807 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23808 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23809 synchronized (mPackages) { 23810 final long identity = Binder.clearCallingIdentity(); 23811 try { 23812 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23813 packageNames, userId); 23814 } finally { 23815 Binder.restoreCallingIdentity(identity); 23816 } 23817 } 23818 } 23819 23820 private static void enforceSystemOrPhoneCaller(String tag) { 23821 int callingUid = Binder.getCallingUid(); 23822 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23823 throw new SecurityException( 23824 "Cannot call " + tag + " from UID " + callingUid); 23825 } 23826 } 23827 23828 boolean isHistoricalPackageUsageAvailable() { 23829 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23830 } 23831 23832 /** 23833 * Return a <b>copy</b> of the collection of packages known to the package manager. 23834 * @return A copy of the values of mPackages. 23835 */ 23836 Collection<PackageParser.Package> getPackages() { 23837 synchronized (mPackages) { 23838 return new ArrayList<>(mPackages.values()); 23839 } 23840 } 23841 23842 /** 23843 * Logs process start information (including base APK hash) to the security log. 23844 * @hide 23845 */ 23846 @Override 23847 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23848 String apkFile, int pid) { 23849 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23850 return; 23851 } 23852 if (!SecurityLog.isLoggingEnabled()) { 23853 return; 23854 } 23855 Bundle data = new Bundle(); 23856 data.putLong("startTimestamp", System.currentTimeMillis()); 23857 data.putString("processName", processName); 23858 data.putInt("uid", uid); 23859 data.putString("seinfo", seinfo); 23860 data.putString("apkFile", apkFile); 23861 data.putInt("pid", pid); 23862 Message msg = mProcessLoggingHandler.obtainMessage( 23863 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23864 msg.setData(data); 23865 mProcessLoggingHandler.sendMessage(msg); 23866 } 23867 23868 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23869 return mCompilerStats.getPackageStats(pkgName); 23870 } 23871 23872 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23873 return getOrCreateCompilerPackageStats(pkg.packageName); 23874 } 23875 23876 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23877 return mCompilerStats.getOrCreatePackageStats(pkgName); 23878 } 23879 23880 public void deleteCompilerPackageStats(String pkgName) { 23881 mCompilerStats.deletePackageStats(pkgName); 23882 } 23883 23884 @Override 23885 public int getInstallReason(String packageName, int userId) { 23886 final int callingUid = Binder.getCallingUid(); 23887 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23888 true /* requireFullPermission */, false /* checkShell */, 23889 "get install reason"); 23890 synchronized (mPackages) { 23891 final PackageSetting ps = mSettings.mPackages.get(packageName); 23892 if (filterAppAccessLPr(ps, callingUid, userId)) { 23893 return PackageManager.INSTALL_REASON_UNKNOWN; 23894 } 23895 if (ps != null) { 23896 return ps.getInstallReason(userId); 23897 } 23898 } 23899 return PackageManager.INSTALL_REASON_UNKNOWN; 23900 } 23901 23902 @Override 23903 public boolean canRequestPackageInstalls(String packageName, int userId) { 23904 return canRequestPackageInstallsInternal(packageName, 0, userId, 23905 true /* throwIfPermNotDeclared*/); 23906 } 23907 23908 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23909 boolean throwIfPermNotDeclared) { 23910 int callingUid = Binder.getCallingUid(); 23911 int uid = getPackageUid(packageName, 0, userId); 23912 if (callingUid != uid && callingUid != Process.ROOT_UID 23913 && callingUid != Process.SYSTEM_UID) { 23914 throw new SecurityException( 23915 "Caller uid " + callingUid + " does not own package " + packageName); 23916 } 23917 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23918 if (info == null) { 23919 return false; 23920 } 23921 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23922 return false; 23923 } 23924 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23925 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23926 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23927 if (throwIfPermNotDeclared) { 23928 throw new SecurityException("Need to declare " + appOpPermission 23929 + " to call this api"); 23930 } else { 23931 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23932 return false; 23933 } 23934 } 23935 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23936 return false; 23937 } 23938 if (mExternalSourcesPolicy != null) { 23939 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23940 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23941 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23942 } 23943 } 23944 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23945 } 23946 23947 @Override 23948 public ComponentName getInstantAppResolverSettingsComponent() { 23949 return mInstantAppResolverSettingsComponent; 23950 } 23951 23952 @Override 23953 public ComponentName getInstantAppInstallerComponent() { 23954 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23955 return null; 23956 } 23957 return mInstantAppInstallerActivity == null 23958 ? null : mInstantAppInstallerActivity.getComponentName(); 23959 } 23960 23961 @Override 23962 public String getInstantAppAndroidId(String packageName, int userId) { 23963 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23964 "getInstantAppAndroidId"); 23965 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23966 true /* requireFullPermission */, false /* checkShell */, 23967 "getInstantAppAndroidId"); 23968 // Make sure the target is an Instant App. 23969 if (!isInstantApp(packageName, userId)) { 23970 return null; 23971 } 23972 synchronized (mPackages) { 23973 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23974 } 23975 } 23976 23977 boolean canHaveOatDir(String packageName) { 23978 synchronized (mPackages) { 23979 PackageParser.Package p = mPackages.get(packageName); 23980 if (p == null) { 23981 return false; 23982 } 23983 return p.canHaveOatDir(); 23984 } 23985 } 23986 23987 private String getOatDir(PackageParser.Package pkg) { 23988 if (!pkg.canHaveOatDir()) { 23989 return null; 23990 } 23991 File codePath = new File(pkg.codePath); 23992 if (codePath.isDirectory()) { 23993 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23994 } 23995 return null; 23996 } 23997 23998 void deleteOatArtifactsOfPackage(String packageName) { 23999 final String[] instructionSets; 24000 final List<String> codePaths; 24001 final String oatDir; 24002 final PackageParser.Package pkg; 24003 synchronized (mPackages) { 24004 pkg = mPackages.get(packageName); 24005 } 24006 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24007 codePaths = pkg.getAllCodePaths(); 24008 oatDir = getOatDir(pkg); 24009 24010 for (String codePath : codePaths) { 24011 for (String isa : instructionSets) { 24012 try { 24013 mInstaller.deleteOdex(codePath, isa, oatDir); 24014 } catch (InstallerException e) { 24015 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24016 } 24017 } 24018 } 24019 } 24020 24021 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24022 Set<String> unusedPackages = new HashSet<>(); 24023 long currentTimeInMillis = System.currentTimeMillis(); 24024 synchronized (mPackages) { 24025 for (PackageParser.Package pkg : mPackages.values()) { 24026 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24027 if (ps == null) { 24028 continue; 24029 } 24030 PackageDexUsage.PackageUseInfo packageUseInfo = 24031 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24032 if (PackageManagerServiceUtils 24033 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24034 downgradeTimeThresholdMillis, packageUseInfo, 24035 pkg.getLatestPackageUseTimeInMills(), 24036 pkg.getLatestForegroundPackageUseTimeInMills())) { 24037 unusedPackages.add(pkg.packageName); 24038 } 24039 } 24040 } 24041 return unusedPackages; 24042 } 24043 24044 @Override 24045 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24046 int userId) { 24047 final int callingUid = Binder.getCallingUid(); 24048 final int callingAppId = UserHandle.getAppId(callingUid); 24049 24050 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24051 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24052 24053 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24054 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24055 throw new SecurityException("Caller must have the " 24056 + SET_HARMFUL_APP_WARNINGS + " permission."); 24057 } 24058 24059 synchronized(mPackages) { 24060 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24061 scheduleWritePackageRestrictionsLocked(userId); 24062 } 24063 } 24064 24065 @Nullable 24066 @Override 24067 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24068 final int callingUid = Binder.getCallingUid(); 24069 final int callingAppId = UserHandle.getAppId(callingUid); 24070 24071 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24072 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24073 24074 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24075 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24076 throw new SecurityException("Caller must have the " 24077 + SET_HARMFUL_APP_WARNINGS + " permission."); 24078 } 24079 24080 synchronized(mPackages) { 24081 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24082 } 24083 } 24084} 24085 24086interface PackageSender { 24087 /** 24088 * @param userIds User IDs where the action occurred on a full application 24089 * @param instantUserIds User IDs where the action occurred on an instant application 24090 */ 24091 void sendPackageBroadcast(final String action, final String pkg, 24092 final Bundle extras, final int flags, final String targetPkg, 24093 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24094 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24095 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24096 void notifyPackageAdded(String packageName); 24097 void notifyPackageRemoved(String packageName); 24098} 24099